In this java program, you will learn how to check whether a number is even or odd in Java. This can be done in two ways: the first way is if..else
statement and the second way is the ternary operator(? :
).
//Java Program to Check Whether a Number Is Even or Odd Using if...else Statement
import java.util.Scanner;
public class JavaPrograms {
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");
}
}
}
Enter a number: 55
55 is odd
Enter a number: 222
222 is even
//Java Program Check Whether a Number Is Even or Odd Using Ternary Operator Using Ternary Operator
import java.util.Scanner;
public class JavaPrograms {
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);
}
}
Enter a number: 333
333 is odd
Enter a number: 444
444 is even
Comments