Introduction
Determining whether a number is even or odd is a fundamental programming task. An even number is divisible by 2 without a remainder, while an odd number has a remainder of 1 when divided by 2. This guide will walk you through writing a Java program that checks if a given number is even or odd.
Problem Statement
Create a Java program that:
- Prompts the user to enter a number.
- Determines whether the number is even or odd.
- Displays the result.
Example:
- 
Input: 4
- 
Output: "4 is an even number"
- 
Input: 7
- 
Output: "7 is an odd number"
Solution Steps
- Read the Number: Use the Scannerclass to take the number as input from the user.
- Check if the Number is Even or Odd: Use the modulus operator (%) to determine if the number is divisible by 2.
- Display the Result: Print whether the number is even or odd.
Java Program
// Java Program to Check if a Number is Even or Odd
// Author: https://www.rameshfadatare.com/
import java.util.Scanner;
public class EvenOddChecker {
    public static void main(String[] args) {
        // Step 1: Read the number from the user
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Enter a number: ");
            int number = scanner.nextInt();
            
            // Step 2: Check if the number is even or odd
            if (number % 2 == 0) {
                System.out.println(number + " is an even number.");
            } else {
                System.out.println(number + " is an odd number.");
            }
        }
    }
}
Explanation
Step 1: Read the Number
- The Scannerclass is used to read an integer input from the user. ThenextInt()method captures the input number.
Step 2: Check if the Number is Even or Odd
- The modulus operator (%) is used to check the remainder when the number is divided by 2.- If number % 2 == 0, the number is even.
- If number % 2 != 0, the number is odd.
 
- If 
Step 3: Display the Result
- The program prints whether the number is even or odd using System.out.println().
Output Example
Example 1:
Enter a number: 4
4 is an even number.
Example 2:
Enter a number: 7
7 is an odd number.
Conclusion
This Java program demonstrates how to determine whether a given number is even or odd. It covers essential concepts such as the modulus operator, conditional statements, and user input handling, making it a valuable exercise for beginners learning Java programming.