String Methods on the ExamΒΆ

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
  • 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.

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.

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

4-2-1: What is the value of s1 after the following code executes?

String s1 = "Hi";
String s2 = s1.substring(0,1);
String s3 = s2.toLowerCase();





4-2-2: What is the value of s3 after the following code executes?

String s1 = "Hi";
String s2 = s1.substring(0,1);
String s3 = s2.toLowerCase();





4-2-3: What is the value of pos after the following code executes?

String s1 = "abccba";
int pos = s1.indexOf("b");





4-2-4: What is the value of len after the following executes?

String s1 = "Miss you!";
int len = s1.length();




4-2-5: What is the value of s2 after the following code executes?

String s1 = new String("hi there");
int pos = s1.indexOf("e");
String s2 = s1.substring(0,pos);