繁体   English   中英

标准输出流的歧义行为

[英]Ambiguous behavior of standard output stream

我想知道以下代码的第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);
                }
        }

输出:

8Message
Message35

为什么第二行代码包含35而不是8而不是35

运算符优先级

除赋值运算符外,所有二进制运算符均从左向右求值; 赋值运算符从右到左评估。

运算符+从左到右进行评估。

这就是为什么在第一种情况下它是加法。 第二种情况是字符串连接。

System.out.println(3+5+"Message");

从左到右评估表达式。 ++是整数,因此加号比+右是字符串连接。
让我们这样打破它(3+5+"Message")

3=integer
+=operator
5=integer

(3)integer (+) (5)integer = (8)integer,

而且比下一次通过

(8)integer (+) ("Message")String = (8Message)String

因此输出为8Message

System.out.println("Message"+3+5);

+运算符开始,这里有一个字符串,因此发生了连接。 因此,输出为Message35

Like the post above sais, you have operator precedence. Everything is evaluated from left to right.


System.out.println(3+5+"Message");

被翻译成

System.out.println((3+5)+"Message"); So first the addition happens and the result concatenates with the string.

在另一种情况下:

System.out.println("Message"+3+5);  

被翻译成

System.out.println(("Message"+3)+5);  

您有一个字符串和一个数字Message3 + 5 = Message53

我希望这可以清除它:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM