start page | rating of books | rating of authors | reviews | copyrights

Java Fundamental Classes Reference

Previous Chapter 2 Next
 

2. Strings and Related Classes

Contents:
String
StringBuffer
String Concatenation
StringTokenizer

As with most programming languages, strings are used extensively throughout Java, so the Java API has quite a bit of functionality to help you manipulate strings. This chapter describes the following classes:

2.1 String

You can create a String object in Java simply by assigning a string literal to a String variable:

String quote = "To be or not to be";

All string literals are compiled into String objects. Although the Java compiler does not generally treat expressions involving object references as compile-time constants, references to String objects created from string literals are treated as compile-time constants.

Of course, there are many other ways to create a String object. The String class has a number of constructors that let you create a String from an array of bytes, an array of characters, another String object, or a StringBuffer object.

If you are a C or C++ programmer, you may be wondering if String objects are null-terminated. The answer is no, and, in fact, the question is irrelevant. The String class actually uses a character array internally. Since arrays in Java are actual objects that know their own length, a String object also knows its length and does not require a special terminator. Use the length() method to get the length of a String object.

Although String objects are immutable, the String class does provide a number of useful methods for working with strings. Any operation that would otherwise change the characters or the length of the string returns a new String object that copies the necessary portions of the original String.

The following methods access the contents of a String object:

You can compare the contents of String objects with the following methods:

Use the following methods to search for characters in a string:

The following methods manipulate the contents of a string and return a new, related string:

The String class also defines a number of static methods named valueOf() that return string representations of primitive Java data types and objects. The Object class defines a toString() method, and, since Object is the ultimate superclass of every other class, every class inherits a basic toString() method. Any class that has a string representation should override the toString() method to produce the appropriate string.


Previous Home Next
The java.util.zip Package Book Index StringBuffer

Java in a Nutshell Java Language Reference Java AWT Java Fundamental Classes Exploring Java