Introduction
A prime number is a number that has only two divisors: 1 and itself. In this tutorial, we will learn how to generate a list of prime numbers up to a specified limit using Java programming. This is a great exercise for beginners to understand loops and conditional statements in Java.
Objective
The objective of this program is to generate and display all prime numbers up to a user-defined limit. The program will loop through numbers from 2 up to the given limit and check whether each number is prime. If it is prime, it will be added to the list of primes.
Code
public class PrimeNumberGenerator {
public static void main(String[] args) {
int limit = 50; // You can change this to any positive integer to set the upper limit
System.out.println("Prime numbers up to " + limit + " are:");
for (int num = 2; num <= limit; num++) {
if (isPrime(num)) {
System.out.print(num + " ");
}
}
}
public static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
Explanation of the Program Structure
The program consists of two main components:
- PrimeNumberGenerator Class: This is the main class that runs the program. It contains the
main
method, where the prime number generation process starts. - isPrime Method: This helper method checks whether a given number is prime. It takes an integer as input and returns
true
if the number is prime andfalse
otherwise.
Steps of the Program
1. The program begins by defining a limit up to which prime numbers will be generated (in this case, 50).
2. The program loops through all numbers from 2 to the limit.
3. For each number, it checks whether the number is prime by calling the isPrime
method.
4. If the number is prime, it is printed to the console.
How to Run the Program
- Copy the code into a file named
PrimeNumberGenerator.java
. - Open a terminal or command prompt and navigate to the directory where the file is saved.
- Compile the Java program using the following command:
javac PrimeNumberGenerator.java
- Run the compiled program using the following command:
java PrimeNumberGenerator
- The program will display the prime numbers up to the defined limit.