Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ternary operator datatype conversion based on the first value?

Tags:

java

operators

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

like image 469
Naveen Kumar Avatar asked Oct 17 '22 08:10

Naveen Kumar


2 Answers

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.

like image 75
Tom Hawtin - tackline Avatar answered Nov 15 '22 07:11

Tom Hawtin - tackline


The type of the expression (a < 5) ? "asd" : 9 depends on the types of the 2nd and 3rd operands - "asd" and 9. The only common type to those two operands is Object (if the int is boxed to Integer).

Therefore the type of the expression is Object, Java has no + operator that accepts Object and int as operands. Hence the compilation error.

In

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

the type of the ternary conditional expression is int, and int and int are acceptable operands of the + operator.

like image 23
Eran Avatar answered Nov 15 '22 05:11

Eran