views:

12289

answers:

6

How do I use optional parameters in Java? What specification supports optional parameters?

+9  A: 

varags could do that (in a way). Other then that, all variables in the deceleration of the method must be supplied. If you want a variable to be optional, you can overload the method using a signature which doesn't require the parameter.

private boolean defaultOptionalFlagValue = true;

public void doSomething(boolean optionalFlag) {
    ...
}

public void doSomething() {
    doSomething(defaultOptionalFlagValue);
}
laginimaineb
yes, I finally found stuff on varargs and that sort of works.
Mike Pone
+5  A: 

There are no optional parameters in Java. What you can do is overloading the functions and then passing default values.

void SomeMethod(int age, String name) {
    //
}

// Overload
void SomeMethod(int age) {
    SomeMethod(age, "John Doe");
}
Dario
+5  A: 

Unfortunately Java doesn't support default parameters directly.

However, I've written a set of JavaBean annotations, and one of them support default parameters like the following:

protected void process(
        Processor processor,
        String item,
        @Default("Processor.Size.LARGE") Size size,
        @Default("red") String color,
        @Default("1") int quantity) {
    processor.process(item, size, color, quantity);
}
public void report(@Default("Hello") String message) {
    System.out.println("Message: " + message);
}

The annotation processor generates the method overloads to properly support this.

See http://code.google.com/p/javadude/wiki/Annotations

Full example at http://code.google.com/p/javadude/wiki/AnnotationsDefaultParametersExample

Scott Stanchfield
+5  A: 

VarArgs and overloading have been mentioned. Another option is a Builder pattern, which would look something like this:

 MyObject my = new MyObjectBuilder().setParam1(value)
                                 .setParam3(otherValue)
                                 .setParam6(thirdValue)
                                 .build();

Although that pattern would be most appropriate for when you need optional parameters in a constructor.

Yishai
A: 

It would depends on what you want to achieve, varargs or method overloading should solve most scenarios. Here some nice examples of how to use them:

http://blog.sleekface.com/in/java-core/method-with-optional-parameters/

but keep in mind not to over use method overloading. it brings confusion.

Marc
A: 

There is optional parameters with Java 1.5 onwards I think. Just declare your function like this:

public void doSomething(boolean...optionalFlag) { ... }

you could call with doSomething() or doSomething(true) now.

bhoot