ternary operator

There is only one ternary operator:?:, The syntax format of the ternary operator is as follows:

(expression) ? if-true-starement : if-false-statement;

The rule of ternary operator is to evaluate the logical expression first. If the logical expression returns true, the value of the second operand is returned. If the logical expression returns false, the value of the third operand is returned. See the following code.

String str = 5 > 3 ? " 5大于3 " :”5不大于3“

System.out.println(str); //输出”5大于3“

Most of the time, the ternary operator is used as the simplified writing method of if else. Therefore, if the above code is replaced by the writing method of if else, the code is as follows:

String str2 = null;
if(5 > 3)
{ 
    str2 = "5大于3";
}
else
{
    str2 = "5不大于3";
}

The effects of the two code writing methods are exactly the same. The difference between the ternary operator and the if else writing method is that the code block after if can have multiple statements, but the ternary operator does not support multiple statements. Ternary operators can be nested, and the nested ternary operators can handle more complex situations, as shown in the following code:

int a = 11;
int b = 12;
//三目运算符支持嵌套
System.out.println( a > b ? 
"a大于b" : (a
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>