Java Program to Check Whether a Number is Even or Odd

Write a program to check whether a number is even or odd.

Using If…Else statement

import java.util.Scanner;

public class CheckEvenOdd {

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

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

        if(num % 2 == 0)
            System.out.println(num + " is an even number");
        else
            System.out.println(num + " is an odd number");
    }
}
Output
Enter any number: 14
14 is an even number

A number which when divided by 2 gives reminder as 0, is an even number. otherwise, its an odd number.

Now, here we are asking the user to enter a random number. Scanner reader = new Scanner(System.in)

Here, we are using if…else statement to determine if the number is even or odd.

We can also check this using ternary operators as shown below.

Using Ternary Operator

import java.util.Scanner;

public class CheckEvenOdd {

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

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

        String evenOrOdd = (num % 2 == 0) ? "even" : "odd";

        System.out.println(num + " is " + evenOrOdd);

    }
}
Output
Enter any number: 15
15 is odd

Leave a Reply