Why Concatenation of two string objects reference not equal to same content string object [duplicate]

人走茶凉 提交于 2019-12-30 07:31:07

问题


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


来源:https://stackoverflow.com/questions/30275117/why-concatenation-of-two-string-objects-reference-not-equal-to-same-content-stri

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!