2013-03-11 71 views
6

我對字符串連接感到困惑。帶+運算符的Java字符串連接

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需要parenthese以便被添加(s1)而不是連接到字符串(s2)。請解釋String運算符+在這裏的工作原理。

+0

的可能的複製[字符串文字後,所有的+將被視爲字符串連接符爲什麼?] (HTTP://計算器。com/questions/34589340 /字符串後文字 - 所有將被處理的字符串連接 - 操作) – Raedwald 2016-01-08 08:10:00

回答

10

加法是關聯的。以第一種情況下

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 
1

添加到關聯的概念,可以確保使用括號總是配對的一個字符串,兩個整數從不加在一起整數,所以所需的連接操作將發生而不是加法。

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

會產生:

2030abc1010 
0

您需要先建立一個空字符串。

所以,這可能工作:

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

或者這樣:

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

第一個是好的,第二個沒有那樣做... – ppeterka 2013-03-12 09:22:38

0

您需要了解一些規則:
1,Java的操作者優先,最左到右
2,支架優先權比+優先。
3,結果爲sum,如果+兩邊的符號都是整數,否則是串接。

+0

感謝您的寶貴意見,它真的可以幫助我解決其他問題。 – shekhar 2013-03-22 03:57:52

1

此外,添加到這個話題,喬納森·肖伯的答案的錯誤部分放倒我關上的事情要記住:

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); 

    } 
}