Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type conversion of int and string, java

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?

like image 681
UpCat Avatar asked Dec 08 '10 18:12

UpCat


2 Answers

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"
like image 88
cdhowie Avatar answered Oct 29 '22 11:10

cdhowie


Number+number=number
number+string=string
string+number=string
etc.
like image 26
Kendrick Avatar answered Oct 29 '22 11:10

Kendrick