Mr.Master Mr.Master - 3 months ago 17
Java Question

How realy work Varargs in java?

I am now learning Varargs in java.
I wrote this method:

public static void vrati(Object... arguments){
for(Object i : arguments)

System.out.println(i);
}


Then I called the method:

main.vrati(8,2,"String");


So my question is: does varargs cast primitive types to object?
Because I have mixed in int and String in this method call and can access them like is one object.

Answer

So my question does varargs cast primitive types to object?

It casts to the type of the array. If you have

a(int... ints)

They will be int

and if you have

b(double... doubles)

they will be doubles even if you write b (1, 2.0f, 10L)

If you have an

c(Object... obj)

it will autobox primitives. This is not a feature of var-args but how types are autoboxed as needed anyway.

Comments