Find Maximum with Varargs in Java
Write a Java program demonstrating the usage of a method with varargs to find the maximum of a sequence of numbers
- The class MaxFinder contains a single static method findMax that takes a variable number of integers as input (using varargs).
- Inside the findMax 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 max with the first number in the array numbers.
- It then iterates through the remaining numbers in the array. If any number is greater than the current max, it updates max to that number.
- Finally, it returns the maximum value found.
- In the main method, the findMax method is called with multiple integer arguments. The maximum value returned by findMax is printed to the console.
Source Code
public class MaxFinder
{
static int findMax(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 = findMax(10, 86, 65, 5, 20, 15);
System.out.println("Maximum Number is " + max);
}
}
Output
Maximum Number is 86