There are several ways to simulate optional parameters in Java.

Method overloading

Copyvoid 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.

Varargs

a) All optional parameters are of the same type:

Copyvoid 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:

Copyvoid 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.

Nulls

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

Copyvoid 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.

Optional class

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

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

foo("a", Optional.of(2));
foo("a", Optional.<Integer>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.

Builder pattern

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

Copyclass 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();

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:

Copyvoid foo(Map<String, Object> 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.<String, Object>of(
    "a", "a",
    "b", 2, 
    "d", "value")); 

In Java 9, this approach became easier:

Copy@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.

Answer from Vitalii Fedorenko on Stack Overflow
🌐
Reddit
reddit.com › r/java › opinions on using optional as parameter
r/java on Reddit: Opinions on using Optional<> as parameter
January 23, 2022 -

I like using Optional<> to return values that may be null but today I saw people using them to accept parameters that may be null, if the parameter wasn't an Optional<> then it couldn't be null. I personally don't like doing that but I'd like to hear some opinions.

They were doing things like

double getStartingBalance(@NotNull Optional<UUID> user) { ... }

In my opinion, Optional<> is used to force the developer to handle null values. If my method is called and may return null, I'll return an Optional<> to make sure that null is handled but if I design the method and define that something cannot be null I can just use Objects#requereNonNull or if it can be null a simple check does the job. Also having to box values in optionals and having to use Optional.empty() for nulls to call a method is messy and makes the call harder to read.

So what are your opinions on using optionals as parameters?

Top answer
1 of 16
1975

There are several ways to simulate optional parameters in Java.

Method overloading

Copyvoid 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.

Varargs

a) All optional parameters are of the same type:

Copyvoid 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:

Copyvoid 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.

Nulls

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

Copyvoid 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.

Optional class

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

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

foo("a", Optional.of(2));
foo("a", Optional.<Integer>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.

Builder pattern

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

Copyclass 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();

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:

Copyvoid foo(Map<String, Object> 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.<String, Object>of(
    "a", "a",
    "b", 2, 
    "d", "value")); 

In Java 9, this approach became easier:

Copy@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.

2 of 16
595

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.

Copyprivate boolean defaultOptionalFlagValue = true;

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

public void doSomething() {
    doSomething(defaultOptionalFlagValue);
}
Discussions

coding style - Java (or other Java-like languages): Best practice for many optional parameters? - Software Engineering Stack Exchange
Code design question for Java or ... such as Javascript flavors): You would like to implement a method with the following features: Take N parameters, for some reasonably large but finite value of N (like N > 2). O(N) of those parameters (as in, the vast majority of those parameters) are optional... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 7, 2019
Optional/Named Arguments for Java
🌐 news.ycombinator.com
1
1
March 8, 2026
Opinions on using Optional<> as parameter

The designers of Optional explicitly warn against using it as method parameters (e.g. https://stackoverflow.com/a/26328555).

More on reddit.com
🌐 r/java
170
113
January 23, 2022
How do I make parameters optional?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
7
2
August 31, 2023
🌐
Stackify
stackify.com › optional-parameters-java
Optional Parameters in Java: Strategies and Approaches-Stackify
April 10, 2024 - In this article, we’ve looked at a variety of strategies for working with optional parameters in Java, such as method overloading, the builder pattern, and the ill-advised strategy of allowing callers to supply null values.
🌐
FavTutor
favtutor.com › blogs › java-optional-parameters
Optional Parameters in Java Explained (with code)
August 23, 2023 - Optional Parameters mean even if a user is not providing the arguments, the function will get executed without any error. In the following sections, we will discuss multiple ways to implement optional parameters in java.
🌐
Rosetta Code
rosettacode.org › wiki › Optional_parameters
Optional parameters - Rosetta Code
1 week ago - Java has no optional parameters, but methods can be overloaded on the number and types of arguments, which can be used to effectively achieve optional positional parameters.
Find elsewhere
🌐
JetBrains
jetbrains.com › help › inspectopedia › OptionalUsedAsFieldOrParameterType.html
'Optional' used as field or parameter type | Inspectopedia Documentation
March 31, 2026 - Using a field with the java.util.Optional type is also problematic if the class needs to be Serializable, as java.util.Optional is not serializable. ... class MyClass { Optional<String> name; // Optional field // Optional parameter void setName(Optional<String> name) { this.name = name; } }
🌐
Baeldung
baeldung.com › home › java › core java › optional as a record parameter in java
Optional as a Record Parameter in Java | Baeldung
January 16, 2024 - Typically, before Java 8, we used null to represent the empty state of an object. However, a null as a return value requires null-check validation from the caller code in runtime. If the caller doesn’t validate, it might get a NullPointerException. And getting the exception is sometimes used to identify the absence of value. The main goal of Optional is to represent a method return value that represents the absence of a value.
🌐
DZone
dzone.com › articles › optional-method-parameters
Optional Method Parameters
February 28, 2017 - Would that stop you from using Java? Obviously not. Ah, us clean coders! Such a good movement, but sometimes we tend to overdo things. But yes, that could be a code smell, especially if that one thing would be the conditional logic we talked about earlier. I’m not so sure if it would be so evil if the logic looked like this: public void myMethod(Optional<String> optionalArgument) { // some code String argument = optionalArgument.orElse("reasonable default"); doSomething(argument); // some code }
🌐
GitConnected
levelup.gitconnected.com › an-argument-for-using-optional-as-input-parameters-43b13fe6dfce
An argument for using Optional as input parameters | by Petre Popescu | Level Up Coding
December 23, 2022 - There is an ongoing debate in the Java community regarding Optional and if it should be used as input parameters for methods or only as return values. Most people, including big names from the Java ecosystem, advocate for using Optional only as output. Even [Sonar has a rule](https://rules.sonarsource.com/java/RSPEC-3553) that grants a “Major” severity for Optional as parameter.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Java optional parameters - Java Code Geeks
November 23, 2018 - Brian Goetz, who is Java language architect at Oracle once stated that Optional was added to the standard library with methods’ results in mind, not their inputs. But software developers are rebels and don’t like listening to authorities. This argument may also seems weak. We have to go deeper. ... The parameter can be either a wrapped value or the empty optional instance.
🌐
ThisCodeWorks
thiscodeworks.com › optional-parameters-in-java-4-different-methods-with-code › 63bba52b89ee9c001559a9cf
Optional Parameters in Java: 4 Different Methods (with code) | thiscodeWorks
In this article, we will learn about the optional parameters in java and implementation using different methods with syntax and example: https://favtutor.com/blogs/java-optional-parameters
🌐
W3Schools
w3schools.com › java › java_methods_param.asp
Java Method Parameters
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A ... Information can be passed to methods as a parameter.
🌐
GitHub
github.com › Auties00 › NamedParameters
GitHub - Auties00/NamedParameters: Named and Optional parameters for Java 17 · GitHub
If you want to make a parameter optional, you can do so by applying the @Option annotation:
Starred by 44 users
Forked by 4 users
Languages   Java
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
April 21, 2026 - If a value is present the result must include its string representation in the result. Empty and present Optionals must be unambiguously differentiable. ... Java™ Platform Standard Ed.
🌐
Xperti
xperti.io › home › optional parameters in java: common strategies and approaches
Java Optional Parameters Approach In Code Practice
February 4, 2026 - When a method is written in Java code, all the required parameters are listed. In certain situations, the developer may not know the exact number of arguments that will be provided to this function at the time of declaring it. In such a case, Java optional parameter allow additional parameters that were initially not defined.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › util › Optional.html
Optional (Java SE 11 & JDK 11 )
January 20, 2026 - java.util.Optional<T> Type Parameters: T - the type of value · public final class Optional<T> extends Object · A container object which may or may not contain a non-null value. If a value is present, isPresent() returns true. If no value is present, the object is considered empty and isPresent() ...
🌐
Medium
medium.com › @bubu.tripathy › clean-code-optional-parameters-327d67abbf90
Clean Code: Optional Parameters. When dealing with optional parameters… | by Bubu Tripathy | Medium
February 26, 2024 - ⭐️ If you’re using Java 8 or later, you can leverage default parameter values in interfaces to provide default values for optional parameters.