Java算术: why aren't they "9 = 9"?

标签 java

我有一个关于 Java 整数和字符串算术的问题。例如,

int a = 1;
int b = 3;
int c = 5;
System.out.println(a + b + (c + " = ") + a + (b + c));
System.out.println((a + b) + c + " = " + a + b + c);
System.out.println(a + (b + c) + " = " + (a + b) + c);

上面的代码分别输出“45 = 18”、“9 = 135”和“9 = 45”。我不明白这个操作背后的逻辑。我的第一直觉是它们都输出“9 = 9”。我希望有人帮助我理解这个操作。感谢您的帮助!

最佳答案

加法是左关联的,但括号可以改变执行顺序。

因此,如果我们必须在这里分解第一个 println,当我们写入 a+b 时,它会导致算术加法(5),但是当我们执行 c + "= "+ a + b + c 时,会导致字符串连接 5=9,因为 c + "= " 首先求值,并将表达式作为 String + int 运算,从而产生字符串连接。请记住,int+intintString+intString

由于括号(),表达式的求值方式发生了变化。如果我们包含括号,这就是上面表达式的计算方式

(c + " = ") + a + (b + c)
 - First it evaluates (c + " = "), so the expression becomes 5 = + a + (b + c)
 - Now it evaluates b+c because of parenthesis, , so the expression becomes 5 = + a + 8
 - Now as there are not parenthesis, it evaluates the expression from left to 
   right and as the first operand is string, the whole expression becomes a
   string concatenation operation

第一个表达式的完整分解

a + b + (c + " = ") + a + (b + c)
- First precedence is of (b + c), so now it becomes a + b + (c + " = ") + a+8
- Next precedence  is of (c + " = "), so now it becomes a + b + "5 = " + a+8
- Now as there is not (), expression is evaluated from left to right, so
  now it evaluates a + b , so it becomes 4 + "5 = " + a+8
- now it evaluates '4 + "5 = "', so it becomes `45 = a + 8`, because we have 
  now a string in the expression, so it does string concatenation
- and it becomes `45 = 18`

类似地,你可以分解其他两个表达式

关于Java算术: why aren't they "9 = 9"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55253752/

相关文章:

java - 添加方法不在 RandomAccessFile 中添加 Student

java - 该程序的 if else 语句有什么问题?

java - Java 中是否可以替换数组?

java - 使用 Stream 比较两个集合 - anyMatch

java - 使用 Java 通过 USB 直接在 Epson Matrix 打印机上发送通用/文本

java - org.springframework.beans.factory.BeanCreationException 错误

java - getResourceAsStream() hell

java - 如何在 Java 中将对象数组写入文件?

java - 组件未从 ArrayList 中显示

java - 父子持久化中生成parent的ID