Tuesday, December 6, 2011

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


The String class
The String class contrasts with Character in that a String object stores a sequence of characters—a string—whereas a Character object stores one character. Because strings are pervasive in text-processing and other programs, Java offers two features that simplify developer interaction with String objects: simplified assignment and an operator that concatenates strings. This section examines those features.
String objects
A java.lang.String object stores a character sequence in a character array that String's private value field variable references. Furthermore, String's private count integer field variable maintains the number of characters in that array. Each String has its own copy of those fields, and Java's simplified assignment shortcut offers the easiest way to create a String and store a string in the String's value array, as the following code demonstrates:

public static void main (String [] args)
{
   String s = "abc";
   System.out.println (s); // Output: abc
}

When the compiler compiles the preceding fragment, it stores the abc string literal in a special area of the class file—the constant pool, which is a collection of string literals, integer literals, and other constants. The compiler also generates a byte code instruction (ldc—load constant) that pushes a reference to a String object containing abc onto the calling thread's stack, and generates another instruction (astore_1) that pops that reference from the stack and stores it in the s local variable, which corresponds to local variable 1 at the JVM level.

No comments: