Java String Concatenation with + operator

后端 未结 5 1181
深忆病人
深忆病人 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:29

    Also, to add to this topic, as the wrong part of the answer of Jonathan Schober tipped me off on a thing to keep in mind:

    a+=something is not equal to a=a+ : the += evaluates the right side first, and only then adds it to the left side. So it has to be rewritten, it is equivalent to:

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

    Showing the difference

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

提交回复
热议问题