Thursday, December 8, 2011

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


The following code demonstrates the first two constructors:
char [] trueFalse = { 't', 'f', 'T', 'F' };
String s1 = new String (trueFalse);
String s2 = new String (trueFalse, 2, 2);

After this fragment executes, s1 references a String containing tfTF, and s2 references a String containing TF.
The following code demonstrates the third constructor:

String s3 = new String ("123");

That fragment passes a reference to a string literal-based String containing 123 to the String(String original) constructor. That constructor copies original's contents to the new s3-referenced String.
No matter how many times the same string literal appears in source code, the compiler ensures that only one copy stores in the class file's constant pool. Furthermore, the compiler ensures that only nonduplicates of all string constant expressions (such as "a" + 3) end up in the constant pool as string literals. When a classloader creates Strings from all string literal entries in the constant pool, each String's contents are unique. The classloader interns, or confines, those Strings in a common string memory pool located in JVM-managed memory.

No comments: