Java Program to Display Prime Numbers Between Intervals Using Function

To understand this example, you should have the knowledge of the following Java programming topics:


To find all prime numbers between two integers, checkPrimeNumber() function is created. This function checks whether a number is prime or not.

Example: Prime Numbers Between Two Integers

public class Prime {

    public static void main(String[] args) {

        int low = 20, high = 50;

        while (low < high) {
            if(checkPrimeNumber(low))
                System.out.print(low + " ");

            ++low;
        }
    }

    public static boolean checkPrimeNumber(int num) {
        boolean flag = true;

        for(int i = 2; i <= num/2; ++i) {

            if(num % i == 0) {
                flag = false;
                break;
            }
        }

        return flag;
    }
}

Output

23 29 31 37 41 43 47 

In the above program, we've created a function named checkPrimeNumber() which takes a parameter num and returns a boolean value.

If the number is prime, it returns true. If not, it returns false.

Based on the return value, the number is printed on the screen inside the main() method.

Note that inside the checkPrimeNumber() method, we are looping from 2 to num/2. This is because a number cannot be divided by more than it's half.

Recommended Readings

Java Program to Check if a number is prime

Did you find this article helpful?