Java String与运算符的连接

前端之家收集整理的这篇文章主要介绍了Java String与运算符的连接前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我对String连接感到困惑.
  1. String s1 = 20 + 30 + "abc" + (10 + 10);
  2. String s2 = 20 + 30 + "abc" + 10 + 10;
  3. System.out.println(s1);
  4. System.out.println(s2);

输出是:@H_403_5@

50abc20
50abc1010@H_403_5@

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

解决方法

加法是左联的.采取第一种情况
  1. 20+30+"abc"+(10+10)
  2. ----- -------
  3. 50 +"abc"+ 20 <--- here both operands are integers with the + operator,which is addition
  4. ---------
  5. "50abc" + 20 <--- + operator on integer and string results in concatenation
  6. ------------
  7. "50abc20" <--- + operator on integer and string results in concatenation

在第二种情况:@H_403_5@

  1. 20+30+"abc"+10+10
  2. -----
  3. 50 +"abc"+10+10 <--- here both operands are integers with the + operator,which is addition
  4. ---------
  5. "50abc" +10+10 <--- + operator on integer and string results in concatenation
  6. ----------
  7. "50abc10" +10 <--- + operator on integer and string results in concatenation
  8. ------------
  9. "50abc1010" <--- + operator on integer and string results in concatenation

猜你在找的Java相关文章