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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With