Anyone Know purpose of String.intern() using java programming...
If i use intern what is the difference between ordinary string and string.intern()
Anyone Know purpose of String.intern() using java programming...
If i use intern what is the difference between ordinary string and string.intern()
string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.
Also read String pooling
Interned String are stored in String pool rather than on general heap space. Prior to Java 7 this pool was in permgen area but from java 7 it has been moved to heap to prevent java.lang.OutOfMemoryError: PermGen space
error which leds to JVM crash.
To summarize interned string with same text(.equals() returns true) will point to same object in string pool i.e even == operation will give true. Normal Strings created with new() with same content(.equals() returns true) will give false to == operation as they point to two different objects.
You may want to go through a good article Busting java.lang.String.intern() Myths . I am sure it will clear most of your doubts(Article also contains Java examples you can execute to see the results yourself).