Check if a number is prime number in Java Example

This example shows how to check if a number is prime number in Java. This example also shows how to find prime numbers between 1 and 100 or between any two numbers.

What is a prime number?

Definition of a prime number from Wikipedia,

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

How to check if a number is a prime number in Java?

If we cannot divide a number (greater than 1) by any positive number other than 1 or itself, then the number is a prime number. We will use the modulus operator (%) to check if we can divide the number as given below.

Output

As you may have observed from the above code, the for loop inside the isPrimeNumber method goes only up to number/2. That is because any number cannot be perfectly divided by anything above the half of that number.

How to find the prime numbers between 1 and 100?

We will do a slight modification to the above program to find prime numbers between 1 and 100 as given below.

Output

Here, we have introduced a new loop that goes through 2 to 100 and checks the number one by one. The inner loop goes from 2 to half of the number and tries to divide the number. If a reminder of any of the divisions is zero then the number is not a prime number.

How to find all prime numbers between 1 to n?

In the above example, we printed prime numbers between 1 and 100. Now, we are going to take input from the user using the Scanner and print the prime numbers between 2 and the input number as given below.

Output

This example is a part of the Java Basic Examples.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *