public String intern()
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned.
intern() returns a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.
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.
string intern() method is used to create an exact copy of heap string object in string constant pool. The string objects in the string constant pool are automatically interned but string objects in heap are not. The main use of creating interns is to save the memory space and to perform faster comparison of string objects.
Example:
/** * * @author Arun.Singh * */ public class InternDemo { public static void main(String args[]) { String s1 = "Rakesh"; String s2 = "Rakesh"; String s3 = "Rakesh".intern(); String s4 = new String("Rakesh"); String s5 = new String("Rakesh").intern(); if (s1 == s2) { System.out.println("s1 and s2 are same"); // 1. } if (s1 == s3) { System.out.println("s1 and s3 are same"); // 2. } if (s1 == s4) { System.out.println("s1 and s4 are same"); // 3. } if (s1 == s5) { System.out.println("s1 and s5 are same"); // 4. } } }Output:
s1 and s2 are same s1 and s3 are same s1 and s5 are same
0 comments:
Post a Comment