✓ Link copied to clipboard
Java 📅 July 17, 2026 ⏱ 3 min read

Java Program to Find Prime Number | Full Code and Output

Java Program to Find Prime Number | Full Code and Output

Figuring out if a number is prime is a pretty common task in programming. A prime number only divides by 1 and itself. Like, take 7 for instance; it's prime because its only divisors are 1 and 7. So, let’s see how to check this using Java.

What You Need Before Writing the Java Program to Find Prime Number

Before diving into the code, let's outline what's needed:

  • Familiarity with if and for loops in Java
  • Understanding of conditional operators like % (modulus)
  • A Java development environment, such as Eclipse or IntelliJ
  • Alternatively, use the Java online compiler

Source Code of Java Program to Find Prime Number

Here's the complete Java code to determine if a number is prime:

PrimeNumber.javaJava▶ Run
import java.util.Scanner;

public class PrimeNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = scanner.nextInt();
        boolean isPrime = true;

        if (n <= 1) isPrime = false;

        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0) isPrime = false;
            break;
        }

        if (isPrime)
            System.out.println(n + " is a prime number.");
        else
            System.out.println(n + " is not a prime number.");
    }
}

Try this code yourself — free

Run it in the EduSeekho online compiler. No setup needed.

▶ Open Compiler

Output of the Find Prime Number Program

When you execute the above code, it will prompt you to enter a number. Here's an example of what the output might look like for the number 7:

OUTPUT
Enter a number: 7
7 is a prime number.
Output of Java Program to Find Prime Number
Output of Java Program to Find Prime Number

Algorithm to Find Prime Number in Java

To find if a number is prime, the program checks divisibility from 2 up to the square root of the number. Here is the exact logic used step by step.

  1. Read the integer n from the user.
  2. If n is less than or equal to 1, it's not prime.
  3. Initialize i to 2.
  4. While i * i <= n, check if n % i == 0.
  5. If true, n is not prime and exit loop.
  6. If loop ends without setting not prime, n is prime.
flowchart TD
  A([Start]) --> B[/Read n/]
  B --> C[i = 2]
  C --> D{n <= 1?}
  D -->|Yes| E([Output: Not Prime])
  D -->|No| F{n % i == 0?}
  F -->|Yes| E
  F -->|No| G{i * i <= n?}
  G -->|Yes| H[i = i + 1]
  H --> F
  G -->|No| I([Output: Prime])
Flowchart: the algorithm step by step

How the Java Program to Find Prime Number Works

Let's break down the code to understand how it determines if a number is prime.

  • The program starts by importing the java.util.Scanner class to read input from the user.
  • It asks the user to enter a number, which is stored in variable n.
  • A boolean variable isPrime is initialized to true. This assumes the number is prime until proven otherwise.
  • The program checks if n <= 1. If true, isPrime is set to false.
  • A for loop runs from 2 to the square root of n, checking divisibility with n % i == 0.
  • If any divisor is found, isPrime is set to false, and the loop breaks.
  • Finally, the program prints whether n is a prime number based on the isPrime flag.
🧠

Quick Quiz — test your understanding

Tap an option to check your answer

What is the purpose of checking 'i * i <= n' in the program?

🎉Correct! Checking 'i * i <= n' reduces the number of checks needed.
🤔Not quite. Think about how checking up to the square root affects the process.

How Fast Is the Prime Number Program in Java?

Let's analyze the time and space complexity of this program.

Time complexity: O(√n). Here, n is the number you're testing for primality. The program only checks divisibility up to the square root of n (e.g., i * i <= n), significantly reducing checks compared to going all the way to n. For instance, checking if 49 is a prime involves up to 7 checks, not 49.

Space complexity: O(1). The program uses a constant amount of extra space: only the Scanner object, the integer n, boolean isPrime, and loop counter i.

⚠️

Common mistake: Not checking if n <= 1 can lead to wrong results for numbers like 0 and 1, which aren't prime.

Key takeaway: Efficiency in prime-checking improves by only looking at factors up to the square root.

FAQs About Java Program to Find Prime Number

Here are some common questions students have when working with prime numbers in Java.

A prime number is one that’s only divisible by 1 and itself, like 2, 3, 5, and 7.
Checking up to the square root cuts down the iterations, making it faster since a larger factor of n has to have a smaller one too.
Nope, prime numbers are only for positive integers greater than 1.
The modulus operator % helps figure out if n divides evenly by another number, which is super important for spotting non-prime numbers.
Assuming n is prime at first means the program just has to prove it wrong. That simplifies things a lot.
The program will correctly identify 2 as prime because the loop doesn’t run for n = 2.

If you found this program helpful, check out these related programs:

Conclusion

This Java program checks for prime numbers efficiently by using the properties of factors. Try tweaking the program to list all prime numbers up to a certain limit. Remember, programming's all about experimenting and learning. Keep at it!

Test your skills with our Java quiz and sharpen your code in the online compiler.