Java Program – Check Prime Number

In this tutorial, we shall check if a number is prime or not.

You can use either while loop statement or for loop statement to find whether the given number is prime number or not.

Algorithm

  1. Start.
  2. Read a number N from user.
  3. Initialize i with 2.
  4. If i is less than N/i, continue with next step, else go to step 7.
  5. Check if i is a factor of N. If i is a factor of N, N is not prime, return false. Go to step 8.
  6. If i is not a factor, increment i. Go to step 4.
  7. Return true.
  8. End.
ADVERTISEMENT

Java Program

In the following program, we shall write a function isPrime(), using the above algorithm. This function takes a number as argument, then check if the number is prime or not, and returns a boolean value. The function returns true if the number is prime, else it returns false.

Example.java

/**
 * Java Program - Check if Number is Prime Number
 */

public class Example {

	public static void main(String[] args) {
		System.out.println("Is 32 prime : "+isPrime(32));
		System.out.println("Is 41 prime : "+isPrime(41));
	}
	
	public static boolean isPrime(int num) {	
		for(int i = 2; i <= num/i; ++i) {
			if(num % i == 0) {
				return false;
			}
		}
		return true;
	}
}

Run the above program, and you shall get the following output in the console.

Output

Is 32 prime : false
Is 41 prime : true

Conclusion

In this Java Tutorial, we learned how to write a Java Program to check if a given number is prime of not.