如何用三元运算符省略else条件?单行语句写法指导
Hey there! Let's tackle your two Java questions one by one.
First, a quick heads-up: The ternary operator in Java follows the strict structure condition ? expressionIfTrue : expressionIfFalse—you can’t actually omit the else-equivalent second expression entirely. That said, you can simulate the effect of skipping an else clause by making the second branch do nothing meaningful for your use case.
For example, if you only want to update a variable when a condition is true (and leave it unchanged otherwise), instead of writing:
if (myCondition) { targetVariable = newValue; }
You can use the ternary operator like this:
targetVariable = myCondition ? newValue : targetVariable;
When the condition is false, we just assign the variable’s current value back to itself. This results in no effective change, which mimics "skipping" the else logic you wanted to avoid.
Looking at your existing code:
Boolean isCapital = city.isCapital(); String isCapitalName; if(isCapital == null) { isCapitalName = ""; }
First, make sure isCapitalName is initialized before this line (otherwise you’ll hit a compiler error for using an uninitialized variable). Assuming it’s already set, you can convert this to a single line using the ternary operator like so:
isCapitalName = isCapital == null ? "" : isCapitalName;
For a more readable null check (available in Java 7+), you can use Objects.isNull() instead of the direct == null comparison:
import java.util.Objects; // ... isCapitalName = Objects.isNull(isCapital) ? "" : isCapitalName;
This does exactly what your original code does: sets isCapitalName to an empty string only when isCapital is null, and leaves it as-is otherwise—no explicit else clause needed.
If isCapitalName wasn’t initialized before this line, you could adjust it to set a default value for the non-null case too (e.g., String isCapitalName = Objects.isNull(isCapital) ? "" : "Non-capital";), but based on your original code, the examples above are the closest match.
内容的提问来源于stack exchange,提问作者MiniSu

