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 SNIPPETimport 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 SNIPPETimport 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.