Java Program to Check Whether a Number is Even or Odd

The program checks whether an entered input is even or not. A number which is divisible by 2 is said to be even number whereas remaining ones are said to be odd. For example, even numbers are 2,4,6 whereas odd numbers are 1,3,5.

There are various ways to achieve this functionality. But in this article, we’ll be using two ways :

1) Using if and else
2) Using ternary Operator

Java program to check whether a number is even or odd using if and else statement

Program:

import java.util.*;
public class Main
{
  public static void main(String[] args) {
  int number; 
  Scanner ed = new Scanner(System.in); 
  System.out.print("Please enter a number : "); 
  number = ed.nextInt(); 
  if(number%2==0)
  System.out.print(number+" is even");
  else
  System.out.print(number+" is odd"); 
  }
}

Ouput:

In the case of Even:

Please enter a number : 90                                                                                                    

90 is even

In case of Odd:

Please enter a number : 43                                                                                                    

43 is odd

Java program to check whether a number is even or odd using ternary operator

Program:

import java.util.*;
public class Main
{
  public static void main(String[] args) {
  int number; 
  String answer; 
  Scanner ed = new Scanner(System.in); 
  System.out.print("Please enter a number : "); 
  number = ed.nextInt(); 
  answer =(number%2==0)?(number+" is even"):(number+" is odd"); 
  System.out.println(answer);
  }
}

Output:

In case of even :

Please enter a number : 22                                                                                                    

22 is even

In case of Odd :

Please enter a number : 89                                                                                                    

89 is odd

Approach :

  1. Using Modulo Operator (%), we can find whether the input is divisible by 2 or not as it would give remainder as 1 otherwise 0
  2.  If the remainder is zero, then it would be an even number, otherwise odd

Leave a Reply