English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Other Java Topics

Java program uses functions to display prime numbers between intervals

Comprehensive Java Examples

In this program, you will learn how to use Java functions to display all prime numbers between given numbers.

To find all prime numbers between two integers, the function checkPrimeNumber() will be created. This functionCheck if a number is a prime number.

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;
    }
}

When running the program, the output is:

23 29 31 37 41 43 47

In the above program, we created a function named checkPrimeNumber() that accepts a parameter num and returns a boolean value.

If the number is a prime number, return true. If not, return false.

Print the number on the screen inside the main() function based on the return value.

Comprehensive Java Examples