Check Even or Odd in Java
Problem
A number is even when dividing it by 2 leaves no remainder, and odd otherwise.
Given an integer, determine whether it is even or odd.
Java Program
public class EvenOrOdd {
public static void main(String[] args) {
int n = 17;
if (n % 2 == 0) {
System.out.println(n + " is even");
} else {
System.out.println(n + " is odd");
}
}
}Output
Core Logic
Checking the remainder left over after dividing by 2 separates even numbers from odd ones directly.
- 1
n % 2 == 0computes the remainder ofndivided by 2 and compares it to zero. - 2A remainder of 0 means the number divides evenly, so it's reported as even.
- 3Any other remainder — which for the modulo operator can only be 1 or -1 — means the number is odd.
n = 17, 17 % 2 is 1, not 0, so the number is reported as odd.Key Point: The remainder from % is the only thing this check needs — there's no separate case for negative numbers, since a nonzero remainder always means odd regardless of sign.
Key Concepts
Approach 2: Using Bitwise AND
public class EvenOrOddBitwise {
public static void main(String[] args) {
int n = 17;
// Checks only the lowest bit — 1 means odd, 0 means even
boolean isEven = (n & 1) == 0;
System.out.println(n + (isEven ? " is even" : " is odd"));
}
}
Output
Core Logic
Inspecting only the lowest bit of a number's binary representation reveals its parity without needing division at all.
- 1
n & 1masks out every bit ofnexcept the lowest one. - 2That lowest bit is
0for every even number and1for every odd number, by definition of binary place value. - 3Comparing the masked result to
0gives the same true/false answer the modulo check produces.
10001; masking with 1 keeps only the final bit, which is 1, so isEven is false and the number is reported as odd.Key Point: In Java, (n & 1) == 0 agrees with n % 2 == 0 even for negative numbers, since Java's two's-complement representation keeps that lowest bit accurate regardless of sign — that isn't guaranteed in every language, but it holds here.