为什么添加长变量会导致连接?

gue*_*rda 1 java string-concatenation addition long-integer

Java在执行添加时对长变量做了什么?

错误的版本1:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long time = speeds.size() + estimated; // time = 21; string concatenation??
Run Code Online (Sandbox Code Playgroud)

错误的版本2:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long time = estimated + speeds.size(); // time = 12; string concatenation??
Run Code Online (Sandbox Code Playgroud)

正确版本:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long size = speeds.size();
long time = size + estimated; // time = 3; correct
Run Code Online (Sandbox Code Playgroud)

我不明白,为什么Java连接它们.

任何人都可以帮助我,为什么两个原始变量连接起来?

问候,guerda

too*_*kit 21

我的猜测是你实际上在做类似的事情:

System.out.println("" + size + estimated); 
Run Code Online (Sandbox Code Playgroud)

此表达式从左到右进行评估:

"" + size        <--- string concatenation, so if size is 3, will produce "3"
"3" + estimated  <--- string concatenation, so if estimated is 2, will produce "32"
Run Code Online (Sandbox Code Playgroud)

要实现这一点,您应该:

System.out.println("" + (size + estimated));
Run Code Online (Sandbox Code Playgroud)

再次从左到右评估:

"" + (expression) <-- string concatenation - need to evaluate expression first
(3 + 2)           <-- 5
Hence:
"" + 5            <-- string concatenation - will produce "5"
Run Code Online (Sandbox Code Playgroud)