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?
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.
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.
Syntax: (Triple dot ... ) --> Means we can add zero or more objects pass in an arguments or pass an array of type object.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With