Varargs Find Smallest Number in Java
Write a Java program demonstrating a method with varargs that finds the smallest number in a sequence of integers
- The class MinFinder contains a single static method findMin that takes a variable number of integers as input (using varargs).
- Inside the findMin method, it first checks if any numbers are provided. If not, it throws an IllegalArgumentException with the message "No numbers provided".
- It initializes the variable min with the first number in the array numbers.
- It then iterates through the remaining numbers in the array. If any number is less than the current min, it updates min to that number.
- Finally, it returns the minimum value found.
- In the main method, the findMin method is called with multiple integer arguments. The minimum value returned by findMin is printed to the console.
Source Code
public class MinFinder
{
static int findMin(int... numbers)
{
if (numbers.length == 0)
{
throw new IllegalArgumentException("No numbers provided");
}
int max = numbers[0];
for (int num : numbers)
{
if (num < max)
{
max = num;
}
}
return max;
}
public static void main(String[] args)
{
int max = findMin(80, 73, 65, 15, 39, 51);
System.out.println("Minimum Number is " + max);
}
}
Output
Minimum Number is 15