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

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

Prime numbers are those numbers which cannot be divided by other numbers than 1 or itself. **Example :** 2, 3, 5, 7, 11, 13, 17….

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

Here’s the java code to check if number is prime or not using if else.

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:**

**Program to check whether the given number is prime or not using while loop**

Here’s the program to check whether a number is prime or not using for loop 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.