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