Java Program to Check Whether a Number is Even or Odd

In this program, you’ll learn to check if a number entered by an user is even or odd. This will be done using if…else statement and ternary operator in Java.

Example 1: Check whether a number is even or odd using if…else statement

  1. import java.util.Scanner;
  2. public class EvenOdd {
  3. public static void main(String[] args) {
  4. Scanner reader = new Scanner(System.in);
  5. System.out.print("Enter a number: ");
  6. int num = reader.nextInt();
  7. if(num % 2 == 0)
  8. System.out.println(num + " is even");
  9. else
  10. System.out.println(num + " is odd");
  11. }
  12. }

When you run the program, the output will be:

Enter a number: 12
12 is even

In the above program, a Scanner object, reader is created to read a number from the user’s keyboard. The entered number is then stored in a variable num.

Now, to check whether num is even or odd, we calculate its remainder using % operator and check if it is divisible by 2 or not.

For this, we use if...else statement in Java. If num is divisible by 2, we print num is even. Else, we print num is odd.

We can also check if num is even or odd by using ternary operator in Java.


Example 2: Check whether a number is even or odd using ternary operator

  1. import java.util.Scanner;
  2. public class EvenOdd {
  3. public static void main(String[] args) {
  4. Scanner reader = new Scanner(System.in);
  5. System.out.print("Enter a number: ");
  6. int num = reader.nextInt();
  7. String evenOdd = (num % 2 == 0) ? "even" : "odd";
  8. System.out.println(num + " is " + evenOdd);
  9. }
  10. }

When you run the program, the output will be:

Enter a number: 13
13 is odd

In the above program, we’ve replaced if...else statement with ternary operator (? :).

Here, if num is divisible by 2, "even" is returned. Else, "odd" is returned. The returned value is saved in a string variable evenOdd.

Then, the result is printed on the screen using string concatenation.