Also, the ternary operator enables a form of "optional" parameter. Java does not allow optional parameters in method signatures but the ternary operator enables you to easily inline a default choice when null
is supplied for a parameter value.
For example:
public void myMethod(int par1, String optionalPar2) {
String par2 = ((optionalPar2 == null) ? getDefaultString() : optionalPar2)
.trim()
.toUpperCase(getDefaultLocale());
}
In the above example, passing null
as the String
parameter value gets you a default string value instead of a NullPointerException
. It's short and sweet and, I would say, very readable. Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.
Moreover, this pattern enables you to make the String
parameter truly optional (if it is deemed useful to do so) by overloading the method as follows:
public void myMethod(int par1) {
return myMethod(par1, null);
}