8

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?

syb0rg
  • 8,057
  • 9
  • 41
  • 81
Chad D
  • 499
  • 1
  • 10
  • 17
  • 1
    it is an array, and you can access it like an array with variable name `arguments`. – jlordo Feb 06 '13 at 22:11
  • @jlordo i think precisely it is converted into array at run time . :) – PermGenError Feb 06 '13 at 22:15
  • It took much longer to type up this answer than to try for yourself... – NominSim Feb 06 '13 at 22:22
  • 2
    I'm wonder why this question has so many upvotes. This is duplicate question and answer is easy to find. http://stackoverflow.com/questions/6010862/what-is-the-meaning-of-the-three-dots-in-a-method-declaration, http://stackoverflow.com/questions/5224252/what-are-these-three-dots-in-parameter-types etc. For me this question is similar to question like "what does the word 'private' mean". – Alex Feb 27 '13 at 22:27
  • @syb0rg Why did you retag this question 25 times (edits 13-37) over a span of 18 days, simply adding or removing the same tag each time? – matts Feb 27 '13 at 23:28
  • @matts I was unsure whether or not the `method` tag was relevant or not. – syb0rg Feb 27 '13 at 23:31

2 Answers2

3

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);
Pshemo
  • 122,468
  • 25
  • 185
  • 269
PermGenError
  • 45,977
  • 8
  • 87
  • 106
0

As per other answer, it's a "varargs" parameter. Which is an array.

What many people don't realise is two important points:

  • you may call the method with no parameters: method1();
  • when you do, the parameter is an empty array

Many people assume it will be null if you specify no parameters, but null checking is unnecessary.


You can force a null to be passed by calling it like this:

method1((boolean[])null);

But I say if someone does this, let it explode.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • I'm no Java user but that looks more like passing an array of booleans (that happens to have been converted from `null`) than forcing a null to be passed. – foxesque Jan 17 '21 at 15:24