Difference between Initializing string with new and “ ”

前端 未结 8 1482
离开以前
离开以前 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 08:59

    String str = new String(); // as there is new operator so you are creating an object of string. This is going to create extra space in memory. So wastage of memory and redundant.Its not advisable to use it until you are not creating some complex object.

    But String str ="qwerty" means that u are assigning it to str. As bot are stored in common pool. So its better to use this notation.

    0 讨论(0)
  • 2021-01-27 09:02

    I guess the below will be good

    String str; // Just declares the variable and the default will be null. This can be done in global scope or outer scope
    
    str = "where id" + unitID + "'"; // Initializing string with value when needed. This will be done in the inner scope.
    

    If declaration and initialization done in a line where the initialization contains dynamic text (unitID in your case) you can't do it globally. If Scope of the variable is not an issue then u may go ahead. Cheers!!

    0 讨论(0)
  • 2021-01-27 09:04

    As we know that String class is immutable so , String str="Hello String"; is the best way of using String class so we can avoid memory wastage.When string with the same value created.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-27 09:06

    I would suggest you to do in this way

    String dynamic = " where id='" + unitId + "'";
    
    String dynamic  = new String();// DON'T DO THIS!
    dynamic = " where id='" + unitId + "'";
    

    The statement creates a new String instance each time it is executed, and none of those object creations is necessary. The argument to the String constructor (" where id='" + unitId + "'") is itself a String instance, functionally identical to all of the objects created by the constructor. If this usage occurs in a loop or in a frequently invoked method, millions of String instances can be created needlessly. The improved version is simply the following:

    String dynamic = " where id='" + unitId + "'";
    
    0 讨论(0)
  • 2021-01-27 09:09

    You can use like this.

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("where id='");
    stringBuilder.append(unitId);
    stringBuilder.append("'");
    
    String dynamic = stringBuilder.toString();
    
    0 讨论(0)
提交回复
热议问题