Java String indexOf(String str) method with example

Java String indexOf(String str) method Returns the index within this string of the first occurrence of the specified substring. The returned index is the smallest value k for which: this.startsWith(str, k)
If no such value of k exists, then -1 is returned.

Method Signature

public int indexOf(String str)


str – the substring to search for.


the index of the first occurrence of the specified substring, or -1 if there is no such occurrence.

String indexOf( String str) method internal implementation

public int indexOf(String str) {
        return indexOf(str, 0);

indexOf(String str) method internally calls public int indexOf(String str, int fromIndex) method. Totally four variants of indexOf method there in Java String class.

  1. Java String indexOf(int ch) method with example
  2. Java String indexOf(int ch, int fromIndex) method with example
  3. Java String indexOf(String str) method with example
  4. Java String indexOf(String str, int fromIndex) method with example

Java String indexOf( String str) method example


public class IndexOfExample {

	public static void main(String[] args) {

		String s = "This is ehowtonow java tutorials";
		System.out.println("index of java : " + s.indexOf("java"));
		System.out.println("index of ehowtonow : "+ s.indexOf("ehowtonow"));
		System.out.println("index of tutorials : "+ s.indexOf("tutorials"));



index of java : 18
index of ehowtonow : 8
index of tutorials : 23

Ask your questions in eHowToNow Forum

Post your technical, non-technical doubts, questions in our site. Get answer as soon as possible, meanwhile you can help others by answering, unanswered questions.
To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

  1. How to search a word inside String
  2. How to find last occurrence of substring inside string
  3. How to convert a String to Lower case
  4. Java String format(String format, Object… args) method with example
  5. How to Split the String in Java
  6. Java String contentEquals(CharSequence cs) method with example
  7. Java String charAt() method with example
  8. How to convert a String to Upper case
  9. Java String compareTo() method with example
  10. String Concatenation in Java
  11. Java String equals() method with example
  12. Java String copyValueOf(char[] data, int offset, int count) method with example
  13. Java String codePointBefore() method with example
  14. Java String equalsIgnoreCase() method with example
  15. Java String Compare

Be the first to comment

Leave a Reply