Page 2 of 5
Because the compiler and classloader treat string literals as String
objects, "abc".length() and synchronized ("sync object")
are legal. "abc".length() returns the length of the String
containing abc; and synchronized ("sync object") grabs
the lock associated with the String containing sync object.
Java regards these and other string literals as String objects to
serve as a convenience for developers. As with the simplified assignment
shortcut, substituting string literals for String object reference
variables reduces the amount of code you must write.
Java also offers a variety of String constructors for creating
String objects. I detail three below:
public String(char [] value) creates a new
String object that contains a copy of all characters found in the
value array parameter. If value is null, this
constructor throws a NullPointerException object. public String(char [] value, int offset, int count)
creates a new String that contains a portion of those characters
found in value. Copying begins at the offset array
index and continues for count characters. If value
is null, this constructor throws a NullPointerException object.
If either offset or count contain values that lead
to invalid array indexes, this constructor throws an
IndexOutOfBoundsException object. public String(String original) creates a new
String that contains the same characters as the original-referenced
String.
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.
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. Continued