Java Basic Examples

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 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 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 modulus operator (%) to check if we can divide the number as given below.

Output

As you may have observed from the above code, for loop inside the `isPrimeNumber` 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 prime number 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 which goes through 2 to 100 and checks the number one by one. Inner loop goes from 2 to the half of the number and tries to divide. If reminder of the any of the division is zero than the number is not a prime number.

How to find prime numbers between 1 to n?

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

Output

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Java IO

Java IO

Java IO

Java IO