In Java, you can use the ternary operator (also known as the conditional operator) to perform a null check and return a default value if the operand is null.
Here's an example of how to use the ternary operator to perform a null check in Java:
String str = null; String defaultStr = "Default"; String result = (str != null) ? str : defaultStr;
In this example, the ternary operator checks whether the value of str
is null. If the condition (str != null)
is true, the value of str
is returned. If the condition is false, the value of defaultStr
is returned.
The ternary operator can be used as a shorter alternative to an if
-else
statement:
String result; if (str != null) { result = str; } else { result = defaultStr; }
You can find more information about the ternary operator and how to use it in Java in the Java documentation.