Print First 10 Prime Numbers in Java

We will write a program to find first ten prime numbers in java . If you are don’t know what are prime numbers  , you should first read about prime numbers in java . In simple word A number which is divided by one and itself is called prime number.

Example 1 : is 21 a prime number?

21 is divided by 1, 3,7 ,21 . Because 21 is divided by 3 and 7 also , so 21 is not a prime number .

Example 2 : is 37 a prime number ?

37 is divided by 1 and 37 only , So 37 is a prime number .

Print First 10 Prime Numbers in Java

Now we will print first ten prime number using java program . In this program we take variable num and count . We iterate a while loop till print first ten prime numbers .  variable num increment by 1 in each iterate and count increment by 1 when find any number is prime number .

Program description: Program to print the first 10 prime numbers

public class FirstTenPrimeNumber {
	
	public static void main(String[] args) {
	
		int num =1 ,count =0;
		while ( count < 10) {
			if (isPrimeNumber(num)) {
				System.out.println( num +" is prime number");
				count++;
			}
			num++;
		}
	
	}

	private static boolean isPrimeNumber(int num) {
		if (num <= 1) {
			return false;
		}
		boolean flag = true;
		for (int j = 2; j <= Math.sqrt(num); j++) {
			if (num % j == 0) {
				flag = false;
				break;
			}
		}
		return flag;
	}

	
}

Output :

2 is prime number
3 is prime number
5 is prime number
7 is prime number
11 is prime number
13 is prime number
17 is prime number
19 is prime number
23 is prime number
29 is prime number

In this tutorial we learned what is prime numbers , prime number examples and how to find first ten prime numbers . You can learn more java program for interview preparation .

Leave a Reply

Your email address will not be published. Required fields are marked *

− 1 = 2