java function 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

//Java 9 and above only    
@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"));

Example 3: java how to make a parameter optional

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

Example 4: java how to make a parameter optional

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

Example 5: 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);

Tags:

Java Example