# Print first n Prime number Program in Java

In this tutorial, we are going to learn writing java program to print all the prime numbers that are smaller than or equal to the number given as an input by the user.

## Problem Statement

For any number that is input by the user, we have to print all the prime numbers. For example

Case1: If the user inputs number 12
then the output should be ‘2, 3, 5, 7, 11’.
Case2: If the user inputs a number 51.
then the output should be ‘2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 ’.

## What is Prime Number?

Prime Numbers are the numbers that have only 2 factors 1 and the number itself. It is only defined for the number which is greater than ‘1’. ‘2’ is the smallest prime number.

Some examples

• 5 is a prime number because only factors of 5 are ‘1 and 5’.
• 11 is a prime number because only factors of 11 are ‘1 and 11’.
• 10 is not prime because the factors of 10 are ‘ 1,2,5 and 10’.

## Java Program to Print First n Prime Number

Output

Explanation

The input number is 9, so our program will check all the numbers smaller than 9 and greater than 0. The numbers that do not have any other factor other than 1 and itself, i.e. prime numbers which are smaller than 9 are 1,2,3,5, and 7.