java.lang.String

To complete this chapter, here is the standard Java class java.lang.String. That's obviously a class type, contrasting with the primitive types with which we started the chapter. You will use String instances a lot—whenever you want to store some characters in a sequence or do human-readable I/O.

As the name suggests, String objects hold a series of adjacent characters, similar to an array. Strings have methods to extract substrings, to put into lower case, to search a String, to compare two Strings, and so on. Arrays of char have none of these. String is a very convenient class and you'll use it extensively in many programs.

literals: A string literal is zero or more characters enclosed in double quotes, like these two lines:

"That'll cost you two-fifty  "
"" // empty string

The empty String is different from the null pointer. The empty String is a pointer to a String object which happens to have zero length. You can invoke all the compare, search, extract methods on an empty String. They do little, but they don't cause errors.

Strings are used so frequently that Java has some special built-in support. Everywhere else in Java, you use a constructor to create an object of a class, such as:

String drinkPref = new String( "I like tea" );

String literals count as a shortcut for the constructor. So this is equivalent:

String drinkPref = "I like tea";

Each string literal behaves as if it is a reference to an instance of class String, meaning that you can invoke methods on it, copy a reference to it, and so on. For convenience or performance, the compiler may implement it another way, but it must be indistinguishable to the programmer. Here's a method invoked on a literal:

String s = "ABCD".toLowerCase();

String s is assigned a pointer to the newly created String “abcd”.

Like all literals, string literals cannot be modified after they have been created. Variables of class String have the same quality—once you have created a String, you cannot change a character in the middle to something else. Some people use the term “immutable” to describe this, as in “Strings are immutable.”

But don't worry: you can always discard any String and make the same reference variable refer to a different String with different content. You can construct a new String out of pieces from other Strings. So being unable to change a given String after it has been created isn't a handicap in practice, and it makes programs more reliable. Programmers can be certain that a String object won't be changed out from under them, via some other reference to it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.202.61