Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Arrays and 3 dots (Varargs) in java

Tags:

java

I cannot figure out that what are the differences between ... in java and arrays also array list, especially array list.

Both we can use as unlimited but ... is rarely used.

Please help thanks in advance.

like image 584
user1550048 Avatar asked Jul 24 '12 22:07

user1550048


People also ask

What does 3 dots mean in Java?

The "Three Dots" in java is called the Variable Arguments or varargs. It allows the method to accept zero or multiple arguments. Varargs are very helpful if you don't know how many arguments you will have to pass in the method.

Is Java Varargs an array?

Every time we use varargs, the Java compiler creates an array to hold the given parameters. In this case, the compiler creates an array with generic type components to hold the arguments. The varargs usage is safe if and only if: We don't store anything in the implicitly created array.

Can you pass an array for Varargs?

If you're passing an array to varargs, and you want its elements to be recognized as individual arguments, and you also need to add an extra argument, then you have no choice but to create another array that accommodates the extra element.

What does Varargs do in Java?

Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs. The syntax for implementing varargs is as follows: accessModifier methodName(datatype… arg) { // method body }


1 Answers

The three dots can only be used in a method argument, and are called 'varargs'. It means you can pass in an array of parameters without explicitly creating the array.

private void method(String[] args) {} is called like method(new String[]{"first", "second"});

private void method(String... args) {} is called like method("first", "second");

like image 117
Jorn Avatar answered Sep 28 '22 06:09

Jorn