Espresso: A Concentrated Introduction to Java
Summary: We introduce (or re-introduce) strings in the Java programming language, focusing on a selection of useful operations.
Prerequisites: Basics of Java, Input and Output in Java.
Important Classes
Contents:
In the parlance of computer science, a string is a sequence of simple characters. (A character is, most frequently, something you can type on the keyboard, such as a letter, number, or piece of punctuation.) Almost every modern programming language permits programmers to use variables of the string data type. Languages typically permit a variety of operations on strings, including input (since they are easy for most people to type), output (since they are easy for most people to type), and to extract individual characters.
In Java, strings are objects that belong to class
java.lang.String
. Because that is such a common class,
Java permits you to skip the package name, even without a corresponding
import
statement. For example,
String username;
is equivalent to
java.lang.String username;
String constants are represented by placing the sequence of characters between a pair of double-quotation marks. For example
username = "jdoe";
Java strings can contain essentially any character you can type or otherwise generate. They can contain numbers, spaces, punctuation, and so on and so forth. For example,
String address; address = "Apt. 2, East House, Main St.";
Strings are also comparable. That means we can determine whether two
strings are the same and whether one string naturally
precedes
another. (Java typically uses a local configuration file for determining
order so that it matches the local language and its ordering rules.)
Once you can compare strings, you have the ability to develop more
sophisticated operations on collections of strings, such as placing
them in order or searching for a particular string.
Java provides two basic operations for comparing strings:
equals(String other)
determines whether this string is the same as another string.
compareTo(String other)
determines the relative order for two strings. It returns zero if they are equal, a negative number if the string executing compareTo
naturally precedes other
, and a
positive number if the string executing compareTo
naturally follows other
.
We will return to the comparison operations when we begin to work with conditionals.
We can do many other things with strings. Java's primary
string class, java.io.String
gives us access not just to
the sequence of characters as a whole, but also to subsequences and to
operations on those subsequences. Interestingly enough, Java takes
advantage of the encapsulation for the String class and makes strings
immutable: Operations do not change strings, but only return
new strings based on the original string executing an operation.
Some of the string operations you may find useful include:
toLowerCase()
: Build a new string, similar to the original, but with all letters in the string converted to lower-case (using the local installations definition of lower-case and upper-case to lower-case conversion).
toUpperCase()
: Build a new string, similar to the original, but with all letters in the string converted to upper-case.
trim()
: Build a new string, similar to the original, but without leading and trailing whitespace. This command is often useful when you're processing unstructured user input.
substring(startindex)
: Extract the portion of the string that begins at startindex
. Note that indices start at 0.
substring(startindex,endindex)
: Extract the portion of the string that begins at startindex
and ends directly before endindex
.
replace(target,replacement)
: Build a new string, similar to the orignal, but with all substrings that match target
replaced by replacement
.
indexOf(target)
: Determine the first index of target
within the string. (This method is often useful in conjunction with substring
.)
indexOf(target, startHere)
: A variant that starts looking at the specified index.
concat(target)
: Build a new string by joining the specified target
to the end of the current string.
length()
: Determine how many characters are in the string.
For example,
String str = "All mimsy were the Borogoves."; pen.println(str); // All mimsy were the Borogoves. pen.println(str.toLowerCase()); // all mimsy were the borogoves. pen.println(str.toUpperCase()); // ALL MIMSY WERE THE BOROGOVES. pen.println(str.substring(4)); // mimsy were the Borogoves. pen.println(str.substring(4,9)); // mimsy pen.println(str.replace("mimsy","frumious")); // All frumious were the Borogoves. pen.println(str.indexOf("Borogoves")); // 19 pen.println(str.indexOf("Borogroves")); // -1 pen.println(str.concat(" And the mome raths outgrabe.")); // All mimsy were the Borogoves. And the mome raths outgrabe. pen.println(str); // All mimsy were the Borogoves.
Observe that even after all of the changes
to the original string,
the final command prints the original string, suggesting that the string
was never changed.
You can find other interesting and useful string operations in the official documentation, linked at the top of this reading.
As suggested at the end of the previous section, String objects are
immutable in Java. However, there are also times that you want to
change your strings, rather than simply building new strings each time.
For such purposes, Java provides the java.lang.StringBuffer
class. (Again, you need not import this class to refer to objects
simply as StringBuffer
.)
You can create a new StringBuffer
in one of two ways,
using a zero-parameter constructor, which builds an empty buffer,
or using a string as the parameter, which builds a string buffer
based on the given string. For example,
StringBuffer initiallyEmpty; StringBuffer sillyWord; initiallyEmpty = new StringBuffer(); sillyWord = new StringBuffer("borogoves");
The StringBuffer
class provides many of the same methods
as the String
class, including indexOf
,
substring
, and length
.
However, the StringBuffer
class also provides many
mutators for changing the underlying string.
append(String str)
: Appends str
to the end of the buffer.
insert(int offset, String str)
: Inserts str
starting at position offset
. Everything that was at that
position is moved to the right, after str
.
delete(int start, int end)
: Delete the characters between
start
and end
-1, inclusive.
You can also use the toString
method to recover a
string from a StringBuffer
.
Monday, 31 January 2005 [Samuel A. Rebelsky]
Sunday, 4 September 2005 [Samuel A. Rebelsky]
Tuesday, 31 January 2006 [Samuel A. Rebelsky]
This page was generated by
Siteweaver on Thu Mar 30 15:24:32 2006.
The source to the page was last modified on Tue Jan 31 09:21:26 2006.
This page may be found at http://www.cs.grinnell.edu/~rebelsky/Espresso/Readings/strings.html
.
You may wish to
validate this page's HTML
;
;
Check with Bobby