Home / Programs / Write a java program to find whether a given number is odd or even or prime.
Programming Example

Write a java program to find whether a given number is odd or even or prime.

👁 12 Views
💻 Practical Program
📘 Step by Step Learning
Study this program carefully to understand the logic, output, and explanation in a structured way.

Information & Algorithm

Given Input:

Enter a number: 7

Expected Output:

The number is Odd.
The number is Prime.

Program Code

import java.util.Scanner;

public class NumberCheck {

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

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

        // Check Odd or Even
        if (num % 2 == 0) {
            System.out.println("The number is Even.");
        } else {
            System.out.println("The number is Odd.");
        }

        // Check Prime
        boolean isPrime = true;

        if (num <= 1) {
            isPrime = false;
        } else {
            for (int i = 2; i <= num / 2; i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
        }

        if (isPrime) {
            System.out.println("The number is Prime.");
        } else {
            System.out.println("The number is Not Prime.");
        }

        sc.close();
    }
}

Explanation

Logic Used

  • If num % 2 == 0Even, otherwise Odd.

  • For prime check:

    • Numbers ≤ 1 are not prime.

    • Check divisibility from 2 to num/2.

    • If divisible → Not Prime.

    • Otherwise → Prime.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.