Adding Java Integer with a String

With the code example below, why the first addition (1/2 + 1/2) prints 0 and 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

+7
java string addition
source share
4 answers

Integer math (int 1 divided by int 2 is int 0 if you want the floating point result to discard one or both of the 1 and 2 floating point types) and the order of operations, the second example is String concatenation. The compiler turns this 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)); 
+4
source share

The first statement is "System.out.println (1/2 + 1/2 +" = 1/2 + 1/2 "); prints 0 because the integer value obtained from 1/2 is zero. The rest is discarded and since 1/2 is equal to 0.5, .5 is discarded. The second statement is "System.out.println (" 1/2 + 1/2 = "+ 1/2 + 1/2); prints 00 because of the concatenation sign. In the second expression, the first integer 1 is shown as +1, so the operator is actually read as (+1/2 +1/2), so it returns 00. If the second statement was configured as follows:

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

The result will be the same as the first statement.

0
source share

The expression evaluates from left to right. In the first case, it is int+int (which is 0 ), then int + "= String" , which is String tmp = "0= String" . Otherwise, you have "String =" + int which becomes "String = int" to which you append one more int`. So you print String, "0" and "0".

0
source share

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

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

-2
source share

All Articles