1

Anyone Know purpose of String.intern() using java programming...

If i use intern what is the difference between ordinary string and string.intern()

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
user3008032
  • 112
  • 12
  • This is a great thread explaining the same: http://stackoverflow.com/questions/1855170/when-should-we-use-intern-method-of-string-on-string-constants – sanket Dec 11 '13 at 07:17
  • See [`String#intern`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern%28%29) – Justin Dec 11 '13 at 07:18
  • Please refer this link. You can get good idea http://stackoverflow.com/questions/1091045/is-it-good-practice-to-use-java-lang-string-intern – Murali Dec 11 '13 at 07:22
  • even this (http://stackoverflow.com/questions/1855170/when-should-we-use-intern-method-of-string-on-string-constants) – dev2d Dec 11 '13 at 07:23
  • 1
    There are two suggestions to close this question as of now, but both suggestions state that it is a duplicate of questions that refer to using intern on string literals. This is a broader question, not a duplicate of these. – Jules Dec 11 '13 at 07:31

2 Answers2

1

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

rachana
  • 3,344
  • 7
  • 30
  • 49
1

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).

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289