Type conversion of int and string, java
last exam we had the exercise to determine t开发者_高级运维he 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?
Assuming that your syntax is :
System.out.println(2 + 3 + ">=" + 1 + 1);
expressions are evaluated from left to right, in this case 2 + 3 get summed to 5 and when "added" to a string result in "5 >=", which when added to 1 gives "5 >= 1", add another 1 and your result is: "5 >= 11"
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.
It is evaluated from left to right. You concatenate"1" to "5 >=" and finally "1" to "5 >= 1".
Let's read it one token at a time from left to right:
The first literal encountered is an integer, 2, then a +, then another integer, 3. A + between two integers is addition, so they are added together to be 5.
Now we have 5, an integer, then a +, then a String ">=". A + between an integer and a String is a concatenation operator. So the Strings are combined to form "5>=".
Then we have "5>=", a String, a +, and then an integer, 1. This is String concatenation again. So the result is "5>=1".
Finally we have "5>=1", a String, a +, and the a 1. his is String concatenation again. So the result is "5>=11".
加载中,请稍侯......
精彩评论