Java String IndexOf Example

Java String class consist of methods for finding the index of occurrence in the given string literals. If there is no occurrence of the given characters, then it will return the “-1″.  The following are the few methods which is very useful to find the string values.

  1. indexOf(char) – Returns the index of the character first occurrence in the given string. If it does not occur as a substring, -1 is returned
  2. lastIndexOf(char) – Returns the index of the character last occurrence in the given string. If it does not occur as a substring, -1 is returned
  3. lastIndexOf(string) – Returns the index within this string of the last occurrence of the specified substring. If it does not occur as a substring, -1 is returned
  4. lastIndexOf(string,fromIndex)  – Returns the index within this string of the last occurrence of the specified substring. If it does not occur as a substring, -1 is returned

Look at the below example for String indexOf() methods.

StringIndexExample.java

package javabeat.net.core;

/**
 * String indexOf() Example
 * @author krishna
 *
 */
public class StringIndexExample {
	public static void main(String args[]) {
		String str = "Java Strings";

		// indexOf(char)
		System.out.println("indexOf(char) : " + str.indexOf('a'));

		// indexOf(char) - non exist character
		System.out.println("indexOf(char) - non exist character : "
				+ str.indexOf('z'));

		// lastIndexOf(char)
		System.out.println("lastIndexOf(char) : " + str.lastIndexOf('a'));

		// lastIndexOf(string)
		System.out.println("lastIndexOf(string) : " + str.lastIndexOf("Str"));

		// lastIndexOf(string,fromIndex)
		System.out.println("lastIndexOf(string,fromIndex) : "
				+ str.lastIndexOf("Str", 4));
	}
}

Output…

indexOf(char) : 1
indexOf(char) - non exist character : -1
lastIndexOf(char) : 3
lastIndexOf(string) : 5
lastIndexOf(string,fromIndex) : -1

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*