The String Constant Pool

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

Instructions

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.

String-Pool

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.

Reference

  • http://renxiangzyq.iteye.com/blog/549554
  • http://www.journaldev.com/797/what-is-java-string-pool
  • http://examples.javacodegeeks.com/core-java/lang/string/java-string-pool-example/
  • http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()
Contact Us
  • Nanyang Technological University, Singapore
  • root [at] haozhexie [dot] com