๐ข Java Program to Check Even or Odd Number โ Explained with Examples
๐งฒ Introduction
Checking if a number is even or odd is one of the first and most useful exercises for beginners in Java. It’s commonly used in loops, game logic, condition checks, and data validation.
By the end of this tutorial, you’ll learn:
- โ How to determine if a number is even or odd in Java
- โ
Use
Scanner
to take input from the user - โ
Apply
if...else
logic with modulo operator
๐งฎ Rule: Even or Odd Number Logic
- A number is even if divisible by 2 (i.e.,
number % 2 == 0
) - Otherwise, it is odd
๐ป Java Program โ Hardcoded Value
public class EvenOddCheck {
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.");
}
}
}
โ Explanation:
number % 2
returns the remainder.- If remainder is
0
, itโs even; else itโs odd.
๐ฅ Java Program โ Using Scanner Input
import java.util.Scanner;
public class EvenOddInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
if (num % 2 == 0) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}
scanner.close();
}
}
โ Explanation:
Scanner
reads user input.%
(modulus) checks divisibility by 2.
๐ Java Method โ Reusable Function
public class EvenOddUtil {
public static boolean isEven(int num) {
return num % 2 == 0;
}
public static void main(String[] args) {
int number = 12;
if (isEven(number)) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
}
}
โ Use this method in projects or logic-based games for clean code.
โ ๏ธ Edge Case Warning
- Works with positive, negative, and zero
0
is considered even in Java
๐ Example Output
Enter a number: 9
9 is odd.
Enter a number: 0
0 is even.
๐ Summary
In this article, youโve learned:
- โ How to check even or odd numbers in Java
- โ
Use input from users with
Scanner
- โ Write reusable and optimized methods
This logic is foundational for loops, conditional branching, and algorithm design.
โ FAQ โ Even or Odd Number in Java
โCan this program handle negative numbers?
โ
Yes! -4 % 2 == 0
, so negative even/odd numbers work just fine.
โHow can I do this with a ternary operator?
String result = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(num + " is " + result);
โ This makes the code cleaner and shorter.
Share Now :