Share on Google+Share on Google+

String indexOf() method in Java

In this tutorial, you will get the detailed explanation about the indexOf() method of String class.

String indexOf() method in Java

In this tutorial we will discuss about indexOf() method in java. indexOf() method which is of string class,  used to locate a character or string.  The String class provide two method for searching a specified character or string, indexOf() and lastIndex(). For example you want to search a character 'a' in the String "abc" then the syntax is like as follows:

String str="abc";
int index=str.indexOf('a');

Then the index  returns integer value 0 i.e. location of 'a' in the string abc.

  • indexOf() : Searches  for the first occurrence of character or string.
  • lastIndex() : Searches for the last occurrence of character or string.

The indexOf() method can be overloaded in different ways they are as follows:

  • indexOf(int ch) : To search for the first occurrence of the string or character. Here ch is the character.
  • indexOf(int ch, int index) : To search for the first occurrence of character starting with the index. Here index indicates from where search starts.
  • indexOf(String str) : To search for first occurrence of  the sub string within the string.
  • indexOf(String str, int index) : To search for the character or string starting from the index.

Syntax :

public int indexOf(int ch)

Code of the program given below :

public class IndexOf {
	public static void main(String args[])
		String str="Hello java world";
		int index=str.indexOf('e');
		String substr="java";
		System.out.println("Index of e is = "+index);
		index=str.indexOf(str, 2);
		System.out.println("Index of o is at "+index);
		System.out.println("found at "+str.indexOf(substr));
		System.out.println("found at "+str.indexOf(substr,7));

Output from the program :

Download Source Code



Posted on: June 26, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: String indexOf() method in Java  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image