String Methods

IndexOf

🙋 Need help? Ask an expert now!

Let's discuss what the concept of "index" means in Java. Index numbering starts with zero and totals up characters. The method indexOf() returns the index of the first occurrence of a String or char in a targeted String. Take a look below to see how this method is used.

IndexOfMethodExample.java
package exlcode;

public class IndexOfMethodExample {

  public static String exampleVariableOne = "Hello World!";
  // returns the index of the given String (case sensitive)
  // and assigns it to integer variables
  public static int exampleVariableTwo = exampleVariableOne.indexOf("World");
  public static int exampleVariableThree = exampleVariableOne.indexOf("world");
  public static int exampleVariableFour = exampleVariableOne.indexOf("world", 7);

  public static void main(String[] args) {
    System.out.println(exampleVariableTwo);
    System.out.println(exampleVariableThree);
    System.out.println(exampleVariableFour);
  }
}

Indexing starts with zero, which is why the program above will print 6, not 7. Therefore, if you had a String "Java":

Index: 0 1 2 3

String: J a v a

Another way to use the indexOf() method is by putting an valid index after the target String. This tells the method where you want to start searching for the target String. As we see in the example above, the index of "World" is 6, meaning if we start searching from index 7, we will not find the String "World", thus returning -1.

Application Question

Consider the following code segment:

String varOne = "Hello World!";
            System.out.println(varOne.indexOf('W'));
            

What is printed as a result of executing this code segment?