双变量实现和不同的输出

Bas*_*oid 1 java

我想知道为什么有两种不同的输出:

double a = 88.0;
System.out.println(a + 10); // 98.0
double result = 88.0;
System.out.println("The result is " + result + 10); // The result is 88.010
Run Code Online (Sandbox Code Playgroud)

khe*_*ood 5

评估时,"the result is " + result + 10 您正在评估String + double + int.

执行此操作时,double首先将其添加到字符串,创建另一个字符串,然后将int其添加到该字符串,并给出另一个字符串.

所以你得到:

"the result is " + result + 10
"the result is 88.0" + 10
"the result is 88.010"
Run Code Online (Sandbox Code Playgroud)

这不同于

"the result is " + (result+10)
Run Code Online (Sandbox Code Playgroud)

这会给

"the result is 98.0"
Run Code Online (Sandbox Code Playgroud)