Arithmetic operators in Java
+ - * / % on numbers.
The five operators
Java has five arithmetic operators: + add, - subtract, * multiply, / divide and % remainder. They work on every numeric type.
int a = 10, b = 4;
a + b // 14
a - b // 6
a * b // 40
a / b // 2 (more on this soon!)
a % b // 2% is the remainder
% gives what's left over after division. 10 % 3: 3 fits into 10 three times (9), leaving 1. 10 % 4 leaves 2. It's perfect for even/odd checks and wrapping around.
* / % before + -
Just like school math, *, / and % bind tighter than + and -. Operators on the same level go left to right. Parentheses override everything.
7 + 3 * 2 // 13
(7 + 3) * 2 // 20
1 + 2 * 3 % 4 // 1 + ((2*3) % 4) = 3Your turn
What does this print?
System.out.println(2 + 4 * 3 % 5);4142
Show the answer
* and % share a level and go left to right: 4 * 3 = 12, then 12 % 5 = 2. Finally 2 + 2 = 4.
Your turn
Can you take a remainder of a decimal?
System.out.println(9.5 % 3);0.50Compile error
Show the answer
Yes! % works on doubles too. 3 fits into 9.5 three times (9), leaving 0.5.
Say what you mean
int cost = price + shipping * 2;* goes first, so only the shipping is doubled.
int cost = (price + shipping) * 2;Parentheses add first, then double the whole order.
In real projects
Precedence slips hide in pricing, discounts and game physics, and they compile perfectly. Professional code adds parentheses whenever a reader might hesitate, because they cost nothing and prevent misreadings.
Key takeaways
- + - * / % work on all numeric types
- * / % before + -, then left to right
- % is remainder: 10 % 3 is 1
- Parentheses override precedence
% runs clocks and calendars: (hour + 5) % 12 wraps around a clock face, and day % 7 cycles through the days of the week.
Practice questions
What does this print?
System.out.println(7 + 3 * 2);- 20
- 16
- 12
- 13
Check your answer
13. * binds tighter than +, so 3 * 2 = 6 is computed first, then 7 + 6 = 13.
What does this print?
System.out.println(7.5 % 2);- 1
- 3.75
- Compile error
- 1.5
Check your answer
1.5. % also works on doubles: 2 fits into 7.5 three times (6), leaving 1.5.