java.lang.StringBuilder indexOf(String str) and indexOf(String str, int fromIndex)

Description

On this document we will be showing a java example on how to use the indexOf() method of StringBuilder Class. Basically the indexOf method search on the StringBuilder character sequence for the occurrence of the specified method argument String. That’s basically the function of the indexOf method, but take into consideration that it is overloaded. One of the method accepts only a String method argument, while the second one accepts a String input with a new argument fromIndex. These two methods are basically the same, it’s just that the method with argument fromIndex, starts searching for the String on the character sequence based on the fromIndex input.

Notes:

  • indexOf(str) is equal to indexOf(str,0)
  • Method overloading is one of the feature of java where we can use the same method name but with different method signature.

Method Syntax

1.

public int indexOf(String str)

2.

public int indexOf(String str, int fromIndex)

Method Argument

Data Type Parameter Description
String str any String we want to search on our character sequence
int fromIndex the index from which to start the search.

Method Returns

The indexOf method returns the index of the first character of the first such substring is returned if the string argument occurs as a substring within this object. If the search string has not been found, -1 will be returned.

Compatibility

Requires Java 1.5 and up

Java StringBuilder indexOf() Example

Below is a java code demonstrates the use of indexOf() method of StringBuilder class. The example presented might be simple however it shows the behavior of the indexOf() method.

The above java example source code demonstrates the use of indexOf() method of StringBuilder class. Initially the code assigns a string “javatutorialhq.com” as initial contents of the StringBuilder. Then we use the indexof method to get the starting index of string “a”. This is very useful method that works well with substring method of StringBuilder class. On this example we will also learn how to use the indexof method to work with substring.

Sample Output

Below is the sample output when you run the above example.

StringBuilder indexOf() example output