---
description: Prime Number Program in Java - A prime number is a number that is only divisible by 1 or itself. Learn Java Program to check whether a number is prime or not.
title: Java Program to Check Prime Number with Example
image: https://www.guru99.com/images/java-prime-number-program.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

Java Program to Check Prime Number demonstrates how a single integer is tested for divisibility and classified as prime or composite. This article covers the mathematical definition, loop logic, complete runnable code, square root optimization, complexity comparison, and frequent beginner mistakes.

* 🔢 **Definition Rule:** A prime number is a natural number greater than 1 that has exactly two divisors, namely 1 and the number itself.
* 🔁 **Loop Logic:** Divide the candidate by every integer from 2 up to half of the number and record whether any remainder equals zero.
* 🚩 **Flag Pattern:** A boolean variable stores the verdict, and the break statement exits the loop the moment a divisor is found.
* √ **Square Root Optimization:** Testing divisors only up to the square root reduces the iteration count from n/2 to √n without changing the result.
* ⚠️ **Edge Cases:** Zero, one, and negative values are never prime, while 2 is the only even prime number.
* ⏱️ **Complexity Comparison:** The basic loop runs in O(n) time and the square root method in O(√n).
* 🧪 **Verification Practice:** Test with 1, 2, 9, 17, and 97 to confirm every boundary condition.

[ Read More ](javascript:void%280%29;) 

![Java Program to Check Prime Number](https://www.guru99.com/images/java-prime-number-program.png)

## What is a Prime Number?

A prime number is a natural number greater than 1 that is only divisible by 1 or itself. For example, 11 is only divisible by 1 or itself. Other prime numbers are 2, 3, 5, 7, 11, 13, 17, and the sequence continues without end.

A number greater than 1 that is not prime is called a composite number, because it can be composed from smaller factors. The value 9 is composite because it divides evenly by 3, and 15 is composite because it divides evenly by 3 and 5.

**Note:** 0 and 1 are not prime numbers. 2 is the only even prime number, and negative values are never considered prime.

## How to Check Whether a Number is Prime in Java

The verification strategy is a straightforward divisibility test. Take the candidate value, divide it by each smaller integer in turn, and inspect the remainder returned by the modulus operator. A remainder of zero proves that a divisor exists, which immediately disqualifies the number.

**Program Logic:**

* We need to divide an input number, say 17, from values 2 to 17 and check the remainder. If the remainder is 0, the number is not prime.
* No number is divisible by more than half of itself. So we need to [loop](https://www.guru99.com/foreach-loop-java.html) through just `numberToCheck/2`. If the input is 17, half is 8.5 and the loop will iterate through values 2 to 8.
* If numberToCheck is completely divisible by another number, the flag isPrime is set to `false` and the loop is exited.

Two Java features carry the whole algorithm. The modulus operator `%` returns the remainder of an integer division, and the `break` statement stops the loop as soon as the answer is known, so no unnecessary iterations are executed.

## Java Program to Check Whether a Number is Prime or Not

The program below assigns the value 17 to the variable numberToCheck and prints every division step, so you can follow the reasoning line by line. The code is editable, so change the value and run it again with a composite number such as 21 to see the opposite outcome.

public class PrimenumberToCheckCheck {

 public static void main(String[] args) {
  int remainder;
  boolean isPrime=true;
  int numberToCheck=17; // Enter the number you want to check for prime

  //Loop to check whether the number is divisible by any number other than 1 and itself
  for(int i=2;i<=numberToCheck/2;i++)
  {
   //number is divided by i
            remainder=numberToCheck%i;
            System.out.println(numberToCheck+" Divided by "+ i + " gives a remainder "+remainder);

       //if remainder is 0 then the number is not prime and we break the loop. Else continue the loop
     if(remainder==0)
     {
        isPrime=false;
        break;
     }
  }
  // Check value true or false, if isPrime is true then the number is prime otherwise not prime
  if(isPrime)
     System.out.println(numberToCheck + " is a Prime number");
  else
     System.out.println(numberToCheck + " is not a Prime number");
    }
  }

### Expected Output:

17 Divided by 2 gives a remainder 1
17 Divided by 3 gives a remainder 2
17 Divided by 4 gives a remainder 1
17 Divided by 5 gives a remainder 2
17 Divided by 6 gives a remainder 5
17 Divided by 7 gives a remainder 3
17 Divided by 8 gives a remainder 1
17 is a Prime number

The loop stops at 8 because 17 divided by 2 equals 8 in integer arithmetic. Since no remainder was ever zero, the flag isPrime keeps its initial value of true and the final condition prints the positive verdict.

### RELATED ARTICLES

* [this Keyword in Java ](https://www.guru99.com/java-this-keyword.html "this Keyword in Java")
* [Java BufferedReader: How to Read a File with Example ](https://www.guru99.com/buffered-reader-in-java.html "Java BufferedReader: How to Read a File with Example")
* [Difference Between C++ and Java ](https://www.guru99.com/cpp-vs-java.html "Difference Between C++ and Java")
* [Scala Tutorial ](https://www.guru99.com/scala-tutorial.html "Scala Tutorial")

## Optimized Prime Number Check Using the Square Root Method

Dividing up to half of the number is correct but wasteful. If a number n has a divisor larger than its square root, the matching co-divisor must be smaller than the square root, so it would already have been discovered. Checking up to √n therefore produces the same answer with far fewer iterations.

public class PrimeCheckOptimized {

    public static boolean isPrime(int n) {
        // 0, 1 and negative values are never prime
        if (n <= 1) {
            return false;
        }
        // 2 is the only even prime number
        if (n == 2) {
            return true;
        }
        if (n % 2 == 0) {
            return false;
        }
        // test only odd divisors up to the square root
        for (int i = 3; i * i <= n; i += 2) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int[] samples = {1, 2, 9, 17, 97};
        for (int value : samples) {
            System.out.println(value + " is prime: " + isPrime(value));
        }
    }
}

### Output:

1 is prime: false
2 is prime: true
9 is prime: false
17 is prime: true
97 is prime: true

The condition `i * i <= n` avoids a floating point call to Math.sqrt, and the step of 2 skips every even divisor. For a value such as 1,000,003 the basic loop performs roughly 500,000 iterations while this version performs fewer than 500.

## Check a Prime Number Entered by the User

Hard-coded input is convenient for demonstrations, yet real exercises usually ask for keyboard input. The Scanner class reads an integer from the console and passes it to the same isPrime method.

import java.util.Scanner;

public class PrimeCheckUserInput {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = sc.nextInt();

        boolean isPrime = number > 1;
        for (int i = 2; i * i <= number; i++) {
            if (number % i == 0) {
                isPrime = false;
                break;
            }
        }

        System.out.println(number + (isPrime ? " is a Prime number" : " is not a Prime number"));
        sc.close();
    }
}

### Sample Run:

Enter a number: 29
29 is a Prime number

**💡 Tip:** Initialising the flag with `number > 1` handles the values 0, 1, and every negative input in a single expression, which removes the need for a separate guard clause.

## Common Mistakes When Writing a Prime Number Program

Most incorrect submissions fail on boundary values rather than on the main loop. The list below covers the errors that appear most often in beginner code.

1. **Starting the loop at 1:** Every integer divides by 1, so the flag is set to false immediately and the program reports that no number is prime.
2. **Treating 1 as prime:** The value 1 has only one divisor, so it fails the two-divisor definition and must return false.
3. **Omitting the break statement:** The program still returns the right answer, but it keeps iterating after the verdict is known, which wastes time on large inputs.
4. **Using `i <= n` as the bound:** The number always divides itself, so the loop must stop before reaching n.
5. **Comparing with `=` instead of `==`:** A single equals sign assigns a value rather than testing it, which produces a compile-time error in the if condition.

## Comparison of Prime Checking Methods

Choose the method that matches the size of the input and whether one value or a whole range must be tested.

| Method                | Divisor Range Tested | Time Complexity | Best Suited For                |
| --------------------- | -------------------- | --------------- | ------------------------------ |
| Basic loop            | 2 to n-1             | O(n)            | Learning the core logic        |
| Half division         | 2 to n/2             | O(n)            | Small inputs, simple code      |
| Square root method    | 2 to √n              | O(√n)           | Single large values            |
| Sieve of Eratosthenes | Precomputed table    | O(n log log n)  | Listing every prime in a range |

When a whole range must be classified rather than a single value, the sieve is far more efficient. Our companion program to find [Prime Numbers from 1 to 100](https://www.guru99.com/prime-number-program-java.html) demonstrates that pattern. For related loop-driven exercises, review the [Fibonacci series in Java](https://www.guru99.com/fibonacci-series-java.html), the [Java palindrome program](https://www.guru99.com/java-palindrome-program.html), and the [Bubble Sort algorithm in Java](https://www.guru99.com/bubble-sort-java.html). Beginners who need a refresher on declaring the flag and counter should read about [Java variables](https://www.guru99.com/java-variables.html) in the main [Java tutorial](https://www.guru99.com/java-tutorial.html).

## FAQs

1️⃣ Is 1 a prime number in Java programs?

No. The number 1 has only one divisor, so it fails the two-divisor definition. Any correct program must return false for 1, for 0, and for every negative integer.

🧮 Why does the loop stop at the square root of the number?

Divisors occur in pairs. If a factor larger than the square root exists, its partner is smaller than the square root and was already tested, so no additional checks are required.

🔢 Can this program check very large numbers such as long values?

Yes. Change the parameter type from int to long and keep the same logic. For values beyond 64 bits, use BigInteger and its isProbablePrime method instead of trial division.

🔄 Can a while loop replace the for loop in this program?

Yes. Declare the counter before the loop, place the same condition in the while header, and increment the counter inside the body. The output remains identical.

🤖 Do AI coding assistants write the prime check correctly?

Usually yes, although generated code often omits the guard for 0, 1, and negative inputs. Always run the boundary tests yourself before accepting an AI-written implementation.

🧠 Where are prime numbers used in artificial intelligence and computing?

Primes underpin hashing functions, random number generation, and RSA encryption that protect model APIs and stored datasets. Hash table sizes are frequently chosen as primes to spread keys evenly.

This code is editable. Click Run to Compile + Execute   

![](https://www.guru99.com/Customization/CodeEditorFiles/Common/ajax-loader.gif)

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter](https://www.guru99.com/images/footer-email-avatar-imges-1.png) Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/java-prime-number-program.png","url":"https://www.guru99.com/images/java-prime-number-program.png","width":"700","height":"250","caption":"Java Prime Number Program","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/java-program-check-prime-number.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/java-tutorials","name":"Java Tutorials"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/java-program-check-prime-number.html","name":"Java Program to Check Prime Number with Example"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/java-program-check-prime-number.html#webpage","url":"https://www.guru99.com/java-program-check-prime-number.html","name":"Java Program to Check Prime Number with Example","dateModified":"2026-07-29T14:32:24+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/java-prime-number-program.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/java-program-check-prime-number.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/james","name":"James Hartman","description":"I am James Hartman, a seasoned professional in Oracle Certified Java Professional tutorials, specializing in crafting comprehensive guides to help you excel in your Java certification journey.","url":"https://www.guru99.com/author/james","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","url":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","caption":"James Hartman","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Java Tutorials","headline":"Java Program to Check Prime Number with Example","description":"Prime Number Program in Java - A prime number is a number that is only divisible by 1 or itself. Learn Java Program to check whether a number is prime or not.","keywords":"java","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/james","name":"James Hartman"},"dateModified":"2026-07-29T14:32:24+05:30","image":{"@id":"https://www.guru99.com/images/java-prime-number-program.png"},"copyrightYear":"2026","name":"Java Program to Check Prime Number with Example","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"Is 1 a prime number in Java programs?","acceptedAnswer":{"@type":"Answer","text":"No. The number 1 has only one divisor, so it fails the two-divisor definition. Any correct program must return false for 1, for 0, and for every negative integer."}},{"@type":"Question","name":"Why does the loop stop at the square root of the number?","acceptedAnswer":{"@type":"Answer","text":"Divisors occur in pairs. If a factor larger than the square root exists, its partner is smaller than the square root and was already tested, so no additional checks are required."}},{"@type":"Question","name":"Can this program check very large numbers such as long values?","acceptedAnswer":{"@type":"Answer","text":"Yes. Change the parameter type from int to long and keep the same logic. For values beyond 64 bits, use BigInteger and its isProbablePrime method instead of trial division."}},{"@type":"Question","name":"Can a while loop replace the for loop in this program?","acceptedAnswer":{"@type":"Answer","text":"Yes. Declare the counter before the loop, place the same condition in the while header, and increment the counter inside the body. The output remains identical."}},{"@type":"Question","name":"Do AI coding assistants write the prime check correctly?","acceptedAnswer":{"@type":"Answer","text":"Usually yes, although generated code often omits the guard for 0, 1, and negative inputs. Always run the boundary tests yourself before accepting an AI-written implementation."}},{"@type":"Question","name":"Where are prime numbers used in artificial intelligence and computing?","acceptedAnswer":{"@type":"Answer","text":"Primes underpin hashing functions, random number generation, and RSA encryption that protect model APIs and stored datasets. Hash table sizes are frequently chosen as primes to spread keys evenly."}}]}],"@id":"https://www.guru99.com/java-program-check-prime-number.html#schema-1154594","isPartOf":{"@id":"https://www.guru99.com/java-program-check-prime-number.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/java-program-check-prime-number.html#webpage"}}]}
```
