HomeJavaJava Program to Check If a Number is Even or Odd

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

You May Also Like

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022