SteelReed

Search

Search posts, questions…

Java CoreQuestion 6 / 43

Junior

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:

  1. 7 / 2 is 3; for 3.5 write 7 / 2.0.
  2. -7 % 2 is -1; for a non-negative result use Math.floorMod.
  3. && 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.