java - 为什么添加长变量会导致串联?

标签 java long-integer string-concatenation addition

Java 在执行加法时如何处理长变量?

错误的版本 1:

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

错误的版本 2:

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

正确的版本:

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

我不明白,为什么 Java 将它们连接起来。

谁能帮我,为什么要连接两个原始变量?

你好,你好

最佳答案

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

System.out.println("" + size + estimated); 

这个表达式从左到右求值:

"" + size        <--- string concatenation, so if size is 3, will produce "3"
"3" + estimated  <--- string concatenation, so if estimated is 2, will produce "32"

要让它工作,你应该这样做:

System.out.println("" + (size + estimated));

再次从左到右求值:

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

关于java - 为什么添加长变量会导致串联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/243045/

相关文章:

c - 试图理解指针加法和减法,但是

r - 如何使用R中的条件/for循环将单列数据转换为两列矩阵

r - 在 R 中将字符串识别为变量名

java 循环与 Integer.MAX_VALUE

javascript - 用逗号和空格连接两个字符串

java - 解释一下 Spring MVC Controller 的行为

java - 如何将 Firestore 数据导出到 Google Cloud Storage?

java - hibernate 序列不存在

java - ConcurrentHashMap 作为缓存

ios - 在iphone中显示长应用程序名称