- Reason
10 % 2 == 0
Check Even Number in Java
What you'll learn
- How
n % 2 == 0checks parity in Java. - How to write reusable methods for one value and for ranges.
- Common interview points like zero and negative numbers.
Prerequisites
Java operators, methods, loops, and integer types.
- Understand that an even integer is divisible by
2. - Know Java modulo syntax:
n % 2.
Math definition
An integer n is even when n = 2k for some integer k. Equivalent test: n % 2 == 0.
Intuition
- Reason
11 % 2 == 1
Live preview
Type an integer to test parity using the same rule as Java code examples.
Algorithm
Goal: return true if n is divisible by 2.
Compute n % 2
If remainder is 0, the number is even; otherwise odd.
Reuse for ranges
For each i in [start, end], apply the same check and print matches.
📜 Pseudocode
function isEven(n):
return (n mod 2) == 0
function printEvensInRange(start, end):
for i from start to end:
if isEven(i):
output iCheck a single number
public class Main {
static boolean isEven(int number) {
return number % 2 == 0;
}
public static void main(String[] args) {
int number = 10;
if (isEven(number)) {
System.out.println(number + " is an even number.");
} else {
System.out.println(number + " is not an even number.");
}
}
}10 is an even number.
Print even numbers in range
public class Main {
static boolean isEven(int n) {
return n % 2 == 0;
}
static void printEvenNumbers(int start, int end) {
System.out.println("Even numbers in the range " + start + " to " + end + ":");
for (int i = start; i <= end; i++) {
if (isEven(i)) {
System.out.print(i + " ");
}
}
System.out.println();
}
public static void main(String[] args) {
printEvenNumbers(1, 10);
}
}Even numbers in the range 1 to 10: 2 4 6 8 10
Optimization
Step by two: align to first even and increment by 2 when printing ranges.
Bitwise alternative: (n & 1) == 0 also checks parity for Java integers.
🔄 Input / output examples
| Input | Output meaning |
|---|---|
0 | Even |
10 | Even |
11 | Odd |
-4 | Even |
Edge cases and pitfalls
n = 0
Zero is even because it is divisible by two.
n < 0
Negative values can still be even, such as -4.
Bounds
Use inclusive loops carefully to avoid missing the end value.
⏱️ Time and space complexity
| Operation | Time | Extra space |
|---|---|---|
isEven(n) | O(1) | O(1) |
Scan [start, end] | O(end - start + 1) | O(1) |
Summary
- Use
n % 2 == 0to test even numbers in Java. - Reuse the same predicate for single values and full ranges.
- Remember that
0and negative multiples of 2 are even.
❓ FAQ
Zero is even because 0 = 2 * 0. So n % 2 == 0 is true for n = 0.
8 people found this page helpful
