Java String Concatenation with + operator

后端 未结 5 1185
深忆病人
深忆病人 2020-11-28 15:57

I got confused with the String concatenation.

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


        
5条回答
  •  没有蜡笔的小新
    2020-11-28 16:52

    Addition is left associative. Taking the first case

    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
    

    In the second case:

    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
    

提交回复
热议问题