Java .indexOf()
Published Aug 22, 2022Updated Aug 22, 2022
Contribute to Docs
The .indexOf() method returns the index of the first occurrence of a substring in a StringBuilder. If the substring is not found, -1 is returned.
Syntax
myStringBuilder.indexOf(substring, index);
The argument substring is of type String.
The index is an int argument that is optional. If provided, .indexOf() returns the first occurrence of substring after that index in the StringBuilder.
Example
The following example creates a StringBuilder with a specified string then uses .indexOf() to find the index of a particular substring:
import java.util.*;public class Example {public static void main(String[] args){StringBuilder str = new StringBuilder("Hello World!");System.out.println(str.toString());System.out.println(str.indexOf("World"));}}
This produces the following output:
Hello World!6
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours