Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

148 Part I: The Java Language


display: outer_x = 100
display: outer_x = 100

While nested classes are not applicable to all stiuations, they are particularly helpful when
handling events. We will return to the topic of nested classes in Chapter 22. There you will
see how inner classes can be used to simplify the code needed to handle certain types of
events. You will also learn aboutanonymous inner classes, which are inner classes that don’t
have a name.
One final point: Nested classes were not allowed by the original 1.0 specification for Java.
They were added by Java 1.1.

Exploring the String Class


Although theStringclass will be examined in depth in Part II of this book, a short exploration
of it is warranted now, because we will be using strings in some of the example programs
shown toward the end of Part I.Stringis probably the most commonly used class in Java’s
class library. The obvious reason for this is that strings are a very important part of
programming.
The first thing to understand about strings is that every string you create is actually an
object of typeString. Even string constants are actuallyStringobjects. For example, in the
statement

System.out.println("This is a String, too");

the string “This is a String, too” is aStringconstant.
The second thing to understand about strings is that objects of typeStringare immutable;
once aStringobject is created, its contents cannot be altered. While this may seem like a
serious restriction, it is not, for two reasons:


  • If you need to change a string, you can always create a new one that contains
    the modifications.

  • Java defines a peer class ofString, calledStringBuffer, which allows strings
    to be altered, so all of the normal string manipulations are still available in Java.
    (StringBufferis described in Part II of this book.)


Strings can be constructed in a variety of ways. The easiest is to use a statement like this:

String myString = "this is a test";

Once you have created aStringobject, you can use it anywhere that a string is allowed.
For example, this statement displaysmyString:

System.out.println(myString);

Java defines one operator forStringobjects:+. It is used to concatenate two strings.
For example, this statement

String myString = "I" + " like " + "Java.";

results inmyStringcontaining “I like Java.”
Free download pdf