Java ternary operator datatype conversion based on the first value?

Naveen Kumar :

I came across this thing which I havent noticed before.

Here is a normal expression

    int a = 5;
                  System.out.println(((a < 5) ? 0 : 9));

so this just prints 9 as an int. Now If I put the first value String instead of an int 0

    int a = 5;
                  System.out.println(((a < 5) ? "asd" : 9));

Here the value 9 is printed as a string and not as an int. To confirm this just try to add this with another integer

 int a = 5;
             System.out.println((((a < 5) ? 0 : 9) + 4)           );

Now this results in 13 but if you change the first value to string instead of an int 0 it gives a compile error

"The operator + is undefined for the argument type(s) Object&Serializable&Comparable<?>, int". 

I am confused with this compile error. What is actually behind this ? Thanks for explanation

Tom Hawtin - tackline :

The type of

(a < 5) ? "asd" : 9

is

Object&Serializable&Comparable<?>

You can see this in the compiler error later in the question. The int 9 is boxed to Integer and then the common type between that and String is found. So you are actually calling the println(Object) overload not println(String) or println(int). println(Object) calls toString on its argument.

If you try to apply + to a Object&Serializable&Comparable<?> then neither string concatenation or arithmetic is applicable, hence the compiler error.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=70354&siteId=1