Difference between Initializing string with new and “ ”

前端 未结 8 1483
离开以前
离开以前 2021-01-27 08:21

Which one is correct and why:

String dynamic = new String();
dynamic = \" where id=\'\" + unitId + \"\'\";

Or

String dynamic = \" where id=\'\" + unitId + \"         


        
相关标签:
8条回答
  • 2021-01-27 09:11
    String dynamic = new String();
    dynamic = " where id='" + unitId + "'";
    

    creates a binding to an empty string, and then dumps it completely by re-initializing it.

    String dynamic = " where id='" + unitId + "'";
    

    creates the binding and leaves it.

    The first one is unnecessary. Just go with the direct string literal.

    0 讨论(0)
  • 2021-01-27 09:18
    String dynamic = new String();   //created an String object
    dynamic = " where id='" + unitId + "'"; //overriding reference with new value
    

    Since string is immutable and now dynamic will store in common pool.

    And

    String dynamic = " where id='" + unitId + "'";
    

    Is again a literal and stores in common pool.

    So , String can be created by directly assigning a String literal which is shared in a common pool.

    It is uncommon and not recommended to use the new operator to construct a String object in the heap.

    So the line

    String dynamic = new String();
    

    Is redundant and allocating unnecessary memory in heap.

    Don't do that.

    Learn what happens in both the cases, then you come to know.

    • How can a string be initialized using " "?

    And finally, do not use much concatenation's with "+", cannot do much harm in lesser amount of concatenations. If you are dealing with larger amount prefer to use StringBuilder with append method.

    • String concatenation in Java - when to use +, StringBuilder and concat
    0 讨论(0)
提交回复
热议问题