Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the 3 dots in parameters?/What is a variable arity (...) parameter? [duplicate]

I am wondering how the parameter of ... works in Java. For example:

public void method1(boolean... arguments)
{
  //...     
}

Is this like an array? How I should access the parameter?

like image 902
Chad D Avatar asked Feb 06 '13 22:02

Chad D


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.

What is variable arity?

A variable arity (aka varargs) method is a method that can take a variable number of arguments. The method must contain at least one fixed argument.

How do you use three dots in Java?

Syntax: (Triple dot ... ) --> Means we can add zero or more objects pass in an arguments or pass an array of type object.

What is parameters in Java?

A parameter is a variable used to define a particular value during a function definition. Whenever we define a function we introduce our compiler with some variables that are being used in the running of that function. These variables are often termed as Parameters.


1 Answers

Its called Variable arguments or in short var-args, introduced in Java 1.5. The advantage is you can pass any number of arguments while calling the method.

For instance:

public void method1(boolean... arguments) throws Exception {
    for(boolean b: arguments){ // iterate over the var-args to get the arguments.
       System.out.println(b);
    }
 }

The above method can accept all the below method calls.

method1(true);
method1(true, false);
method1(true, false, false);
like image 105
PermGenError Avatar answered Sep 28 '22 03:09

PermGenError