This Java example code demonstrates a simple Java program that checks whether a given number is an even or odd number and prints the output to the screen.
Program:
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");
}
}
}
Program Output:
Enter a number: 8 8 is even
If a number is evenly divisible by 2 without any remainder, then it is an even number; Otherwise, it is an odd number. The modulo operator %
is used to check it in such a way as num%2 == 0
.
In the calculation part of the program, the given number is evenly divisible by 2 without remainder, so it is an even number.
The above program can also be written using a ternary operator such as:
Java Program to Check Even or Odd Number Using Ternary Operator
Program:
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);
}
}
Program Output:
Enter a number: 9 9 is odd