last exam we had the exercise to determine the output of the following code:
System.out.println(2 + 3 + ">=" + 1 + 1);
My answer was 5 >= 2
but now I realize that this is the wrong answer. It should be 5 >= 11
.
But why?
Because "adding" a string to anything results in concatenation. Here is how it gets evaluated in the compilation phase:
((((2 + 3) + ">=") + 1) + 1)
The compiler will do constant folding, so the compiler can actually reduce the expression one piece at a time, and substitute in a constant expression. However, even if it did not do this, the runtime path would be effectively the same. So here you go:
((((2 + 3) + ">=") + 1) + 1) // original
(((5 + ">=") + 1) + 1) // step 1: addition (int + int)
(("5>=" + 1) + 1) // step 2: concatenation (int + String)
("5>=1" + 1) // step 3: concatenation (String + int)
"5>=11" // step 4: concatenation (String + int)
You can force integer addition by sectioning off the second numeric addition expression with parentheses. For example:
System.out.println(2 + 3 + ">=" + 1 + 1); // "5>=11"
System.out.println(2 + 3 + ">=" + (1 + 1)); // "5>=2"
Number+number=number
number+string=string
string+number=string
etc.
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