Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 612
Joshnee Avatar asked Apr 02 '16 16:04

Joshnee


1 Answers

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));
like image 153
Elliott Frisch Avatar answered Sep 23 '22 18:09

Elliott Frisch