You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用三元运算符省略else条件?单行语句写法指导

Hey there! Let's tackle your two Java questions one by one.

1. How to "avoid" the else clause in a single-line ternary operator?

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.

2. Single-line replacement for your null-check if statement

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:27:29