Java Program to Check Whether a Number is Odd or Even

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

FeatureNormal JavaJava 8
Approachif-elseLambda expression
Operator%%
InputScannerScanner
Java VersionAll common versionsJava 8+
ComplexitySimpleSlightly more advanced
Best for beginnersYesGood 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.

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *