Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 514
J.P Avatar asked Mar 24 '26 05:03

J.P


2 Answers

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.

like image 136
Peter Lawrey Avatar answered Mar 25 '26 18:03

Peter Lawrey


Varargs are the variable number of arguments. It allows arguments from 0 to unlimited. Varargs are denoted by ... (triple dots). Varargs must be the last argument of the function. Consider the following program :

class Test
{
    static void display(Object ... o)
    {   
        for(Object o1 : o)
            System.out.print(o1+" ");
        System.out.println();
    }
    public static void main(String []args)
    {
        display();
        display(10,20,30,40,50);
        display(10.2f,20.3f,3.14f);
    }
}
like image 42
Pankti Avatar answered Mar 25 '26 19:03

Pankti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!