🎉 Special Offer !    Code: GET300OFF    Flat ₹300 OFF on every Java Course
Grab Deal 🚀

WAP to Check Even or Odd Number in Java  


Logical Steps:
  • To check the number is even or odd, follow these steps:
    1. Take a number.
    2. Check if the number is divisible by 2:
      • Use the modulus (%) operator to divide the number by 2.
      • If the remainder is 0, the number is even.
      • Otherwise, it is odd.
    3. Use an if-else statement for the condition:
      • If the remainder is 0, print that the number is even.
      • Else, print that the number is odd.
    4. Print the result.
Program:
  • Below is the simple program:
    public class CheckEvenOddNo
    {
        public static void main(String[] args)
        {
            int number = 31;
    
            // Check if the number is even or odd using conditional logic
            if(number % 2 == 0)
            {
                System.out.println(number + " is an even number.");
            }
            else
            {
                System.out.println(number + " is an odd number.");
            }
        }
    }
    Output:
    31 is an odd number.
  • Below is the program by taking user input:
    import java.util.Scanner;
    
    public class CheckEvenOddNo
    {
        public static void main(String[] args)
        {
            // Import Scanner Class to take user input
            Scanner scanner = new Scanner(System.in);
    
            // Take input from the user
            System.out.print("Enter a number: ");
            int number = scanner.nextInt();
    
            // Check if the number is even or odd using conditional logic
            if(number % 2 == 0)
            {
                System.out.println(number + " is an even number.");
            }
            else
            {
                System.out.println(number + " is an odd number.");
            }
    
            // Close the scanner to release resources
            scanner.close();
        }
    }
    Output:
    Enter a number: 26
    26 is an even number.
Program Explanation:
  • Import Scanner Class:
    • The Scanner class is imported to take user input.
  • Declare a Variable:
    • An integer variable (number) is declared to store the user’s input.
  • Take Input:
    • The program prompts the user to enter an integer, and scanner.nextInt() reads the input and stores it in the number variable.
  • Comparison Logic:
    • The if condition checks if number % 2 is equal to 0. If true, it means the number is divisible by 2 and is an even number.
    • Otherwise, the number is odd.
  • Display the Result:
    • The program prints a message to indicate whether the number is even or odd.
  • Close Scanner:
    • The scanner.close() method is used to close the input stream and release resources.