String Constant Pool is possible only because String is immutable in Java and its implementation of the String interning concept. The string pool is also an example of a Flyweight design pattern.

String Pool Examples

String s1 = "Hello";
String s2 = "Hello";
String s3 = "Hel" + "lo";
String s4 = "Hel" + new String("lo");
String s5 = new String("Hello");
String s6 = s5.intern();
System.out.println(s1 == s2);  // true
System.out.println(s1 == s3);  // true
System.out.println(s1 == s4);  // false
System.out.println(s4 == s5);  // false
System.out.println(s1 == s6);  // true


So as you can see, the reference of s1, s2, s3, and s6 are the same.

Actually, the object of s4 and s5 are stored in the Heap of JVM, and String Constants are stored in the Method Area of JVM.

Something about intern()

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.


The Disqus comment system is loading ...
If the message does not appear, please check your Disqus configuration.