Java String与运算符的连接

我对String连接感到困惑.
String s1 = 20 + 30 + "abc" + (10 + 10);
String s2 = 20 + 30 + "abc" + 10 + 10;
System.out.println(s1);
System.out.println(s2);

输出是:

50abc20
50abc1010

我想知道为什么在这两种情况下都会将20 30加在一起,但10 10需要括号才能被添加(s1)而不是连接到字符串(s2).请解释String运算符如何在这里工作.

解决方法

加法是左联的.采取第一种情况
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

在第二种情况:

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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...