Connection between Java string and operator

I'm confused about string connections

String s1 = 20 + 30 + "abc" + (10 + 10);
String s2 = 20 + 30 + "abc" + 10 + 10;
System.out.println(s1);
System.out.println(s2);

The output is:

I wonder why 20 and 30 are added together in both cases, but 10 and 10 need parentheses to be added (S1) rather than connected to the string (S2) Please explain how the string operator works here

Solution

Addition is the of the left League Take the first case

20+30+"abc"+(10+10)
-----       -------
  50 +"abc"+  20    <--- here both operands are integers with the + operator,which is addition
  ---------
  "50abc"  +  20    <--- + operator on integer and string results in concatenation
    ------------
      "50abc20"     <--- + operator on integer and string results in concatenation

In the second case:

20+30+"abc"+10+10
-----
  50 +"abc"+10+10  <--- here both operands are integers with the + operator,which is addition
  ---------
   "50abc"  +10+10  <--- + operator on integer and string results in concatenation
    ----------
    "50abc10"  +10  <--- + operator on integer and string results in concatenation
     ------------
      "50abc1010"   <--- + operator on integer and string results in concatenation
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>