The remainder operator %
% gives the remainder of a division between whole numbers: 17 % 5 is 2, because 17 is three fives and 2 left over.
System.out.println(17 % 5);
System.out.println(12 % 4);
System.out.println(7 % 10);
2
0
7A remainder of 0 means the division comes out even, so % is the way to test whether a number divides by another. The most common case is even and odd: a number is even when number % 2 == 0.
Negative numbers
In Java the remainder has the same sign as the number being divided, so -7 % 2 is -1, not 1:
System.out.println(-7 % 2);
System.out.println(-8 % 2);
-1
0That's why "is it odd?" is safest written as number % 2 != 0: number % 2 == 1 is false for odd negative numbers.