Ternary operator "? : ", Syntax: condition expression? Expression 1: Expression 2;
This operation first calculates the value of the condition expression (bool type). If it is true, expression 1 is called, and expression 2 is called when it is flase. The logic is: "If it is true, execute the first, otherwise execute the second ."
Syntax
Test? Expression1: expression2
Test
Any Boolean expression.
Expression1
Expression returned when test is true. It may be a funny expression.
Expression2
Expression returned when test is false. It may be a funny expression.
Instance
The code is as follows: |
Copy code |
A = 3> 4? 3: 4; the output is 4. A = 3 <4? 3: 4; the output is 3.
|
Instance
The code is as follows: |
Copy code |
Int lenth = 10; String s; S = (lenth> 16? "Jihua.cnblogs.com": "Scheduler "); Console. WriteLine (s ); |
Here, condition is the Boolean expression to be calculated, true_value is the value returned when condition is true, and false_value is the value returned when condition is false. Jihua.cnblogs.com
In this example, if it is later than six o'clock P.M., a string containing "Good evening." is created. The equivalent code for using the if... else statement is as follows:
The code is as follows: |
Copy code |
Var now = new Date (); Var greeting = "Good "; If (now. getHours ()> 17) Greeting + = "evening ."; Else Greeting + = "day ."; |
Properly using the ternary operator can make the program very concise.