Why Concatenation of two string objects reference

2019-02-15 14:28发布

问题:

This question already has an answer here:

  • How do I compare strings in Java? 23 answers

Why below s3 and s5 String objects are differ, When s5 try to created in String pool it checks content s3 already have same content so s5 refers s3 object in string pool. But my assumption is wrong, then any one correct me.

       String s1="Buggy";
       String s2="Bread";

       String s3="BuggyBread";

       String s4 = "Buggy"+"Bread"; 
       String s5 = s1 + s2 
     System.out.println(s3==s4); // True
     System.out.println(s3==s5); //false

回答1:

  1. String s4 = "Buggy" + "Bread";

    The compiler is smart enough to realize this is just the constant BuggyBread which is already referenced in s3. In other words, s4 references the same String as s3 that is in the string pool.

  2. String s5 = s1 + s2;

    Here the compiler faithfully translates to a StringBuilder-based concatenation of the contents of the variables, which yields a difference reference than s3. In other words, this is similar to:

    StringBuilder sb = new StringBuilder(s1);     
    sb.append(s2);
    String s5 = sb.toString();
    


回答2:

 Just try this   
  String s = "Buggy";
  s = s.concat("Bread");
  System.out.println(s);


标签: java string core