Table of Contents
Java variable arguments was introduced in java 5 and it allows methods to take as many number of arguments you want.
Syntax:
We use three dots (…) also known as ellipsis to define variable arguments.
1 2 3 4 5 6 |
public void method (String a,int ... b) { } |
There are some points which you need to keep in mind while using varargs methods:
- You can have only one variable arguments (ellipsis) in one method
- varargs should be last parameter in the method, otherwise method won’t compile.
Why to use variable arguments or varargs methods:
There are two alternatives which can be used which developers used before java 1.5
- Method overloading
- Passing array to the method
Method overloading may not be good idea because you don’t know number of methods you need to overload.You can pass arguments in the array but why don’t we can directly use varargs method and let compiler create array for us.
How varargs works internally.
Lets say you have method signature as below:
1 2 3 4 5 6 |
public void method (String a,int b,int ... c) { } |
and you invoke this method as
1 2 3 |
method("test",1,2,3,4) |
then “test” and 1 will be passed as normal parameters and 2,3 and 4 will be passed as array.
Java variable arguments or varargs example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package org.arpit.java2blog; public class VarArgsMainJava { public static void main(String[] args) { method("test",1,2,3,4,5); anotherMethod(10,20,30,40,50); } public static void method (String a,int b,int ... c) { System.out.println("Method arguments are"); System.out.print(a); System.out.print(" "+b); for (int i = 0; i < c.length; i++) { System.out.print(" "+c[i]); } System.out.println(); } public static void anotherMethod (int b,int ... c) { System.out.println("Method arguments are"); System.out.print(b); for (int i = 0; i < c.length; i++) { System.out.print(" "+c[i]); } } } |
1 2 3 4 5 6 |
Method arguments are test 1 2 3 4 5 Method arguments are 10 20 30 40 50 |