Java Program to Check Even or Odd Number

Checking whether a number is even or odd is one of the simplest and most commonly used programs in Java. It helps beginners understand conditional statements and the modulus operator.

In this tutorial, we will create a simple Java program that determines whether a given number is even or odd.

By the end of this guide, you will understand how to use the modulus operator and if-else statements in Java.

Concept Overview

A number is even if it is divisible by 2, otherwise it is odd.

In Java, we use the modulus operator (%) to check the remainder when dividing a number by 2.

If num % 2 == 0, the number is even; otherwise, it is odd.

Program

Java
import java.util.Scanner;

public class EvenOddCheck {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        if (num % 2 == 0) {
            System.out.println(num + " is Even");
        } else {
            System.out.println(num + " is Odd");
        }
    }
}

Output

TEXT
Enter a number: 8
8 is Even

Detailed Explanation

The program starts by importing the Scanner class to take input from the user.

Inside the main() method, a Scanner object is created to read the number.

The modulus operator (%) is used to find the remainder when the number is divided by 2.

If the remainder is 0, the number is even; otherwise, it is odd.

The result is displayed using an if-else statement.

Example Walkthrough

Let us consider an example where the user enters 8.

8 % 2 = 0, so the number is even.

The output is displayed as '8 is Even'.

Applications

Even-odd logic is widely used in programming, such as alternating patterns, game logic, scheduling, and mathematical computations.

Advantages of This Approach

This program is simple and helps beginners understand conditionals and operators.

It is a foundational concept for more advanced decision-making logic in Java.

Limitations

The program only handles integer input and does not validate incorrect input formats.

Improvements You Can Make

You can improve this program by adding input validation.

You can extend it to handle multiple numbers using loops.

You can also integrate it into a larger calculator program.

This Java program helps beginners understand the modulus operator and conditional statements effectively.