Home Java Check a Number is Even or Odd in Java

Check a Number is Even or Odd in Java

In this article we look at how to check if a number is odd or even in Java

Example

In the program,  we first create a Scanner object, and then a reader is created to read a number from the user’s keyboard.

The entered number is then stored in a variable number.

To check whether the number  is even or odd, we calculate its remainder using the % operator and check if it is divisible by 2 or not.

For this, we use if…else statement in Java. We then display a suitable message whether its odd or even.

import java.util.Scanner;

public class JavaApplication1 
{
    public static void main(String[] args) 
    {
        Scanner reader = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int number = reader.nextInt();

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

 

A couple of test runs

run:
Enter a number: 9
9 is odd

run:
Enter a number: 10
10 is even

You may also like