Skip to main content
Engineering LibreTexts

17.5: The indexOf Method

  • Page ID
    15267
  • The indexOf method searches for a character in a string.

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

    This example finds the index of 'a' in the string. But the letter appears three times, so it’s not obvious what indexOf should do. According to the documentation, it returns the index of the first appearance.

    To find subsequent appearances, you can use another version of indexOf, which takes a second argument that indicates where in the string to start looking.

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

    This code starts at index 2 (the first 'n') and finds the next 'a', which is at index 3. If the letter happens to appear at the starting index, the starting index is the answer. So fruit.indexOf('a', 5) returns 5.

    If the character does not appear in the string, indexOf returns -1. Since indexes cannot be negative, this value indicates the character was not found.

    You can also use indexOf to search for a substring, not just a single character. For example, the expression fruit.indexOf("nan") returns 2.

    • Was this article helpful?