Difference between Initializing string with new and “ ”

前端 未结 8 1484
离开以前
离开以前 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:05

    Short answer:

    String str = new String();
    

    creates a new String object on the heap. When you do afterwards:

    str = "Hello, String Pool";
    

    You simply overwrite the reference to the first object with another reference. Thus, the first object is lost. Keep this in mind: Strings are immutable.

提交回复
热议问题