what is the use of the intern() method
intern
strings gives the simplicity to compare strings with ==
(faster) instead of equals
function where non-intern can't use the ==
operator for equality.
String s = new String(“hello”);
new
will assign memory to s
in heap instead of internal set of unique strings which is maintained by VM ,also known as SCP.All strings found in class at the time of loading calls, are automatically interned(with strong-reference) which leads to efficient memory use.
Calling intern()
on s
string literal will add a weak-reference(short-time) of s
in SCP and also returned that reference so GC
will surely free heap memory consumed by s
.
Weak-reference will also be deleted when it is no longer used hence again leads to efficient memory management.
When exactly the object is created in string constant pool
String will be added to SCP temorarly, either with direct double quotes
(String s="sytax";) syntax or calling intern()
.
when we use new operator?
Avoid it as much as you can with strings or never.