Java Program to Display Prime Numbers Between Intervals Using Function

In this program, you'll learn to display all prime numbers between the given intervals using a function in Java.

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;

When you run the program, the output will be:

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, number is printed on the screen inside main() function.