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 Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

📌 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.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.