Control Flow
Java Program to Check Even or Odd Number
Learn to check if a number is even or odd in Java using modulus operator. Complete program with examples and explanations of different approaches.
Problem Description
Write a Java program to check whether a given number is Even or Odd.
- Even Number: A number perfectly divisible by 2 (remainder is 0). Examples: 2, 4, 6, 8, 10.
- Odd Number: A number not divisible by 2 (remainder is 1). Examples: 1, 3, 5, 7, 9.
Code
import java.util.Scanner;
public class CheckEvenOdd {
public static void main(String[] args) {
int num;
System.out.print("Enter an Integer number: ");
// The input provided by user is stored in num
Scanner input = new Scanner(System.in);
num = input.nextInt();
/* If number is divisible by 2 then it's an even number
* else odd number */
if (num % 2 == 0) {
System.out.println(num + " is an even number");
} else {
System.out.println(num + " is an odd number");
}
input.close();
}
}Output
Case 1:
Enter an Integer number: 78
78 is an even numberCase 2:
Enter an Integer number: 77
77 is an odd numberExplanation
Scanner: Used to take input from the user.%(Modulus Operator): This operator returns the remainder of a division.num % 2dividesnumby 2.- If the remainder is
0, the number is even. - If the remainder is
1(or -1 for negative odd numbers), the number is odd.
if-else: Checks the condition. If true, prints "Even"; otherwise, prints "Odd".
Try Yourself
- Zero Check: Run the program with
0. Is it even or odd? - Negative Numbers: Try
-4and-5. Does the logic hold? - Ternary Operator: Can you rewrite the
if-elseblock using a single line?String result = (num % 2 == 0) ? "Even" : "Odd"; - Bitwise Challenge: Try checking for odd/even using the bitwise AND operator (
&). Hint:(num & 1) == 0means even. - Looping: Modify the program to check numbers from 1 to 10 automatically.
