C # operator "?" : "What is it?
C # operator "?" : "Is also called a conditional operator.
For conditional expression B? X: y. Calculate Condition B and then judge.
If the value of B is true, the value of x is calculated and the calculation result is the value of x. Otherwise, the calculation result is y.
A conditional expression never calculates x or y again. Conditional operators are associated to the right, that is, grouped from left to right.
C # operator "?" : "Operation instance:
Expression? B: c? D: e will press? B :( C? D: e.
? : The second and third operands control the type of the conditional expression. If x and y are the types of the second and third operands respectively, then:
● If x and y are of the same type, this type is the type of the conditional expression.
● Otherwise, if there is an implicit conversion from x to y, but there is no conversion from y to x, then y is the type of the conditional expression.
● Otherwise, if there is an implicit conversion from y to x, but there is no conversion from x to y, then x is the type of the conditional expression.
● Otherwise, no expression type is defined and an error occurs during compilation.
C # operator "?" : "I will introduce you to the basic content here. I hope you can understand and learn about the three-element operator of the C # Operator."? : "Is helpful.
The ternary operator is also a conditional operator. It seems special because it has three operands, but it does belong to one of the operators.
The format is
Boolean-exp? Value0: value1
If the boolean-exp expression returns true, value0 is calculated, and the calculation result is the final value produced by the operator. If the boolean-exp expression returns false, value1 is calculated. Similarly, the result is the final value of the operator.
Of course, it can also be replaced by if-else, but the ternary operator and if-else are completely different, and the operator will generate a value.
Copy codeThe Code is as follows: public class TernaryIfElse {
Static int ternary (int I ){
Return I <10? I * 100: I * 10;
}
Static int standardIfElse (int I ){
If (I <10)
Return I * 100;
Else
Return I * 10;
}
Public static void main (String [] args ){
System. out. println (ternary (9 ));
System. out. println (ternary (10 ));
System. out. println standardIfElse (9 ));
System. out. println standardIfElse (10 ));
}
}
Output
900
100
900
100
In contrast, the ternary operators are much more compact, and if-else is easier to understand.