简体   繁体   中英

Ambiguous behavior of standard output stream

I want to know why the line 5 and line 6 of the following code differs in output?

  /*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 ?

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=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

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

Here from begining around + operator there's a string hence concatenation takes place. Hence the output is 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

I hope this clears it :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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