Java Program to Check If a Number is Even or Odd

In this Java program, you’ll learn how to check whether a number is even or odd using the Java programming language. 

How to check if a number is even or odd in JAVA? 

Example 1: using if……else statement 

RUN CODE SNIPPET
import java.util.Scanner; 

public class Main  

{ 

    public static void main(String[] args)  

    { 

        Scanner reader = new Scanner(System.in); 

        System.out.print("Enter a number: "); 

        int num = reader.nextInt(); 

        if(num % 2 == 0) 

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

        else 

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

    } 

}

OUTPUT 

Enter a number: 2 is even

In the above program, a scanner object and reader are created to read a number from the user’s keyword.

The entered number is then stored in a variable called num. 

To check whether the entered number is even or odd, we calculate its remainder using the % operator and check if it is divisible by 2 or not. We use if…..else statement in JAVA. If the number is divisible by 2, we print the number is even. Else we print number is the number is odd. 

Example 2: using the ternary operator. 

RUN CODE SNIPPET
import java.util.Scanner; 

public class Main 

{ 

    public static void main(String[] args) { 

        Scanner reader = new Scanner(System.in); 

        System.out.print("Enter a number: "); 

        int num = reader.nextInt(); 

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

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

    } 

}

OUTPUT 

Enter a number: 9 is odd

The ternary operator which takes three operands rather and the typical one or two that most operators use. 

If the is divisible by 2, we print number is even. Else we print number is odd. The returned value is saved in a string value called evenodd. 

The result’s is printed on the screen using string concatenation.  

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024