Hi guys!! Welcome to flower brackets blog. Today we are going to learn prime number java.

A prime number is a number that is greater than one and divided by itself. Prime numbers are those numbers which cannot be divided by other numbers than 1 or itself.

Also read – palindrome number in java

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

In the example for loop determines if given number is prime or not. In this for loop condition is checked if number is divisible by any number in range number / 2.

We set “temp” to true and break out of for loop. Hence it is a prime number. If number is not divisible “temp” is false and number is prime number.

Here’s java program to check whether a number is prime or not,

public class JavaPrimeNumber { public static void main(String[] args) { int number = 23; boolean temp = false; for(int a = 2; a <= number / 2; ++a) { // checking condition for non-prime number if(number % a == 0) { temp = true; break; } } if(!temp) { System.out.println(number + " is a prime number"); } else { System.out.println(number + " is not a prime number"); } } }

**Output :**

23 is a prime number

Now let’s see java program to check prime number using a while loop,

import java.util.Scanner; public class JavaPrimeNumber { public static void main(String[] args) { boolean checkPrime = false; 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 = true; 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 : 50

50 is not a prime number.