In this article, You can print prime numbers between 1 to n numbers using the java program. A Prime number will be divisible by 1 and itself and also it is always a positive number. Okay, Let’s start the article about the java program to display prime numbers from 1 to n.

## Java Program to Display Prime Numbers from 1 to n

This is the example program to execute a task here.

```
import java.util.Scanner;
class PrimeNumbers2
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
System.out.println("Enter the value of n:");
int n = scanner.nextInt();
scanner.close();
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to n are :");
System.out.println(primeNumbers);
}
}
```

## Program Explanation

Initially, We need to import the java.util.scanner() class into this program. The input numbers are stored in the variables. The program asks you to enter the “n” value after running this program.

If the for loop will iterate from 1 to i<=n then the int counter will be equal to zero. Later, If the for loop will iterate from 1 to i>=n along with if(i%num==0) then the counter value will be added with 1.

Otherwise, The prime numbers will be added with 1. Finally, We will see the output on the screen using the system.out.printIn() function.

Read Also : Java Program to Display Prime Numbers from 1 to 100

## Output

The output of the java program to display prime numbers from 1 to n will be given below for your reference.

```
Enter the value of n:
150
Prime numbers from 1 to n are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89
97 101 103 107 109 113 127 131 137 139 149
```

## Final Words

I hope this article helps you to learn Java Program to display prime numbers from 1 to n. If you face any issues please let me know via the comment section. Share this article with other Java program developers via social networks. Thank You!