The conditional operator (?:) is a ternary operator . The so-called "item" refers to the number of objects this operator participates in the operation. In other words, the conditional operator has three operands.
The conditional operator has the following form:
Expression1?Expression2:Expression3
During the operation, it is first judged whether expression 1 is true or not. If it is true, it is false. If expression 1 is true, then the result of the entire operation is the value of expression 2. If expression 1 is not true, then the result of the entire operation is The result is the value of expression 3.
Example:
publicclassMain{publicstaticvoidmain(String[]args){inta,b;a=1;b=(a==1)?2:3;//If a equals 1, set the value of b to 2, otherwise it is 3System .out.println(Valueofbis:+b);b=(a==10)?2:3;//If a equals 10, set the value of b to 2, otherwise it is 3System.out.println(Valueofbis: +b);}}
The running results are as follows:
Valueofbis:2Valueofbis:3