In this program, you will learn to check whether a number is Even or Odd in Java. To understand this program you should have basic knowledge of if…else statements and ternary operators in java.
Here, we use a java.lang.Scanner
object to read a number from the user’s keyboard. The entered number is then stored in a variable number
. Now, to check whether the number
is even or odd, we find its remainder using %
operator and check if it is divisible by 2
or not.
Example-1. Check whether a number is even or odd using the if…else statement
package com.javacodepoint.basics;
import java.util.Scanner;
public class CheckOddEven {
public static void main(String[] args) {
// Create scanner object to read user input
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer number: ");
int number = sc.nextInt();
// Check whether Odd or Even
// if number is divisible by 2 completely, then it is Even otherwise Odd
if (number % 2 == 0) {
System.out.println("Given number " + number + " is an Even number.");
} else {
System.out.println("Given number " + number + " is an Odd number.");
}
}
}
OUTPUT-1:
Enter an integer number:
7
Given number 7 is an Odd number.
OUTPUT-2:
Enter an integer number:
4
Given number 4 is an Even number.
Example-2. Check whether a number is even or odd using the ternary operator
package com.javacodepoint.basics;
import java.util.Scanner;
public class CheckOddEven2 {
public static void main(String[] args) {
// Create scanner object to read user input
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer number: ");
int number = sc.nextInt();
// Check Odd or Even using ternary operator
String result = (number % 2 == 0) ? "Even number." : "Odd number.";
// Print the result
System.out.println("Given number " + number + " is an " + result);
}
}
OUTPUT-1:
Enter an integer number:
5
Given number 5 is an Odd number.
OUTPUT-2:
Enter an integer number:
20
Given number 20 is an Even number.
See also:
Java Program to Add two Numbers.
Java Program to check whether an integer number is a prime number in java.