How do I use optional parameters in Java?

JavaOptional Parameters

Java Problem Overview


What specification supports optional parameters?

Java Solutions


Solution 1 - Java

There are several ways to simulate optional parameters in Java:

  1. Method overloading.

    void foo(String a, Integer b) { //... }

    void foo(String a) { foo(a, 0); // here, 0 is a default value for b }

    foo("a", 2); foo("a");

One of the limitations of this approach is that it doesn't work if you have two optional parameters of the same type and any of them can be omitted.

  1. Varargs.

a) All optional parameters are of the same type:

    void foo(String a, Integer... b) {
        Integer b1 = b.length > 0 ? b[0] : 0;
        Integer b2 = b.length > 1 ? b[1] : 0;
        //...
    }

    foo("a");
    foo("a", 1, 2);

b) Types of optional parameters may be different:

    void foo(String a, Object... b) {
        Integer b1 = 0;
        String b2 = "";
        if (b.length > 0) {
          if (!(b[0] instanceof Integer)) { 
              throw new IllegalArgumentException("...");
          }
          b1 = (Integer)b[0];
        }
        if (b.length > 1) {
            if (!(b[1] instanceof String)) { 
                throw new IllegalArgumentException("...");
            }
            b2 = (String)b[1];
            //...
        }
        //...
    }

    foo("a");
    foo("a", 1);
    foo("a", 1, "b2");

The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Furthermore, if each parameter has the different meaning you need some way to distinguish them.

  1. Nulls. To address the limitations of the previous approaches you can allow null values and then analyze each parameter in a method body:

    void foo(String a, Integer b, Integer c) { b = b != null ? b : 0; c = c != null ? c : 0; //... }

    foo("a", null, 2);

Now all arguments values must be provided, but the default ones may be null.

  1. Optional class. This approach is similar to nulls, but uses Java 8 Optional class for parameters that have a default value:

    void foo(String a, Optional bOpt) { Integer b = bOpt.isPresent() ? bOpt.get() : 0; //... }

    foo("a", Optional.of(2)); foo("a", Optional.absent());

    Optional makes a method contract explicit for a caller, however, one may find such signature too verbose.

    Update: Java 8 includes the class java.util.Optional out-of-the-box, so there is no need to use guava for this particular reason in Java 8. The method name is a bit different though.

  2. Builder pattern. The builder pattern is used for constructors and is implemented by introducing a separate Builder class:

    class Foo {
        private final String a; 
        private final Integer b;
    
        Foo(String a, Integer b) {
          this.a = a;
          this.b = b;
        }
    
        //...
    }
    
    class FooBuilder {
      private String a = ""; 
      private Integer b = 0;
      
      FooBuilder setA(String a) {
        this.a = a;
        return this;
      }
    
      FooBuilder setB(Integer b) {
        this.b = b;
        return this;
      }
    
      Foo build() {
        return new Foo(a, b);
      }
    }
    
    Foo foo = new FooBuilder().setA("a").build();
    
  3. Maps. When the number of parameters is too large and for most of the default values are usually used, you can pass method arguments as a map of their names/values:

    void foo(Map parameters) { String a = ""; Integer b = 0; if (parameters.containsKey("a")) { if (!(parameters.get("a") instanceof Integer)) { throw new IllegalArgumentException("..."); } a = (Integer)parameters.get("a"); } if (parameters.containsKey("b")) { //... } //... }

    foo(ImmutableMap.of( "a", "a", "b", 2, "d", "value"));

    In Java 9, this approach became easier:

    @SuppressWarnings("unchecked")
    static <T> T getParm(Map<String, Object> map, String key, T defaultValue) {
      return (map.containsKey(key)) ? (T) map.get(key) : defaultValue;
    }
    
    void foo(Map<String, Object> parameters) {
      String a = getParm(parameters, "a", "");
      int b = getParm(parameters, "b", 0);
      // d = ...
    }
    
    foo(Map.of("a","a",  "b",2,  "d","value"));
    

Please note that you can combine any of these approaches to achieve a desirable result.

Solution 2 - Java

varargs could do that (in a way). Other than that, all variables in the declaration 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);
}

Solution 3 - Java

There is optional parameters with Java 5.0. Just declare your function like this:

public void doSomething(boolean... optionalFlag) {
    //default to "false"
    //boolean flag = (optionalFlag.length >= 1) ? optionalFlag[0] : false;
}

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

Solution 4 - Java

You can use something like this:

public void addError(String path, String key, Object... params) { 
}

The params variable is optional. It is treated as a nullable array of Objects.

Strangely, I couldn't find anything about this in the documentation, but it works!

This is "new" in Java 1.5 and beyond (not supported in Java 1.4 or earlier).

I see user bhoot mentioned this too below.

Solution 5 - Java

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");
}

Solution 6 - Java

VarArgs and overloading have been mentioned. Another option is a Bloch 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.

Solution 7 - Java

In JDK>1.5 you can use it like this;

public class NewClass1 {

    public static void main(String[] args) {

        try {
            someMethod(18); // Age : 18
            someMethod(18, "John Doe"); // Age & Name : 18 & John Doe
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static void someMethod(int age, String... names) {

        if (names.length > 0) {
            if (names[0] != null) {
                System.out.println("Age & Name : " + age + " & " + names[0]);
            }
        } else {
            System.out.println("Age : " + age);
        }
    }
}

Solution 8 - Java

You can do thing using method overloading like this.

 public void load(String name){ }

 public void load(String name,int age){}

Also you can use @Nullable annotation

public void load(@Nullable String name,int age){}

simply pass null as first parameter.

If you are passing same type variable you can use this

public void load(String name...){}

Solution 9 - Java

Short version :

Using three dots:

public void foo(Object... x) {
    String first    =  x.length > 0 ? (String)x[0]  : "Hello";
    int duration    =  x.length > 1 ? Integer.parseInt((String) x[1])     : 888;
}   
foo("Hii", ); 
foo("Hii", 146); 

(based on @VitaliiFedorenko's answer)

Solution 10 - Java

Overloading is fine, but if there's a lot of variables that needs default value, you will end up with :

public void methodA(A arg1) {  }    
public void methodA(B arg2) {  }
public void methodA(C arg3) {  }
public void methodA(A arg1, B arg2) {  }
public void methodA(A arg1, C arg3) {  }
public void methodA(B arg2, C arg3) {  }
public void methodA(A arg1, B arg2, C arg3) {  }

So I would suggest use the Variable Argument provided by Java.

Solution 11 - Java

If it's an API endpoint, an elegant way is to use "Spring" annotations:

@GetMapping("/api/foos")
@ResponseBody
public String getFoos(@RequestParam(required = false, defaultValue = "hello") String id) { 
    return innerFunc(id);
}

Notice in this case that the innerFunc will require the variable, and since it's not api endpoint, can't use this Spring annotation to make it optional. Reference: https://www.baeldung.com/spring-request-param

Solution 12 - Java

You can use a class that works much like a builder to contain your optional values like this.

public class Options {
	private String someString = "default value";
	private int someInt= 0;
	public Options setSomeString(String someString) {
		this.someString = someString;
		return this;
	}
	public Options setSomeInt(int someInt) {
		this.someInt = someInt;
		return this;
	}
}

public static void foo(Consumer<Options> consumer) {
	Options options = new Options();
	consumer.accept(options);
	System.out.println("someString = " + options.someString + ", someInt = " + options.someInt);
}

Use like

foo(o -> o.setSomeString("something").setSomeInt(5));

Output is

someString = something, someInt = 5

To skip all the optional values you'd have to call it like foo(o -> {}); or if you prefer, you can create a second foo() method that doesn't take the optional parameters.

Using this approach, you can specify optional values in any order without any ambiguity. You can also have parameters of different classes unlike with varargs. This approach would be even better if you can use annotations and code generation to create the Options class.

Solution 13 - Java

Java now supports optionals in 1.8, I'm stuck with programming on android so I'm using nulls until I can refactor the code to use optional types.

Object canBeNull() {
    if (blah) {
        return new Object();
    } else {
        return null;
    }
}

Object optionalObject = canBeNull();
if (optionalObject != null) {
    // new object returned
} else {
    // no new object returned
}

Solution 14 - Java

This is an old question maybe even before actual Optional type was introduced but these days you can consider few things:

  • use method overloading
  • use Optional type which has advantage of avoiding passing NULLs around Optional type was introduced in Java 8 before it was usually used from third party lib such as Google's Guava. Using optional as parameters / arguments can be consider as over-usage as the main purpose was to use it as a return time.

Ref: https://itcodehub.blogspot.com/2019/06/using-optional-type-in-java.html

Solution 15 - Java

Default arguments can not be used in Java. Where in C#, C++ and Python, we can use them..

In Java, we must have to use 2 methods (functions) instead of one with default parameters.

Example:

Stash(int size); 

Stash(int size, int initQuantity);

http://parvindersingh.webs.com/apps/forums/topics/show/8856498-java-how-to-set-default-parameters-values-like-c-

Solution 16 - Java

We can make optional parameter by Method overloading or Using DataType...

|*| Method overloading :

RetDataType NameFnc(int NamePsgVar)
{
	// |* Code Todo *|
	return RetVar;
}

RetDataType NameFnc(String NamePsgVar)
{
	// |* Code Todo *|
	return RetVar;
}

RetDataType NameFnc(int NamePsgVar1, String NamePsgVar2)
{
	// |* Code Todo *|
	return RetVar;
}

Easiest way is

|*| DataType... can be optional parameter

RetDataType NameFnc(int NamePsgVar, String... stringOpnPsgVar)
{
	if(stringOpnPsgVar.length == 0)  stringOpnPsgVar = DefaultValue; 

	// |* Code Todo *|
	return RetVar;
}

Solution 17 - Java

If you are planning to use an interface with multiple parameters, one can use the following structural pattern and implement or override apply - a method based on your requirement.

public abstract class Invoker<T> {
    public T apply() {
        return apply(null);
    }
    public abstract T apply(Object... params);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike PoneView Question on Stackoverflow
Solution 1 - JavaVitalii FedorenkoView Answer on Stackoverflow
Solution 2 - JavalaginimainebView Answer on Stackoverflow
Solution 3 - JavabhootView Answer on Stackoverflow
Solution 4 - JavatheninjagregView Answer on Stackoverflow
Solution 5 - JavaDarioView Answer on Stackoverflow
Solution 6 - JavaYishaiView Answer on Stackoverflow
Solution 7 - Javaaz3View Answer on Stackoverflow
Solution 8 - JavaIshan FernandoView Answer on Stackoverflow
Solution 9 - JavaT.ToduaView Answer on Stackoverflow
Solution 10 - JavaJigar ShahView Answer on Stackoverflow
Solution 11 - JavaSophie CoopermanView Answer on Stackoverflow
Solution 12 - JavarybaiView Answer on Stackoverflow
Solution 13 - JavaPelletView Answer on Stackoverflow
Solution 14 - JavaxprophView Answer on Stackoverflow
Solution 15 - JavaParvinder SinghView Answer on Stackoverflow
Solution 16 - JavaSujay U NView Answer on Stackoverflow
Solution 17 - JavaMukundhanView Answer on Stackoverflow