java method optional parameter code example

Example 1: java how to make a parameter optional

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

Example 2: java how to make a parameter optional

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

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

Example 3: java how to make a parameter optional

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

foo("a", null, 2);

Example 4: java how to make a parameter optional

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

Example 5: java how to make a parameter optional

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

Tags:

Java Example