Which one is correct and why:
String dynamic = new String();
dynamic = \" where id=\'\" + unitId + \"\'\";
Or
String dynamic = \" where id=\'\" + unitId + \"
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.
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.