1. Overview
1.概述
The ternary conditional operator ?: allows us to define expressions in Java. It’s a condensed form of the if-else statement that also returns a value.
三元条件运算符 ?:允许我们在Java中定义表达式。它是if-else语句的一种浓缩形式,也会返回一个值。
In this tutorial, we’ll learn when and how to use a ternary construct. We’ll start by looking at its syntax and then explore its usage.
在本教程中,我们将学习何时以及如何使用三元结构。我们将先看一下它的语法,然后探讨它的用法。
2. Syntax
2. 语法
The ternary operator ?: in Java is the only operator that accepts three operands:
Java中的三元操作符?:是唯一接受三个操作数的操作符。
booleanExpression ? expression1 : expression2
The very first operand must be a boolean expression, and the second and third operands can be any expression that returns some value. The ternary construct returns expression1 as an output if the first operand evaluates to true, expression2 otherwise.
第一个操作数必须是一个boolean表达式,第二个和第三个操作数可以是任何返回某个值的表达式。如果第一个操作数的值是true,那么三元结构就会返回expression1作为输出,否则就会返回expression2。
3. Ternary Operator Example
3.三元运算符实例
Let’s consider this if-else construct:
让我们考虑这个if-else结构。
int num = 8;
String msg = "";
if(num > 10) {
msg = "Number is greater than 10";
}
else {
msg = "Number is less than or equal to 10";
}
Here we have assigned a value to msg based on the conditional evaluation of num.
这里我们根据num的条件评估,给msg分配了一个值。
We can make this code more readable and safe by easily replacing the if-else statement with a ternary construct:
我们可以通过用三元结构轻松取代if-else语句,使这段代码更易读和安全。
final String msg = num > 10
? "Number is greater than 10"
: "Number is less than or equal to 10";
4. Expression Evaluation
4.表达式评估
When using a Java ternary construct, only one of the right-hand side expressions, i.e. either expression1 or expression2, is evaluated at runtime.
当使用Java三元结构时,只有右边的表达式之一,即表达式1或表达式2,在运行时被评估。
We can test that out by writing a simple JUnit test case:
我们可以通过编写一个简单的JUnit测试案例来测试。
@Test
public void whenConditionIsTrue_thenOnlyFirstExpressionIsEvaluated() {
int exp1 = 0, exp2 = 0;
int result = 12 > 10 ? ++exp1 : ++exp2;
assertThat(exp1).isEqualTo(1);
assertThat(exp2).isEqualTo(0);
assertThat(result).isEqualTo(1);
}
Our boolean expression 12 > 10 always evaluates to true, so the value of exp2 remained as-is.
我们的boolean表达式12 > 10总是评估为true,所以exp2的值保持原样。
Similarly, let’s consider what happens for a false condition:
同样地,让我们考虑一下对于一个false条件会发生什么。
@Test
public void whenConditionIsFalse_thenOnlySecondExpressionIsEvaluated() {
int exp1 = 0, exp2 = 0;
int result = 8 > 10 ? ++exp1 : ++exp2;
assertThat(exp1).isEqualTo(0);
assertThat(exp2).isEqualTo(1);
assertThat(result).isEqualTo(1);
}
The value of exp1 remained untouched, and the value of exp2 was incremented by 1.
exp1的值保持不变,exp2的值增加了1。
5. Nesting Ternary Operator
5.嵌套三元运算符
It’s possible for us to nest our ternary operator to any number of levels of our choice.
我们有可能将我们的三元运算符嵌套到我们选择的任何数量的层次。
So, this construct is valid in Java:
所以,这个结构在Java中是有效的。
String msg = num > 10 ? "Number is greater than 10" :
num > 5 ? "Number is greater than 5" : "Number is less than equal to 5";
To improve the readability of the above code, we can use braces () wherever necessary:
为了提高上述代码的可读性,我们可以在必要时使用大括号()。
String msg = num > 10 ? "Number is greater than 10"
: (num > 5 ? "Number is greater than 5" : "Number is less than equal to 5");
However, please note that it’s not recommended to use such deeply nested ternary constructs in the real world. This is because it makes the code less readable and difficult to maintain.
然而,请注意,不建议在现实世界中使用这种深度嵌套的三元结构。这是因为它使代码的可读性降低,难以维护。
6. Conclusion
6.结论
In this quick article, we learned about the ternary operator in Java. It isn’t possible to replace every if-else construct with a ternary operator. But it’s a great tool for some cases and makes our code much shorter and more readable.
在这篇快速文章中,我们了解了Java中的三元运算符。用三元运算符取代每个if-else结构是不可能的。但在某些情况下,它是一个很好的工具,可以使我们的代码更短、更易读。
As usual, the entire source code is available over on GitHub.
像往常一样,整个源代码都可以在GitHub上找到over。