Creating and Manipulating Strings 109
equals() and equalsIgnoreCase()
This example should be fairly intuitive. In the fi rst example, the values aren’t exactly the same. In the second, they are exactly the same. In the third, they differ only by case, but it is okay because we called the method that ignores differences in case.
startsWith() and endsWith()
Again, nothing surprising here. Java is doing a case-sensitive check on the values provided.
110 Chapter 3 ■ Core Java APIs
Again, we have a case-sensitive search in the String. The contains() method is a conve-nience method so you don’t have to write str.indexOf(otherString) != -1.
String replace(CharSequence oldChar, CharSequence newChar)
The following code shows how to use these methods:
You’ve made it through the all the String methods you need to know except one. We left the easy one for last. The trim() method removes whitespace from the beginning and end of a String. In terms of the exam, whitespace consists of spaces along with the \t (tab) and \n (newline) characters. Other characters, such as \r (carriage return), are also included in what gets trimmed. The method signature is as follows:
public String trim()
It is common to call multiple methods on the same String, as shown here: