Friday, December 9, 2011

Java's character and assorted string classes support text-processing - 9


At runtime, as new Strings are created, they do not intern in the common string memory pool for performance reasons. Verifying a String's nonexistence in that pool eats up time, especially if many Strings already exist. However, thanks to a String method, code can intern newly created String objects into the pool, which I'll show you how to accomplish later in this article.
For proof that string literal-based Strings store in the common string memory pool and new Strings do not, consider the following code fragment:

String a = "123";
String b = "123";
String c = new String (a);
System.out.println ("a == b: " + (a == b));
System.out.println ("a == c: " + (a == c));

System.out.println ("a == b: " + (a == b)); outputs a == b: true because the compiler stores one copy of 123 in the class file's constant pool. At runtime, a and b receive the same reference to the 123 String object that exists in the common string memory pool. In contrast, System.out.println ("a == c: " + (a == c)); outputs a == c: false because the a-referenced (and b-referenced) String stores in the common string memory pool and the c-referenced String does not. If c existed in the common string memory pool, c, b, and a would all reference the same String (since that pool contains no duplicates). Hence, System.out.println ("a == c: " + (a == c)); would output a == c: true.

No comments: