2.7. String Methods

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 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 AP CS A Java Quick Reference Sheet that you get during the exam so you don’t have to memorize these.

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

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

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

  • int compareTo(String other) returns a negative value if the current string is less than the other string alphabetically, 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 alphabetically.

  • 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. Notice that indexOf returns -1 if it cannot find the substring in the message.

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? Remember that substring(from,to) does not include the character at the to index!

exercise Check your understanding

    2-7-1: What is the value of pos after the following code executes?

    String s1 = "abccba";
    int pos = s1.indexOf("b");
    
  • 2
  • The first character is at index 0 in a string.
  • 1
  • The method indexOf returns the first position of the passed str in the current string starting from the left (from 0).
  • 4
  • Does indexOf start from the left or right?
  • -1
  • Does the string contain a b?

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

    String s1 = "baby";
    int len = s1.length();
    
  • 2
  • Length returns the number of characters in the string, not the number of characters in the name of the string.
  • 3
  • The position of the last character is 3, but the length is 4.
  • 4
  • Length returns the number of characters in the string.
  • -1
  • Length is never negative.

    2-7-3: What is the value of s2 after the following code executes?

    String s1 = "baby";
    String s2 = s1.substring(0,3);
    
  • baby
  • This would be true if substring returned all the characters from the first index to the last inclusive, but it does not include the character at the last index.
  • b
  • This would be true if it was s1.substring(0,1)
  • ba
  • This would be true if it was s1.substring(0,2)
  • bab
  • Substring returns all the characters from the starting index to the last index - 1.

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

    String s1 = "baby";
    String s2 = s1.substring(2);
    
  • by
  • The method substring(index) will return all characters starting the index to the end of the string.
  • aby
  • This would be true if it was substring(1);
  • a
  • This would be true if it was substring(1,2);
  • b
  • This would be true if it was substring(2,3);
  • ba
  • This would be ture if it was substring(0,2);

Run the example below to see the output from compareTo and equals. Notice that compareTo tells you how you would order the two strings alphabetically. If they are equal, it returns 0. Since “Hello!” would be alphabetically ordered after “And”, compareTo returns a positive number. Since “Hello!” would be alphabetically ordered before “Zoo”, compareTo returns a negative number. And notice that equals is case-sensitive.

There are lots of other methods in the String class. You can look through the Java documentation for the String class online. You don’t have to know all of these for the exam, but you can use them if you want to on the exam.

The String library which is built into the default java.lang library simplifies a lot of complex programming tasks for us. Classes are grouped together into a package like java.lang. Many other useful library packages can be imported in. Programmers provide Application Program Interfaces (APIs) to allow other programmers to use their code. Documentation for APIs and libraries are essential to understanding the attributes and behaviors of an object of a class.

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.

exercise Check your understanding

    2-7-5: Drag the definition from the left and drop it on the correct concept on the right. Click the "Check Me" button to see if you are correct Review the vocabulary.
  • the position of a character in a string
  • index
  • a new string with 0 to all characters copied from another string
  • substring
  • doesn't change
  • immutable
  • the number of characters in a string
  • length
    2-7-6: Drag the definition from the left and drop it on the correct method on the right. Click the "Check Me" button to see if you are correct. Review the vocabulary.
  • Returns true if the characters in two strings are the same
  • equals
  • Returns the position of one string in another or -1
  • indexOf
  • Returns a number to indicate if one string is less than, equal to, or greater than another
  • compareTo
  • Returns a string representing the object that is passed to this method
  • toString

    2-7-7: 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);
    
  • hi th
  • The substring method returns the string starting at the first index and not including the last index. The method indexOf returns the index of the first place the string occurs.
  • hi the
  • This would be correct if substring returned all characters between the first index and last index, but does it?
  • hi ther
  • This would be correct if indexOf returned the last position the string str was found in the current string, does it?
  • hi there
  • This would be correct if indexOf returned the last position the string str was found in the current string and if substring included all characters between the start and end index. Check both of these.

    2-7-8: What is the value of s1 after the following code executes?

    String s1 = "Hi";
    String s2 = s1.substring(0,1);
    String s3 = s2.toLowerCase();
    
  • Hi
  • Strings are immutable, meaning they don't change. Any method that changes a string returns a new string. So s1 never changes.
  • hi
  • This would be true if the question was what is the value of s2 and it was substring(0,2) not (0,1)
  • H
  • This would be true if the question was what is the value of s2, not s1.
  • h
  • This would be true if the question was what is the value of s3, not s1.

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

    String s1 = "Hi";
    String s2 = s1.substring(0,1);
    String s3 = s2.toLowerCase();
    
  • Hi
  • Is this the value of s3? What does toLowerCase do?
  • hi
  • How does substring work? Does it include the character at the end index?
  • H
  • What does toLowerCase do?
  • h
  • s2 is set to just "H" and s3 is set to changing all characters in s2 to lower case.

    2-7-10: What is the value of answer after the following code executes?

    String s1 = "Hi";
    String s2 = "Bye";
    int answer = s1.compareTo(s2);
    
  • positive (> 0)
  • H is after B in the alphabet so s1 is greater than s2.
  • 0
  • The method compareTo will only return 0 if the strings have the same characters in the same order.
  • negative (< 0)
  • This would be true if it was s2.compareTo(s1)

2.7.1. Common Mistakes

  • Using == to test if two strings are equal. This is actually a test to see if they refer to the same object. Usually you only want to know if they have the same characters in the same order. In that case you should use equals or compareTo instead.

  • Treating upper and lower case characters the same in Java. If s1 = "Hi" and s2 = "hi" then s1.equals(s2) is false.

  • Thinking that substrings include the character at the last index when they don’t.

  • Thinking that strings can change when they can’t. They are immutable.

  • Trying to invoke a method like indexOf on a string reference that is null. You will get a null pointer exception.

  • Trying to access part of a string that is not between index 0 and length - 1. This will throw an IndexOutOfBoundsException.

2.7.2. groupwork Programming Challenge : Pig Latin

pig latin Can you speak Pig Latin? In Pig Latin, you take the first letter and put it at the end of the word and add the letters “ay” to the end. For example, “pig” becomes “igpay”.

Create a program that takes a word and outputs it in Pig Latin using String methods. You may need the word’s length, a substring that does not include the first letter, and a substring that is just the first letter (you can get the ith letter of a string using substring(i,i+1) so for example the letter at index 3 would be substring(3,4)).

Your teacher may ask you to create this program in a Java IDE like repl.it so that you can use input to read in the word (see input examples using the Scanner class).

2.7.3. Summary

  • index - A number that represents the position of a character in a string. The first character in a string is at index 0.

  • length - The number of characters in a string.

  • substring - A new string that contains a copy of part of the original string.

  • A String object has index values from 0 to length – 1. Attempting to access indices outside this range will result in an IndexOutOfBoundsException.

  • String objects are immutable, meaning that String methods do not change the String object. Any method that seems to change a string actually creates a new string.

  • The following String methods and constructors, including what they do and when they are used, are part of the AP CS A Java Quick Reference Sheet that you can use during the exam:

    • String(String str) : Constructs a new String object that represents the same sequence of characters as str.

    • int length() : returns the number of characters in a String object.

    • String substring(int from, int to) : returns the substring beginning at index from and ending at index (to – 1).

    • String substring(int from) : returns substring(from, length()).

    • int indexOf(String str) : returns the index of the first occurrence of str; returns -1 if not found.

    • boolean equals(String other) : returns true if this (the calling object) is equal to other; returns false otherwise.

    • int compareTo(String other) : returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other.

  • A string identical to the single element substring at position index can be created by calling substring(index, index + 1).

You have attempted of activities on this page
Next Section - 2.8. Wrapper Classes - Integer and Double