Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
IndexOf
Introduction To Java Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Introduction To Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
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.