Chapter 11

String Methods

Commonly Used Methods

Now that we have a better understanding of classes and objects, let’s return to the String type that we’ve used throughout. We’ve noted before that strings are actually objects (instances of the String class). Within the String class, there are several useful methods that can be applied to strings.

The location of each character in a String is called its index. Note that the first index is numbered 0, not 1, as shown below for the String literal “Hello, world!”.

Indices of chars in a string

Here is a listing of some of the most important String methods. A complete reference may be found here

Here are each of the above applied to the String “Hello:




String s = “Hello”;
s.toUpperCase(); // returns “HELLO”
s.toLowerCase(); // returns “hello”
s.length(); // returns 5
s.charAt(2); // returns ’l’ (not ‘e’)
s.indexOf(‘o’); // returns 4, the first index where ‘o’ is found
s.indexOf(‘l’); // returns 2, the first index where ‘l’ is found
s.indexOf(‘q’); // returns -1, because ‘q’ is not found
s.substring(1); // returns “ello”
s.substring(2,4); // returns “ll” (not “llo”)
Note that these methods do not change the literal (the characters) in the original String (in fact, Strings are "immutable"--can't be changed-- in Java). So, in all examples above, the String s continues to hold the literal "Hello." If you need to change the characters within a String, take a look at the StringBuilder class in Java.

Comparing strings

As we saw earlier, one important method for Strings is called equals. It determines whether the characters in one String object match exactly the characters in another and returns true or false. Note that you cannot use == to compare Strings (or any other reference type, i.e. “non-primitive” type). For reference types, == determines whether two objects are in the same memory location, not whether they contain the same data. It is possible to have two Strings that have the same set of characters but are located in two different locations in memory.

There is also a compareTo method for Strings. It returns an int representing the numerical difference between the first two characters that differ in a String (or 0 if the Strings have the exact same characters), based on their Unicode values (shown in this table-- see the decimal column for the integer values in base 10).



Some examples:




String s1 = "Africa", s2 = "africa", s3 = "Africa", s4 = "AFRICA";
System.out.println(s1.equals(s2)) // prints false
System.out.println(s1.equals(s3)) // prints true
System.out.println(s1.compareTo(s4)) // prints -32 'f' and 'F' have a difference of 32 (102-70)
System.out.println(s1.compareTo(s3)) // prints 0