Neeraj Neeraj - 4 months ago 7
Java Question

Java Integer addition with String

With below code sample why the first addition (1/2+1/2) prints 0 but the second addition prints 00.

System.out.println(1/2+1/2+"=1/2+1/2");
System.out.println("1/2+1/2="+1/2+1/2);


Output:

0=1/2+1/2

1/2+1/2=00

Answer

Integer math (int 1 divided by int 2 is int 0, if you want a floating point result cast one, or both, of 1 and 2 to a floating point type) and order of operations, the second example is String concatenation. The compiler turns that into

 System.out.println(new StringBuilder("1/2+1/2=").append(1/2).append(1/2));

and then you get

 System.out.println(new StringBuilder("1/2+1/2=").append(0).append(0));