I have seen most of times developer declares the string in below fashion
Approach 1:-
public void method1(){
String str1 ="Test";
}
Approach 2:-
Per my understanding better approach will be
public void method2(){
String str2 = new String("Test");
}
Again based on my understanding , Second approach is better than first, because String literal are interned and stored in permgen. So it will not be GC'ed even thread comes out of approach 1 but in second approach str2 will be GC'ed(Str 2 will not be interned) as thread comes out of method 2 and GC runs as it is stored in heap not permgen.
Is my understanding correct ?
Per mine understanding I should literal if same string is going to be created again and again as it will be good for performance point of view otherwise go for new String() so that can be GC'ed once not used ?
Linked related string-literal-String-Object
"Test"your second example is, if it's not a literal?WeakReferenceandSoftReference.Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.String. Now the question is when a copy is necessary if any change on it generates a new one that doesn't modify the original? Or does it creates the same sequence of chars in memory?String str1 ="Test"then only intern method is called and stored intern perm gen space, But when we create string with new operator likeString str2 = new String("Test")intern method is not called and new object is created which is stored in heap(not in perm gen)