How to Check Even or Odd Number in Java
The Challenge
Determine if a number is even or odd - a fundamental programming task!
Solution
Using Modulus Operator (%)
public class Main {
public static void main(String[] args) {
int number = 7;
if (number % 2 == 0) {
System.out.println(number + " is even");
} else {
System.out.println(number + " is odd");
}
}
}
// Output: 7 is oddUsing Ternary Operator
int number = 10;
String result = (number % 2 == 0) ? "even" : "odd";
System.out.println(number + " is " + result);
// Output: 10 is evenUsing Bitwise AND
int number = 15;
if ((number & 1) == 0) {
System.out.println(number + " is even");
} else {
System.out.println(number + " is odd");
}
// Output: 15 is oddHow It Works
The modulus operator % returns the remainder of division. Even numbers are divisible by 2 with no remainder (remainder = 0), while odd numbers have a remainder of 1.
- 10 % 2 = 0 Even
- 7 % 2 = 1 Odd
Did You Know?
The bitwise AND method (number & 1) is faster than modulus because it directly checks the least significant bit. If it's 0, the number is even; if it's 1, the number is odd!
Pro Tip
For readability, stick with the modulus operator %. For performance-critical code, use bitwise AND &.
Real-World Use Cases
- Pagination: Alternate row colors in tables
- Scheduling: Determine alternating shifts
- Games: Determine player turns
- Data validation: Check if input meets criteria
›Short versionOpen if you only have a minute.
- An int is even when n % 2 == 0. Zero is even.
- In Java the remainder takes the sign of the dividend, so a negative odd value yields -1, not 1.
- Test odd with n % 2 != 0. The check n % 2 == 1 misses every negative odd int.
- Parity is a property of integers. Do not ask it of a double.
Even or odd
Determine whether an integer is divisible by 2.
Working approach
- Use n % 2 == 0 for the even test.
- Return a boolean from a method such as isEven so callers do not reimplement the sign rule.
- Parse input outside the test. The test itself is one expression.
Walk the sample
- Input 7
- 7 % 2 leaves 1
- The remainder is not 0, so 7 is odd
The trap
n % 2 == 1 is the check that fails for negatives. -3 % 2 is -1 in Java, so the number is odd and the condition is still false.
static boolean isEven(int n) {
return n % 2 == 0;
}
static boolean isOdd(int n) {
return n % 2 != 0; // not == 1; negatives leave a remainder of -1
}Is -4 even, and what does -3 % 2 produce?
-4 % 2 is 0, so -4 is even. Zero is even for the same reason.
-3 % 2 is -1. A test written as == 1 classifies every negative odd integer as even.
Time O(1), space O(1).
Easy to get wrong
- Writing n % 2 == 1 and then feeding it a negative odd value.
- Using a floating-point value in a parity test.