In this Java program, we will learn how to check whether a given number is odd or even using the modulo (%) operator.
1. Normal Java Program
import java.util.Scanner;
public class OddEven {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
if (number % 2 == 0) {
System.out.println(number + " is Even");
} else {
System.out.println(number + " is Odd");
}
sc.close();
}
}
Output
Enter a number: 10
10 is Even
Explanation
The modulo operator % returns the remainder after division.
number % 2
If the remainder is 0, the number is even. Otherwise, the number is odd.
2. Java 8 Program
Java 8 introduced features such as Lambda expressions and functional interfaces. We can use a lambda expression to perform the odd/even check.
import java.util.Scanner;
import java.util.function.Function;
public class OddEvenJava8 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
Function<Integer, String> checkOddEven =
n -> n % 2 == 0 ? "Even" : "Odd";
System.out.println(number + " is " + checkOddEven.apply(number));
sc.close();
}
}
Output
Enter a number: 15
15 is Odd
Explanation
In the Java 8 version, we use the Function<T, R> functional interface:
Function<Integer, String>
The lambda expression:
n -> n % 2 == 0 ? "Even" : "Odd"
checks whether the number is divisible by 2.
The ternary operator:
condition ? valueIfTrue : valueIfFalse
returns "Even" when the condition is true; otherwise, it returns "Odd".
The result is obtained using:
checkOddEven.apply(number)
Difference Between Normal Java and Java 8
| Feature | Normal Java | Java 8 |
|---|---|---|
| Approach | if-else | Lambda expression |
| Operator | % | % |
| Input | Scanner | Scanner |
| Java Version | All common versions | Java 8+ |
| Complexity | Simple | Slightly more advanced |
| Best for beginners | Yes | Good for learning Java 8 |
Conclusion
The normal if-else approach is recommended for beginners because it is simple and easy to understand. The Java 8 version demonstrates how a lambda expression and functional interface can be used for the same task.