Setting a default value w/o Null

2015-10-13

In a constructor or other method, instead of using code like:

1
String value = (input == null) ? "default" : input;

you can use something like this:

1
2
3
4
5
// Guava
String value = Optional.fromNullable(input).or("default");
//JDK 8
String value = Optional.ofNullable(input).orElse("default");


Comments: