繁体   English   中英

带有+运算符的Java String Concatenation

[英]Java String Concatenation with + operator

我对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

添加到关联性的概念,您可以确保永远不会将两个整数添加到一起,使用括号始终将字符串与整数配对,以便进行所需的连接操作而不是添加。

String s4 = ((20 + (30 + "abc")) + 10)+10;

会产生:

2030abc1010

另外,为了补充这个话题,Jonathan Schober的答案的错误部分让我想到了一件事:

a+=something不等于a=a+<something>+=评估右侧,然后才将其添加到左侧。 所以它必须重写,它相当于:

a=a+(something); //notice the parentheses!

显示差异

public class StringTest {
  public static void main(String... args){
    String a = "";
    a+=10+10+10;

    String b = ""+10+10+10;

    System.out.println("First string, with += : " + a);
    System.out.println("Second string, with simple =\"\" " + b);

  }
}

您需要以空字符串开头。

所以,这可能有效:

String s2 = ""+20+30+"abc"+10+10; 

或这个:

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

你需要知道一些规则:
1,Java运算符优先级,大多数是从左到右
2,括号优先于+符号优先。
3,结果为sum,如果+符号的两边都是整数,则为连接。

暂无
暂无

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

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