How to Check Even or Odd in Java

The following sample Java program shows how the modulus operator in Java can be used to check whether a given number is even or odd. The following program reads a number from the console using the Scanner class and System.in input stream,

import java.util.Scanner;

// Java program to check whether a number is even or odd.
public class EvenOrOdd {
    public static void main(String[] args) {
        System.out.println("Please enter a number");
        Scanner scanner = new Scanner(System.in);

        int input = scanner.nextInt();

        if (input % 2 == 0) {
            System.out.println(input + " is an even number");
        } else {
            System.out.println(input + " is an odd number");
        }

        scanner.close();
    }
}

Compile the program,

javac EvenOrOdd.java

Run the program

java EvenOrOdd

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply