Let’s learn java program to check whether a number is prime or not.

## Java program to check whether number is prime or not

check prime number java is one of the most asked interview question. A prime number is a number that is greater than one and divided by one or itself.

Prime numbers are those numbers which cannot be divided by other numbers than 1 or itself.

**Example :** 2, 3, 5, 7, 11, 13, 17….

Here’s the program to check whether a number is prime or not using if else statement.

public class PrimeNumberInJava { public static void main(String[] args) { int a, b = 0, flag = 0; int number = 66; b = number / 2; if(number == 0 || number == 1) { System.out.println(number + " is not prime number"); } else { for(a = 2; a <= b; a++) { if(number % a == 0) { System.out.println(number + " is not prime number."); flag = 1; break; } } if(flag == 0) { System.out.println(number + " is prime number."); } } } }

**Output:**

**prime number program in java using while loop**

Similarly let’s learn to check prime number java using while loop.

import java.util.Scanner; public class PrimeNumberUsingWhileLoop { public static void main(String[] args) { boolean checkPrime = true; Scanner sc = new Scanner(System.in); System.out.println("Please enter any number: "); int number = sc.nextInt(); int a = 2; while(a <= number / 2) { if(number % a == 0) { checkPrime = false; break; } a++; } if(checkPrime) { System.out.println(number + " is a prime number."); } else { System.out.println(number + " is not a prime number."); } sc.close(); } }

**Output:**

Please enter any number: 17

17 is a prime number.

**NOTE:** 2 is the only even prime number. 0 and 1 are not prime numbers.