## Java Program to check whether a given number is Prime or not using while loop

A whole number greater than 1 that cannot be exactly divided by any whole number other than itself and 1 is called a prime number.

For Example:

3, 5, 7 , 13 … are prime numbers because they can only divide by 1 or the number itself.

### Required Knowledge

Steps to writing prime number program in java

• Here we are using “Scanner” to take input for numbers.
• We will start the loop from 2 as 1 is not a prime number and limit it to number/2 as it will be useless iterations.
• Inside the loop, we are checking the divisibility of the number with i starting from 2. If it is divisible then we break from the loop as it definitely is not a prime number because it is fully divisible by other numbers as well.
• Else we keep on iterating till number/2.

Prime number program in Java

``````import java.util.*;
public class Main
{
public static void main(String args[])
{
System.out.println("Prime Number program in Java While loop ");
Scanner sc = new Scanner(System.in);
int i = 2;
boolean flag = false;
System.out.println("Enter the Number to check for prime : ");
int number = sc.nextInt();
while(i<=number/2) {
if(number%i == 0) {
flag = true;
break;
}
++i;
}
if (!flag)
System.out.println(number + " is a prime number.");
else
System.out.println(number + " is not a prime number.");
sc.close();
}
}``````

Output 1:

``````Prime Number program in Java While loop
Enter the Number to check for prime:
31
31 is a prime number.``````

Output 2:

``````Prime Number program in Java While loop
Enter the Number to check for prime :
12
12 is not a prime number.``````