Java Program to Check Whether a Number is Even or Odd

JavaObject Oriented ProgrammingProgramming

In this article, we will understand how to check whether a number is even or odd. This is accomplished by checking if the given number is divisible by 2.

Below is a demonstration of the same −

Input

Suppose our input is −

Enter the number : 45

Output

The desired output would be −

The number 45 is an odd number

Algorithm

Step 1 - START
Step 2 - Declare an integer values namely my_input.
Step 3 - Read the required values from the user/ define the values
Step 4 - Use the modulus operator and compute my_input % 2 value.
Step 5 - If the result is 0, then its an even number, else it’s an odd number.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, the input is being entered by the user based on a prompt. You can try this example live in our coding ground tool run button.

import java.util.Scanner;
public class EvenOdd {
   public static void main(String[] args) {
      int my_input;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the number : ");
      my_input = my_scanner.nextInt();
      if(my_input % 2 == 0)
         System.out.println("The number " +my_input + " is an even number");
      else
         System.out.println("The number " +my_input + " is an odd number");
   }
}

Output

Required packages have been imported
A reader object has been defined
Enter the number : 45
The number 45 is an odd number

Example 2

Here, the integer has been previously defined, and its value is accessed and displayed on the console.

public class EvenOdd {
   public static void main(String[] args) {
      int my_input;
      my_input = 45;
      System.out.println("The number is defined as " +my_input);
      if(my_input % 2 == 0)
         System.out.println("The number " +my_input + " is an even number");
      else
         System.out.println("The number " +my_input + " is an odd number");
   }
}

Output

The number is defined as 45
The number 45 is an odd number
raja
Updated on 22-Feb-2022 10:42:25

Advertisements