This operator is rare because it has three operand objects. But it does belong to one of the operators because it will eventually generate a value. This is different from the normal IF-ELSE statements that are described in the latter sectionto of this chapter. An expression takes the following form:
Boolean expression? Value 0: value 1
If the result of Boolean expression is true, the value 0 is computed and its result becomes the value that is ultimately generated by the operator. However, if the result of a Boolean expression is False, the value 1 is computed and its result becomes the value that is ultimately generated by the operator.
Of course, you can also swap the normal If-else statement (described later), but the ternary operator is more concise. Although C is proud to be a concise language, and the introduction of ternary operators is mostly to demonstrate this high-efficiency programming, but if you intend to use it frequently, still need to do a little more thinking-it is easy to produce code that is very poor readability.
You can use conditional operators for your own "side effects", or for the values that it generates. However, it should usually be used for values, because that would make it possible to distinguish the operator from the If-else explicitly. Here's an example:
static int ternary (int i) {
Return I < 10? I * 100:i * 10; As you can see, if you write the above code in a normal if-else structure, the amount of code will be much larger than the above. as follows: static int alternative (int i) {if (I <) return I *, return i * 10;} But the second form is easier to understand and does not require more input. So when choosing the ternary operator, be sure to weigh the pros and cons.
Ternary operators for Java