7

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

Joshnee
  • 241
  • 4
  • 8
  • 1
    Because it goes from left to right. for the first one its going to be `1/2` which is `0` (integer division) and then `1/2` which is 0 again. So `0+0 = 0` then it will concat that onto the String `1/2+1/2`. For the second one it will do concat(1/2) onto the `String` "1/2+1/2=` which (1/2) is 0 again. and then again for the next one – 3kings Apr 02 '16 at 16:51

4 Answers4

4

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));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

The first statement "System.out.println(1/2+1/2+"=1/2+1/2");" prints 0 because an the integer value obtained from 1/2 is zero. The remainder is dropped and since 1/2 equals 0.5 the .5 is dropped. The second statement "System.out.println("1/2+1/2="+1/2+1/2);" prints out 00 because of the concatenation sign. In the second statement the first integer 1 is shown as +1 so the statement is actually being read as (+1/2 +1/2) which is why it returns 00. If the second statement was set up like this:

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

The output would be the same as the first statement.

JNicholas76
  • 31
  • 10
0

Expression is evaluated from left to right. In the first case it does int+int (which is 0), then int + "= String" which is a String tmp = "0= String". In the other case you have '"String =" + intwhich becomes"String =int"to which you append one moreint`. Thus you print String, "0" and "0".

sixtytrees
  • 1,156
  • 1
  • 10
  • 25
-2

java assumes that the result of the division is integer , since its members are integers. For the floating result ( 0.5 ) of each division , the divisor or the dividend should be of type float

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