Java Program to Print Prime Numbers between 1 to N - The Coding Shala

Home >> Java Programs >> Print Prime Numbers between 1 to N

 In this post, we will learn how to display prime numbers between 1 to n using the Java program.

Java Program to Print Prime Numbers between 1 to N

Write a Java Program to print prime numbers between 1 to given n.

Example 1:
Input: 10
Output: 2


We are going to check every number from 1 to n, if it is prime then will print it.

Prime numbers are only divisible by 1 and the number itself, so if the given number is divisible by any other numbers from 2 to n-1 then it's not a prime number.

Java Program: 


import java.util.Scanner;

public class Main {

    public static boolean checkPrime(int num) {
        if(num < 2) return false;

        for(int i = 2; i * i <= num; i++) {
            if(num % i == 0) return false;
        return true;

    public static void main(String[] args) {
        Scanner sc = new Scanner(;
        System.out.println("Enter the value of n");
        int n = sc.nextInt();
        System.out.println("Prime number from 1 to " + n + " are: ");
        for (int i=2; i <= n; i++) {
            if (checkPrime(i)) {


Enter the value of n
Prime number from 1 to 15 are: 

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.


Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Display the digits which are at odd positions in a given 5-digit number - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

Add two numbers in Scala - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala