Next: String-related methods. Up: Strings. Previous: None.
Textbook: Section 3.9
A string is a sequence of characters. It might represent a word, a sentence, or a name. They're extremely important to programming, and Java provides quite a bit of support for them.
Java implements strings as objects - the class name is String. Using strings is just like using other objects, except that Java also provides a little bit of additional syntax for dealing with strings, since they're so important.
To create a string, you don't even need to use the new keyword: You just enclose the string in double-quotes.
If you want double-quotes, you can put the escape character (backslash) before them.String name = "Carl";
String shesaid = "\"Hello there,\" she said.";
The String class, by the way, is immutable - that is, the class provides no ways to modify the string once it's created. This distinguishes it from the Account class, which had a method (deposit()) that permitted you to alter its state. We would say that the Account class is mutable.
The String class provides a number of useful methods for working with strings. You can and should refer a complete list in the library documentation, but today we'll just touch on some of the more important.
Java provides a particularly simple operator for the very common operating of catenating two string together: the + operator.
The result of the catenation here is the string ``Carl Burch,'' and that is what the above would display.IO.println(name + " Burch");
You can use numbers here also.
If i is an int variable, the above would print the current value held by i, in decimal form.IO.println("i holds " + i);
Notice that Java uses + for both addition and catenation. Usually, this causes no confusion, but occassionally it's problematic. Consider the following example.
If i held 2, this would actually print ``i+1 = 21''. This is because the + operator works left-to-right, so the above is identical toIO.println("i+1 = " + i+1);
IO.println(("i+1 holds " + i) + 1);
Next: String-related methods. Up: Strings. Previous: None.