Java ternary operators and type casts

Source: Internet
Author: User

 Public class Yunsuanfu {    publicstaticvoid  main (string[] args) {        int a = 5;        System.out.println ("value is" + ((a<5)?) 10.9:9));}    }

Just see an interview problem, the first glance is very simple, a ternary operator, if you think the output of the result is 9, then the problem of the trap, pay attention to "((a<5)? 10.9:9)", There is a 10.9 in it, and the back is followed by a 9, which is the automatic type conversion of Java based on the operator's precision type, because there is a 10.9, so the subsequent 9 will be converted to 9.0, so the output is 9.0.

And look at the other one.

    char x= ' x ';     int i =10;    System.out.println (false ?) i:x);    System.out.println (false ?) Ten : x);    }

The result of the output is

x

int i=10; I is a variable, so the first output x is cast to int, i is int, the value of x is converted to int value is 120, so the first output is 120.

As for the second output, the Java specification mentions that when the latter two expressions have a constant expression (referred to as 10 above) and the other type is T (referred to as char above), and the constant expression can be represented by T, the output is the T type.

Since 10 is a constant, it can be represented by a char, and the result of the output is a char type, so it is X.

Does it feel like a bit of pit ~ ~

Java ternary operators and type casts

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.