簡體   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