Java Variable-length arguments

18-Sep-2024

Learn how to pass a variable number of arguments to a method in Java using varargs


We can pass a number of variable using variable length arguments. It is called varargs in Java. The syntax is data_type...  argument_name.


Examples:





public class LearnMethod {

public static void main(String[] args) {

loopNumbers(345,3,98,698,63,2,63,34);

}

public static void loopNumbers(int... numbers){
for (int i = 0; i < numbers.length; i++){
System.out.println(numbers[i]);
}
}

}


In the example we pass many values but in the method definition we catch all the values by using varargs. and loop on varargs to get all values.


Output:




345 3 98 698 63 2 63 34




There are some rules for using varargs


1. A method can have only one varargs

2. And the varargs must be the last agrument or parameter in the method


you should follow the rules otherwise you will get errors.


Comments