What are the common Java operator traps: integer division, %, a++ vs ++a, && vs &, bitwise operators?
Short answer
Dividing two integers gives an integer (the fraction is cut). % takes the sign of the dividend. a++ returns the old value, ++a the new one.
| Expression | Result | Why |
|---|---|---|
7 / 2 |
3 |
integer division, truncates toward 0 |
-7 % 2 |
-1 |
% is remainder, follows the dividend's sign |
int x = a++; (a = 5) |
x = 5, a = 6 |
returns the old value, then increments |
obj != null & obj.isActive() |
NPE when obj is null |
& does not short-circuit |
3 points to say:
7 / 2is3; for3.5write7 / 2.0.-7 % 2is-1; for a non-negative result useMath.floorMod.&&stops early,&always evaluates both sides.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.