Java for Beginners · Module 3: Operators
🎯 What Is an Operator?
An operator is a symbol that tells Java to do a calculation or a comparison. The values it works on are called operands. In a + b, the + is the operator and a and b are the operands.
1️⃣ Arithmetic Operators
| Operator | Name | Example (a = 17, b = 5) | Result |
+ | addition | a + b | 22 |
- | subtraction | a - b | 12 |
* | multiplication | a * b | 85 |
/ | division (int ÷ int drops fraction) | a / b | 3 |
% | remainder (modulus) | a % b | 2 |
Figure 1: The five arithmetic operators.
Program 1: The five operators
public class ArithDemo {
public static void main(String[] args) {
int a = 17, b = 5;
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
System.out.println("17.0 / 5 = " + (17.0 / 5));
System.out.println("-17 / 5 = " + (-17 / 5));
System.out.println("-17 % 5 = " + (-17 % 5));
System.out.println("7.5 % 2 = " + (7.5 % 2));
}
}
a + b = 22
a – b = 12
a * b = 85
a / b = 3
a % b = 2
17.0 / 5 = 3.4
-17 / 5 = -3
-17 % 5 = -2
7.5 % 2 = 1.5
17 / 5is 3, because both numbers areint. The fraction is dropped (Lesson 9). Using17.0gives 3.4.17 % 5is the remainder: 17 = 3 × 5 + 2.- For negative numbers, division moves towards zero (-17 / 5 is -3), and the remainder takes the sign of the left number (-17 % 5 is -2).
%also works on decimals: 7.5 % 2 is 1.5.
2️⃣ Real Uses of / and %
| Task | Expression | Result |
| 135 minutes to hours and minutes | 135 / 60 and 135 % 60 | 2 h and 15 min |
| Last digit of 4728 | 4728 % 10 | 8 |
| Remove last digit | 4728 / 10 | 472 |
| Even or odd | n % 2 | 0 = even, 1 = odd |
| Wrap around a week | (day + 10) % 7 | day 3 + 10 days = day 6 |
Figure 4: Where / and % are used in real programs.
public class RealUse {
public static void main(String[] args) {
int totalMinutes = 135;
int hours = totalMinutes / 60;
int minutes = totalMinutes % 60;
System.out.println(totalMinutes + " minutes = " + hours + " h " + minutes + " min");
int number = 4728;
int lastDigit = number % 10;
int rest = number / 10;
System.out.println("last digit of " + number + " = " + lastDigit + ", remaining = " + rest);
int day = 3;
int after = (day + 10) % 7;
System.out.println("10 days after day " + day + " is day " + after);
int sumSq = 0;
for (int k = 1; k <= 3; k++) sumSq += k * k;
System.out.println("1+4+9 = " + sumSq);
}
}
135 minutes = 2 h 15 min
last digit of 4728 = 8, remaining = 472
10 days after day 3 is day 6
1+4+9 = 14
- The pair
/and%splits a number into a quotient and a remainder, which is how time, digits and cycles are handled. - Repeating
% 10and/ 10pulls apart every digit of a number. You will use this in many practice programs. - The
forloop on the last lines is covered in Lesson 19.
3️⃣ Increment and Decrement: ++ and —
x++ is a short way to write x = x + 1, and x-- means x = x - 1. The position of the symbol matters when you use the result in the same line.
y = x++POST: use x, then add 1
q = ++pPRE: add 1, then use p
Figure 2: Post-increment uses the old value, pre-increment uses the new one.
public class IncDec {
public static void main(String[] args) {
int x = 5;
int y = x++; // use x, then increase
System.out.println("after y = x++ : x = " + x + ", y = " + y);
int p = 5;
int q = ++p; // increase p, then use
System.out.println("after q = ++p : p = " + p + ", q = " + q);
int n = 10;
n--;
--n;
System.out.println("n after two decrements = " + n);
int i = 3;
int r = i++ + ++i;
System.out.println("i++ + ++i with i=3 -> r = " + r + ", i = " + i);
}
}
after y = x++ : x = 6, y = 5
after q = ++p : p = 6, q = 6
n after two decrements = 8
i++ + ++i with i=3 -> r = 8, i = 5
- Post (
x++): y gets the old value 5, and x becomes 6 afterwards. - Pre (
++p): p becomes 6 first, and q gets 6. - On a line by itself,
n--and--ndo exactly the same thing. - In the last line,
i++gives 3 (then i is 4), and++imakes i 5 and gives 5. So 3 + 5 = 8. Code like this is hard to read, so avoid it. Use ++ and — on their own line.
4️⃣ Compound Assignment Operators
| Long form | Short form | If score = 50 |
score = score + 10 | score += 10 | 60 |
score = score - 5 | score -= 5 | 45 |
score = score * 2 | score *= 2 | 100 |
score = score / 4 | score /= 4 | 12 |
score = score % 7 | score %= 7 | 1 |
Figure 3: Compound assignment operators as short forms.
public class Compound {
public static void main(String[] args) {
int score = 50;
score += 10;
System.out.println("score += 10 : " + score);
score -= 5;
System.out.println("score -= 5 : " + score);
score *= 2;
System.out.println("score *= 2 : " + score);
score /= 4;
System.out.println("score /= 4 : " + score);
score %= 7;
System.out.println("score %= 7 : " + score);
}
}
score += 10 : 60
score -= 5 : 55
score *= 2 : 110
score /= 4 : 27
score %= 7 : 6
- Each step builds on the value from the step before: 50, 60, 55, 110, then 110 / 4 = 27 (integer division), and 27 % 7 = 6.
- Compound operators also include a hidden cast, which is why
byte b += 1is allowed (Lesson 9).
5️⃣ Dividing by Zero
Dividing by zero behaves differently for integers and decimals.
public class DivZero {
public static void main(String[] args) {
System.out.println("5.0 / 0 = " + (5.0 / 0));
System.out.println("-5.0 / 0 = " + (-5.0 / 0));
System.out.println("0.0 / 0 = " + (0.0 / 0));
int zero = 0;
System.out.println(10 / zero);
}
}
5.0 / 0 = Infinity
-5.0 / 0 = -Infinity
0.0 / 0 = NaN
Exception in thread “main” java.lang.ArithmeticException: / by zero
at DivZero.main(DivZero.java:7)
- Decimals give
Infinity,-InfinityorNaN(“not a number”) and the program carries on. - Whole numbers throw an
ArithmeticExceptionand the program stops. Always check the divisor before dividing.
6️⃣ Errors Beginners Meet
Using ++ on something that is not a variable
public class Bad2 {
public static void main(String[] args) {
int a = 10;
5++;
System.out.println(a);
}
}
Bad2.java:4: error: unexpected type
5++;
^
required: variable
found: value
1 error
++changes a variable’s stored value. The literal 5 cannot be changed.
Applying ++ twice
public class Bad1 {
public static void main(String[] args) {
int x = 5;
int y = x++ ++;
System.out.println(y);
}
}
Bad1.java:4: error: unexpected type
int y = x++ ++;
^
required: variable
found: value
1 error
x++produces a value, not a variable, so a second++has nothing to change.
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
double avg = 7 / 2; | Integer division gives 3.0 | Write 7 / 2.0 |
Confusing x++ with ++x in an expression | Different value used | Use them on their own line |
Dividing an int by 0 | ArithmeticException | Check the divisor first |
Writing x =+ 5 instead of x += 5 | Assigns +5, no addition | Put the operator first: += |
Using ^ for power | ^ is XOR, not power | Use Math.pow(2, 3) |
Writing i = i++; | i keeps its old value | Just write i++; |
❓ Frequently Asked Questions
Q1. What does % do with decimals?
It gives the remainder too: 7.5 % 2 is 1.5.
Q2. Is there a power operator?
No. Use Math.pow(base, exponent), which returns a double.
Q3. Can ++ be used on a double?
Yes, d++ adds 1.0. It also works on char, which moves to the next letter.
Q4. Which is faster, x++ or x = x + 1?
No difference. Use whichever reads better.
✅ Key Takeaways
- Arithmetic operators:
+ - * / %. int / intdrops the fraction.%gives the remainder.x++uses the old value then adds 1.++xadds 1 then uses the new value.+=,-=,*=,/=,%=are short forms that update a variable.- Integer division by zero throws an exception. Decimal division by zero gives Infinity or NaN.
🎓 Practice questions: (1) Write a program to convert 5000 seconds into hours, minutes and seconds. (2) Find the sum of the digits of 4728 using % and /. (3) What are the values of x and y afterint x = 4; int y = x++ + x;? (4) Why does-17 % 5give -2? (5) Write a program that checks whether a number is even or odd using %.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java