Write a Java Program to Display Prime Numbers Between Two Intervals

In this tutorial, we will discuss how to write a Java program that displays prime numbers between two given intervals.

A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself.

To solve this problem, we will use a simple algorithm that checks each number between the given intervals to see if it is a prime number.

We will start by taking two input integers from the user representing the starting and ending points of the interval.

The program will then loop through all the numbers between the two given intervals and check if each number is a prime number.

To check if a number is a prime number, we will divide it by all the numbers between 2 and the square root of the number.

If the number is not divisible by any of these numbers, it is a prime number.

Here is the Java program to display prime numbers between two intervals:

import java.util.Scanner;

public class PrimeNumbers {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter the starting point of the interval: ");
        int start = input.nextInt();

        System.out.print("Enter the ending point of the interval: ");
        int end = input.nextInt();

        System.out.println("Prime numbers between " + start + " and " + end + " are:");

        for (int i = start; i <= end; i++) {
            boolean isPrime = true;
            if (i == 1 || i == 0) {
                isPrime = false;
            } else {
                for (int j = 2; j <= Math.sqrt(i); j++) {
                    if (i %% j == 0) {
                        isPrime = false;
                        break;
                    }
                }
            }
            if (isPrime)
                System.out.print(i + " ");
        }
    }
}

In this program, we first take input from the user for the starting and ending points of the interval.

We then use a for loop to loop through all the numbers between the two intervals.

For each number, we use another for loop to check if it is a prime number.

We start by setting the boolean variable isPrime to true.

If the number is 1 or 0, we set isPrime to false.

Otherwise, we loop through all the numbers between 2 and the square root of the number.

If the number is divisible by any of these numbers, we set isPrime to false and break out of the loop.

Finally, if isPrime is still true after the inner loop, we print the number as a prime number.


In conclusion, this Java program allows the user to input two integers representing a range of numbers and outputs all the prime numbers in that range.

This program can be used to quickly identify all the prime numbers within a given interval.