This book is now obsolete Please use CSAwesome instead.

4.3. String Methods on the Exam

A string holds characters in a sequence. Each character is at a position or index which starts with 0 as shown below. An index is a number associated with a position in a string. The length of a string is the number of characters in it including any spaces or special characters. The string below has a length of 14.

a string with the position (index) shown above each character

Figure 1: A string with the position (index) shown above each character

Note

The first character in a string is at index 0 and the last characters is at the length - 1.

For the AP CS A exam there are only a few things that you have to know about strings. All of the following are included in the quick reference that you get during the exam so you don’t have to memorize these. I recommend printing a copy of the quick reference and using it when you practice for the exam. You can get it at https://secure-media.collegeboard.org/digitalServices/pdf/ap/explore-ap/AP_Computer-Science-A-Quick-Reference.pdf.

  • the int length() method returns the number of characters in the string, including spaces and special characters like punctuation.

  • the String substring(int from, int to) method returns a string with the characters in the current string starting with the character at the from index and ending at the character before the to index (if the to index is specified, and if not specified it will contain the rest of the string).

  • the int indexOf(String str) method returns the index of the beginning of str in the current string or -1 if it isn’t found.

  • the int compareTo(String other) returns a negative value if the current string is less than the other string, 0 if they have the same characters in the same order, and a positive value if the current string is greater than the other string.

  • the boolean equals(String other) returns true when the characters in the current string are the same as the ones in the other string. This method is inherited from the Object class, but is overriden which means that the String class has its own version of that method.

Run the code below to see the output from length, substring, and indexOf.

Note

Did you notice that message1.substring(0,3) includes all the characters from position 0 to 2 and doesn’t include the character at position 3?

Check your understanding

Run the example below to see the output from compareTo and equals.

There are lots of other methods in the String class. See the Java documentation for the String class at http://docs.oracle.com/javase/6/docs/api/java/lang/String.html. You don’t have to know all of these for the exam, but you can use them if you want to on the exam.

Note

Strings are immutable which means that they can’t change. Anything that you do to modify a string (like creating a substring or appending strings) returns a new string.

Check your understanding

You have attempted of activities on this page