Java Personal Learning Note: ternary

Source: Internet
Author: User

(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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.