javamethodsparametersoptional-parametersoption-type

Have multiple optional parameters in Java


I am trying to have optional parameters in my method. I found the boolean... test, and it works. But whenever I try it with a second one, it doesn't work.

Is there a possibility to put two or more (of same type eg: 2 optional booleans) in the parameter list?

Code I have now:

public void addJButton(boolean... yo){}

What I want:

public void addJButton(boolean... yo, boolean... yo2){}

Solution

  • As for the varargs-notation (boolean...): the varargs-parameter always has to be the last one, so you can only have one of these.

    You can consider passing null for omitted parameters or you could try some sort of method-overloading like Bathseba suggested.

    When going for the overloading you have to keep in mind that there are no named paramters, so only poosition and type can define which parameter is passed and which is omitted!!