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) {
                System.out.print(low + " ");


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

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

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

        return flag;


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.

Also Read:

Did you find this article helpful?