Checking Prime with Varargs in Java
Write a Java program demonstrating a method with varargs that checks if a specific integer is prime
- The PrimeChecker class contains a static method named isPrime that checks whether each given number is prime or not.
- It iterates through each number in the array of numbers.
- For each number, it first assumes it's prime (prime = true).
- If the number is less than or equal to 1, it sets prime to false because prime numbers are greater than 1.
- For numbers greater than 1, it iterates from 2 to num/2 and checks if num is divisible by any number other than 1 and itself.
- If it finds such a number, it sets prime to false and breaks out of the loop.
- After checking all numbers, it prints whether each number is prime or not.
- In the main method, the isPrime method is called with the numbers 1, 2, 3, 4, and 5.
- The output will show whether each number is prime or not.
Source Code
public class PrimeChecker
{
static boolean isPrime(int... numbers)
{
boolean prime = true;
for (int num : numbers)
{
if (num <= 1)
{
prime = false;
}
else
{
for (int i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
prime = false;
break;
}
}
}
System.out.println(num + " is Prime ? " + prime);
}
return prime;
}
public static void main(String[] args)
{
isPrime(1, 2, 3, 4, 5);
}
}
Output
1 is Prime ? false
2 is Prime ? false
3 is Prime ? false
4 is Prime ? false
5 is Prime ? false