Interesting three-mesh operator "?:" in Java

Source: Internet
Author: User

Programs that have had a programming experience apes generally know the trinocular operator "?:", the following is a review of the use of this operator, the expression is: Condition?expression1:expression2.

That is, when condition is true, calculate exression1, otherwise calculate expression2, for example:

X<y?x:y

Returns the smaller of the values in X and Y.

Let's look at a few more examples below:

Example 1

        int i=55;        String s= (i<60)? " You ":(i<50)?" He ":" Me ";        System.out.println (s);


Because the trinocular operator is right-associative, the output is: you.

Example 2

        int i=8;        System.out.println (i<3?10.2:8);

Operation, Java will automatically type conversions based on the operator's precision type, so the output is: 8.0.

Example 3

int i=10;
Char a= ' a ';
System.out.println (FALSE?10:A);
System.out.println (FALSE?I:A);

The output is: a,97.

The Java programming specification mentions that when the latter two expressions have a constant expression (10 in the case) and the other type T (char in the case), while the constant expression can be represented by T, the output is the T type, so the first output is a; because I is a variable, type int, B is promoted to type int, so the second output is 97.

Interesting three-mesh operator "?:" in Java

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.