Varargs: passing a variable number of arguments to a method

From version 5 of Java you can call a method passing a variable number of arguments.
A variable of this type is called varargs, you can only use in a method signature and its syntax is the primitive type or object type followed by 3 dots (ellipsis).
An example is the following:

package eu.lucazanini.varargs;

public class Main {

    public static void main(String[] args) {
	varargs(1, 2);
    }

    public static void varargs(int... x) {
	System.out.println("varargs");
	for (int i : x) {
	    System.out.println(i);
	}
    }
}

where the variable x is an array containing all the values ​​passed (in this example x[0] is equal to 1).
This way has some limitations:

  1. you can use the variable varargs only one time in a method
  2. the variable varargs must be at the last place in the method signature

As variable varargs you can pass null or no value; in the above example the call varargs() is like varargs(new int[0]) where new int[0] is an empty array but not null.

In situations of ambiguity for overloaded methods the call to method with varargs is always loser as you see from the following examples:

  • example 1:
    package eu.lucazanini.varargs;
    
    public class Main {
    
        public static void main(String[] args) {
    	varargs(1, 2);
        }
    
        // not called
        public static void varargs(int... x) {
    	System.out.println("varargs");
    	for (int i : x) {
    	    System.out.println(i);
    	}
        }
    
        // called
        public static void varargs(int x, int y) {
    	System.out.println("int int");
    	System.out.println(x);
    	System.out.println(y);
        }
    }
    
  • example 2 (boxing):
    package eu.lucazanini.varargs;
    
    public class Main {
    
        public static void main(String[] args) {
    	varargs(1, 2);
        }
    
        // not called
        public static void varargs(int... x) {
    	System.out.println("varargs");
    	for (int i : x) {
    	    System.out.println(i);
    	}
        }
    
        // called
        public static void varargs(Integer x, Integer y) {
    	System.out.println("Integer Integer");
    	System.out.println(x);
    	System.out.println(y);
        }
    }
    
  • example 3 (widening):
    package eu.lucazanini.varargs;
    
    public class Main {
    
        public static void main(String[] args) {
    	varargs(1, 2);
        }
    
        // not called
        public static void varargs(int... x) {
    	System.out.println("varargs");
    	for (int i : x) {
    	    System.out.println(i);
    	}
        }
    
        // called
        public static void varargs(long x, long y) {
    	System.out.println("long long");
    	System.out.println(x);
    	System.out.println(y);
        }
    }
    

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.