(conditions)? Statement 1: Statement 2
When the condition is true run statement 1
When the condition is false run statement 2
Statement 1 and type one of statement 2
The difference between ternary operator and If-else
Ternary operators can be simplified into if-else
Ternary operators require that a result be returned
If the code block can have more than one statement.
int j = 109;
int n1 = J & 15;
int n2 = (J >> 4) & 15;
String C1 = (N1 > 9)? (char) (n1-10 + ' a ') + "": (N1) + "";
String c2 = (N2 > 9)? (char) (n2-10 + ' a ') + "": (N2) + "";
String s = c1+ "" +C2;
System.out.println (s);
Converts 109 to 16 binary.
Train of thought displacement operation because 2 binary is converted to 16 binary is four-bit binary converted to one bit 16 binary
For example 60 (high ignore, all 0)
60
30 0
15 0
7 1
3 1
1 1
0 1
0011 1100 (32+16+8+4=60)
0011 1100
& 0000 1111
0000 1100 C
>> 4
0000 0011 (1100)
& 0000 1111
0000 0011 3
And then we know that 60 translates into a 16-in-one high is 3-low is C
You can then use the Swtich statement to convert. A represents ten B for 11 other invariant and so on
You can also use the method above. (char) (a–10 + ' a ') because a corresponds to a sum of ten ' a ' and the previous value after the strong transfer to get a character. (because characters can be computed directly, the value of their Unicode is calculated, and a Unicode value is turned back to be a character again.) )
Java Personal Learning Note: ternary