Google News
logo
Java Program to Check Whether a Number is Even or Odd
Once the entered number is stored in the variable num, we are using if..else statement to check if the number is perfectly divisible by 2 or not. Based on the outcome, it is executing if block (if condition true) or else block (if condition is false).

Here is an example Java program to check whether a number is even or odd :
Program :
import java.util.Scanner;

public class EvenOdd {

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

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

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


In this program, we use the Scanner class to read a number input by the user. We then check whether the number is even or odd using the modulus operator %. If the number is divisible by 2 with no remainder, it is even, otherwise it is odd. We then print out the appropriate message indicating whether the number is even or odd.

Output :
Enter a number: 32
32 is even.
Enter a number: 37
37 is odd.


Program to check even odd number using ternary operator

A ternary operator is a one liner replacement of an if-else statement. In this program, we are using the same logic that we have seen above, however instead of using if..else, we are using a ternary operator here.
Program :
import java.util.Scanner;
public class JavaExample {

  public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

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

    //checking if else using ternary operator
    //ternary operator syntax: condition ? expression1 : expression2
    // if condition is true, expression1 executes else expression2
    String evenOrOdd = (num % 2 == 0) ? "even number" : "odd number";

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

  }
}
Output :
Enter a number: 17
17 is an odd number
Enter a number: 24
24 is an even number