Monday, March 26, 2012

String Handling

in Java a string is a sequence of characters. But, unlike many other
languages that implement strings as character arrays, Java implements strings as
objects of type String.
Implementing strings as built-in objects allows Java to provide a full complement
of features that make string handling convenient. For example, Java has methods to
compare two strings, search for a substring, concatenate two strings, and change the
case of letters within a string. Also, String objects can be constructed a number of
ways, making it easy to obtain a string when needed.
Somewhat unexpectedly, when you create a String object, you are creating a string
that cannot be changed. That is, once a String object has been created, you cannot change
the characters that comprise that string. At first, this may seem to be a serious restriction.
However, such is not the case. You can still perform all types of string operations. The
difference is that each time you need an altered version of an existing string, a new String
object is created that contains the modifications. The original string is left unchanged. This
approach is used because fixed, immutable strings can be implemented more efficiently
than changeable ones. For those cases in which a modifiable string is desired, there is a
companion class to String called StringBuffer, whose objects contain strings that can be
modified after they are created.
Both the String and StringBuffer classes are defined in java.lang. Thus, they are
available to all programs automatically. Both are declared final, which means that neither
of these classes may be subclassed. This allows certain optimizations that increase
performance to take place on common string operations. Beginning with Java 2,
version 1.4, both String and StringBuffer implement the CharSequence interface.
One last point: To say that the strings within objects of type String are
unchangeable means that the contents of the String instance cannot be changed after it
has been created. However, a variable declared as a String reference can be changed to
point at some other String object at any time.

No comments:

Post a Comment