Neeraj Neeraj - 1 year ago 88
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.





Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download