Java Program to Check Whether a Number is Prime or Not

In this article, you'll learn to check whether a number is prime or not. This is done using a for loop and while loop in Java.

A prime number is a number which is divisible by only two numbers: 1 and itself. So, if any number is divisible by any other number, it is not a prime number.

Example 1: Program to Check Prime Number using a for loop

public class Prime {

    public static void main(String[] args) {

        int num = 29;
        boolean flag = false;
        for(int i = 2; i <= num/2; ++i)
        {
            // condition for nonprime number
            if(num % i == 0)
            {
                flag = true;
                break;
            }
        }

        if (!flag)
            System.out.println(num + " is a prime number.");
        else
            System.out.println(num + " is not a prime number.");
    }
}

When you run the program, the output will be:

29 is a prime number.

In the above program, for loop is used to determine if the given number num is prime or not. We only have to loop through 2 to half of num, because no number is divisible by more than its half.

Inside the for loop, we check if the number is divisible by any number in the given range (2..num/2). If it is, flag is set to true and we break out of the loop. This determines num is not a prime number.

If num isn't divisible by any number, flag is false and num is a prime number.


Example 2: Program to Check Prime Number using a while loop

public class Prime {

    public static void main(String[] args) {

        int num = 33, i = 2;
        boolean flag = false;
        while(i <= num/2)
        {
            // condition for nonprime number
            if(num % i == 0)
            {
                flag = true;
                break;
            }

            ++i;
        }

        if (!flag)
            System.out.println(num + " is a prime number.");
        else
            System.out.println(num + " is not a prime number.");
    }
}

When you run the program, the output will be:

33 is not a prime number.

In the above program, while loop is used instead of a for loop. The loop runs until i <= num/2. On each iteration, whether num is divisble by i is checked and the value of i is incremented by 1.

Visit this page to learn, how you can display all prime numbers between two intervals.