• August 28, 2014
  • Core Java
  • Comments Off on indexOf(String str) and lastIndexOf(String str) String functions in java

indexOf(String str) and lastIndexOf(String str) String functions in java

indexOf(String str): Returns the index of the first occurrence of the specified substring within this string.

Syntax:  public int indexOf(String str).

Note: If no such occurrence of substring within this string than it returns -1.

lastIndexOf(String str): Returns the index of the last occurrence of the specified substring within this string.

Syntax: public int lastIndexOf(String str).

Note: If no such occurrence of substring within this string than it returns -1.

Example:

StringIndexTestExample.java

/**
 * This program is used to show the use 
 * of indexOf and lastIndexOf() method.
 * @author javawithease
 */
class TestString{
	String str = "www.javawithease.com";
 
	/**
	 * This method is used to show the use of indexOf() method.
	 * @author javawithease
	 */
	public void indexOfTest(){
		System.out.println(str.indexOf("a"));
	}
 
	/**
	 * This method is used to show the use of lastIndexOf() method.
	 * @author javawithease
	 */
	public void lastIndexOfTest(){
		System.out.println(str.lastIndexOf("e"));
	}
}
 
public class StringIndexTestExample {
	public static void main(String args[]){
		//creating TestString object
		TestString obj = new TestString();
 
		//method call
		obj.indexOfTest();
		obj.lastIndexOfTest();
	}
}

Output:

5
15

Download this example.
 
Next Topic: toLowerCase() and toUpperCase() String functions in java.
Previous Topic: startsWith(String prefix) and endsWith(String suffix) String functions in java.

Related Topics:

String handling in java with example.
String Comparison in java with example.
String concatenation in java with example.
Substring in java with example.
How to write Immutable class in java with example.
toString() method in java with example.
Commonly used methods of String Class with example.
charAt(int index) String function in java with example.
startsWith(String prefix) and endsWith(String suffix) String functions in java.
indexOf(String str) and lastIndexOf(String str) String functions in java.
toLowerCase() and toUpperCase() String functions in java.
intern() String functions in java with example.
length() String functions in java with example.
trim() String functions in java with example.

 


Comments are closed.