Section 2.9
Details of Strings
JAVA HAS A BUILT-IN TYPE, String, to represent strings of characters. This type differs from the eight primitive types because a value of type String is an object. A String is not just a data value; it also has "methods." (A method is a subroutine that is part of an object.) For example, if str is a variable of type String, you can call the method str.length(), which is a function that returns the number of characters in the string. There's a lot more you can do with strings. This section covers some of the details.
One thing that you cannot do with strings is to use the relational operators <, >, <=, and <= to compare them. You can legally use == and != to compare Strings, but because of peculiarities in the way objects behave, they won't give the results you want. (The == operator checks whether two objects are stored in the same memory location, rather than whether they contain the same value. Occasionally, for some objects, you do want to make such a check -- but rarely for strings. I'll get back to this in a later chapter.) Instead, you should use the methods equals() and equalsIgnoreCase(), which are described below, to compare two Strings.
The String class defines a lot of methods. Here are some that you might find useful. Assume that s1 and s2 are Strings:
- s1.equals(s2) is a boolean-valued function that returns true if s1 consists of exactly the same sequence of characters as s2.
- s1.equalsIgnoreCase(s2) is another boolean-valued function that checks whether s1 is the same string as s2, but this function considers upper and lower case letters to be equivalent. Thus, if s1 is "cat", then s1.equals("Cat") is false, while s1.equalsIgnoreCase("Cat") is true.
- s1.length(), as mentioned above, is an integer-valued function that gives the number of characters in s1.
- s1.charAt(N), where N is an integer, is a char-valued function that returns the N-th character in the string. Positions are numbered starting with 0, so s1.charAt(0) is the actually the first character, s1.charAt(1) is the second, and so on. The final position is s1.length() - 1.
- s1.substring(N,M), where N and M are integers, returns a String containing a substring of the characters in s1. The substring consists of the characters in s1 in positions N, N+1,..., M-1. Note that the character in position M is not included.
- s1.indexOf(s2) returns an integer. If s2 occurs as a substring of s1, then the returned value is the starting position of that substring. Otherwise, the returned value is -1. You can also use s1.indexOf(ch) to search for a particular character, ch, in s1. To find the first occurrence of x at or after position N, you can use s1.indexOf(x,N).
- s1.compareTo(s2) is an integer-valued function that compares the two strings. If the strings are equal, the value returned is zero. If s1 is less than s2, the value returned is -1, and if s1 is greater than s2, the value returned is 1. (If the strings consist entirely of lowercase letters, then "less than" and "greater than" refer to alphabetical order.)
- s1.toUpperCase() is a String-valued function that returns a new string that is equal to s1, except that any lower case letters in s1 have been converted to upper case. There is also a method s1.toLowerCase().
- s1.trim() is a String-valued function that returns a new string that is equal to s1 except that any non-printing characters such as spaces and tabs have been trimmed from the beginning and from the end of the string. Thus, if s1 has the value "fred ", then s1.trim() is the string "fred".
For the methods s1.toUpperCase(), s1.toLowerCase() and s1.trim(), note that the value of s1 is not changed. Instead a new string is created and returned as the value of the function. The returned value could be used, for example, in an assignment statement such as "s2 = s1.toLowerCase();".
Here is another extremely useful fact about strings that I haven't mentioned so far: You can use the operator + to concatenate two strings. The concatenation of two strings is a new string consisting of all the characters of the first string followed by all the characters of the second string. For example, "Hello" + "World" evaluates to "HelloWorld". (Gotta watch those spaces, of course.)
Even more surprising is that you can concatenate values belonging to one of the primitive types onto a String using the + operator. The value of primitive type is converted to a string, just as it would be if you printed it to the standard output. For example, the expression "Number" + 42 evaluates to the string "Number42". And the statements
TextIO.put("After "); TextIO.put(years); TextIO.put(" years, the value is "); TextIO.put(principal);can be replaced by the single statement:
TextIO.put("After " + years + " years, the value is " + principal);Obviously, this is very convenient. It would have shortened several of the examples used earlier in this chapter.
You can even use the += operator to add something onto the end of a String. For example, if you want to read a sequence of letters from standard input and store them in a String, you could do it like this:
String str = ""; // start with an empty string char ch = TextIO.getChar(); // read one character while ( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ) { // ch is a letter, so append it to the string // and read the next character. str += ch; // (note: same as str = str + ch;) ch = TextIO.getChar(); } // end of while loop
End of Chapter 2
[ Next Chapter | Previous Section | Chapter Index | Main Index ]