[英]Ambiguous behavior of standard output stream
I want to know why the line 5 and line 6 of the following code differs in output? 我想知道以下代码的第5行和第6行的输出为何不同?
/*1*/ class A
/*2*/ {
/*3*/ public static void main(String[] args)
/*4*/ {
/*5*/ System.out.println(3+5+"Message");
/*6*/ System.out.println("Message"+3+5);
}
}
Output: 输出:
8Message
Message35
Why the second line code has 35
and not 8
instead of 35
? 为什么第二行代码包含
35
而不是8
而不是35
?
Operator precedence . 运算符优先级 。
All binary operators except for the assignment operators are evaluated from left to right;
除赋值运算符外,所有二进制运算符均从左向右求值; assignment operators are evaluated right to left.
赋值运算符从右到左评估。
The operator + is evaluated left-to-right. 运算符+从左到右进行评估。
That is why in first case it is addition. 这就是为什么在第一种情况下它是加法。 And in second case it is String concatenation.
第二种情况是字符串连接。
System.out.println(3+5+"Message");
Expression is evaluate from left to right. 从左到右评估表达式。 Left and right
+
is integer hence addition and than right of +
is string concatenation. 左
+
右+
是整数,因此加号比+
右是字符串连接。
Let's break it this way (3+5+"Message")
让我们这样打破它
(3+5+"Message")
3=integer
+=operator
5=integer
(3)integer (+) (5)integer = (8)integer,
And than on next pass 而且比下一次通过
(8)integer (+) ("Message")String = (8Message)String
Therefore output is 8Message
因此输出为
8Message
System.out.println("Message"+3+5);
Here from begining around +
operator there's a string hence concatenation takes place. 从
+
运算符开始,这里有一个字符串,因此发生了连接。 Hence the output is Message35
因此,输出为
Message35
Like the post above sais, you have operator precedence. Everything is evaluated from left to right.
System.out.println(3+5+"Message");
is translated to 被翻译成
System.out.println((3+5)+"Message"); So first the addition happens and the result concatenates with the string.
In the other case: 在另一种情况下:
System.out.println("Message"+3+5);
is translated to 被翻译成
System.out.println(("Message"+3)+5);
You have a String and a number Message3 + 5 = Message53 您有一个字符串和一个数字Message3 + 5 = Message53
I hope this clears it :) 我希望这可以清除它:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.