English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)/O)

Java Reader/Writer

Java other topics

Java program to check if a number is prime

Comprehensive Java Examples

In this article, you will learn how to check if a number is prime. This is done using for loop and while loop in Java.

A prime number is a number that can only be divided by two numbers:1and itself. Therefore, if a number can be divided1and itself, then it is not a prime number.

Example1Program to check for prime numbers using 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 non-prime number
            if (num % i == 0)
            {
                flag = true;
                break;
            }
        }
        if (!flag)
            System.out.println(num + " Is a prime number ");
        else
            System.out.println(num + " Not a prime number ");
    }
}

Output the result

29 is a prime number

In the above program, the for loop is used to determine whether the given number num is a prime number.

Please note here that we start from2Loop to num / 2. This is because a number cannot be divided by an integer greater than half of itself.

Inside the for loop, we check if the number can be evenly divided by any number in the given range (2...num/2)。

  • If num is divisible, flag is set to true, and we exit the loop. This confirms that num is not a prime number.

  • If num cannot be evenly divided by any number, flag is set to false, and num is a prime number.

Example2: Program to check for prime numbers 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 non-prime number
            if (num % i == 0)
            {
                flag = true;
                break;
            }
            ++i;
        }
        if (!flag)
            System.out.println(num + " Is a prime number ");
        else
            System.out.println(num + " Not a prime number ");
    }
}

Output the result

33 Not a prime number

In the above program, replace the for loop with a while loop. The loop runs until i <= num / 2. In each iteration, check if num is divisible by i and increment the value of i1.

Visit this page to learn howDisplay all prime numbers between two time intervals.

Comprehensive Java Examples