|
The String class represents the strings (sequence) of characters in Java. Java uses 16-bit Unicode to represent characters. Therefore, the string objects are also made up of 16-bit Unicode characters.
|
|
Certification exam does not require you to know about character encoding. However, it is a interesting thing to know about. Character encoding is simply a technique of mapping characters of a human language to the machine understandable bit patterns. Java uses the Unicode encoding to represent characters. It uses 16 bits to represent the characters. Most of the English language characters can be mapped to 7-bit representations (ASCII). The rest of the bits make it possible to map the characters from the other spoken languages (Greek, Indian, Asian languages etc). |
The string objects are created just like other Java object using the new keyword. String objects can also be created by enclosing a sequence of characters in double quotes. The string object created by either way is immutable. It simply means once you create a string object by specifying a sequence of characters, that object will always represent that same sequence of characters throughout its life. For instance, if we create a string object as:
String str = new String(“Hello”);
Now the string object created has sequence of 5 characters. You can never change this sequence of characters in this object. No method in java.lang.String class allows you to do so. Any method that may appear to be changing the string actually creates a new string object. For example, if you try to modify the string “Hello” by concatenating “ World!” to it as:
String str = new String("Hello");
str.concat(" World");
System.out.println(str); // prints "Hello"

The string object created on the first line is not modified. It is still same
and contains “Hello”. The call to concat() creates another string object.
Figure 13.7 illustrates the memory model after this code is executed.
Figure 13.7 The string created in concat() is immediately lost as no reference points to it
Figure shows that the string object created by calling concat() is lost immediately after its creation. It is said to be lost because no reference refers to it. (Hence it becomes eligible for garbage collection.)