Java Reference
In-Depth Information
1.10. String Objects
A String class type deals specifically with sequences of character data
and provides language-level support for initializing them. The String class
provides a variety of methods to operate on String objects.
You've already seen string literals in examples like the HelloWorld pro-
gram. When you write a statement such as
System.out.println("Hello, world");
the compiler actually creates a String object initialized to the value of the
specified string literal and passes that String object as the argument to
the println method.
You don't need to specify the length of a String object when you create it.
You can create a new String object and initialize it all in one statement,
as shown in this example:
class StringsDemo {
public static void main(String[] args) {
String myName = "Petronius";
myName = myName + " Arbiter";
System.out.println("Name = " + myName);
}
}
Here we declare a String variable called myName and initialize it with an ob-
ject reference to a string literal. Following initialization, we use the String
concatenation operator ( + ) to make a new String object with new con-
tents and store a reference to this new string object into the variable.
Finally, we print the value of myName on the standard output stream. The
output when you run this program is
 
Search WWH ::




Custom Search