The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


The indexOf method

In some ways, indexOf is the opposite of charAt. charAt takes an index and returns the character at that index. indexOf takes a character and finds the index where that character appears.

charAt fails if the index is out of range, and causes an exception. indexOf fails if the character does not appear in the string, and returns the value -1.

    String fruit = "banana";
    int index = fruit.indexOf('a');

This finds the index of the letter 'a' in the string. In this case, the letter appears three times, so it is not obvious what indexOf should do. According to the documentation, it returns the index of the first appearance.

In order to find subsequent appearances, there is an alternate version of indexOf (for an explanation of this kind of overloading, see Section 5.4). It takes a second argument that indicates where in the string to start looking. If we invoke

    int index = fruit.indexOf('a', 2);

it will start at the twoeth letter (the first n) and find the second a, which is at index 3. If the letter happens to appear at the starting index, the starting index is the answer. Thus,

    int index = fruit.indexOf('a', 5);

returns 5. Based on the documentation, it is a little tricky to figure out what happens if the starting index is out of range:

indexOf returns the index of the first occurrence of the character in the character sequence represented by this object that is greater than or equal to fromIndex, or -1 if the character does not occur.

One way to figure out what this means is to try out a couple of cases. Here are the results of my experiments:

  • If the starting index is greater than or equal to length(), the result is -1, indicating that the letter does not appear at any index greater than the starting index.
  • If the starting index is negative, the result is 1, indicating the first appearance of the letter at an index greater than the starting index.

If you go back and look at the documentation, you'll see that this behavior is consistent with the definition, even if it was not immediately obvious. Now that we have a better idea how indexOf works, we can use it as part of a program.



Last Update: 2011-01-24