You can check whether an integer is even or odd using the remainder operator (%).
An even number has a remainder of zero when divided by two. An odd number has a nonzero remainder.
Source code
public class EvenOddExample {
public static void main(String[] args) {
int number = 27;
if (number % 2 == 0) {
IO.println(number + " is even.");
} else {
IO.println(number + " is odd.");
}
}
}
Explanation
The variable number stores the integer to check:
int number = 27;
The % operator returns the remainder after division. The following expression checks whether dividing number by two leaves a remainder of zero:
number % 2 == 0
If the condition is true, the program prints that the number is even. Otherwise, it prints that the number is odd.
For 27, the remainder is 1, so the program runs the else block.
This check also works with negative integers and zero:
| Number | Remainder when divided by 2 | Result |
|---|---|---|
28 |
0 |
Even |
27 |
1 |
Odd |
-28 |
0 |
Even |
-27 |
-1 |
Odd |
0 |
0 |
Even |
To check directly for an odd number, use number % 2 != 0. Checking for a remainder of 1 would miss negative odd numbers.
The program displays the result using IO.println(), which is available in Java 25. No import is required for java.lang.IO.
Run the example
Compile and run the file:
javac EvenOddExample.java
java EvenOddExample
Output
27 is odd.
Change number to 28 and run the program again:
28 is even.
