Java Program to Display Prime Numbers Between Two Intervals

In this program, you'll learn to display prime numbers between two given intervals, low and high. You'll learn to do this using a while and a for loop in Java.

Example: Display Prime Numbers Between two Intervals

public class Prime {

    public static void main(String[] args) {

        int low = 20, high = 50;

        while (low < high) {
            boolean flag = false;

            for(int i = 2; i <= low/2; ++i) {
                // condition for nonprime number
                if(low % i == 0) {
                    flag = true;
                    break;
                }
            }

            if (!flag)
                System.out.print(low + " ");

            ++low;
        }
    }
}

When you run the program, the output will be:

23 29 31 37 41 43 47 

In this program, each number between low and high are tested for prime. The inner for loop checks whether the number is prime or not.

You can check: Java Program to Check Prime Number for more explanation.

The difference between checking a single prime number compared to an interval is, you need to reset the value of flag = false on each iteration of while loop.