CodesJava

Easy learning with example program codes

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 codesjava
 */
class TestString{
	String str = "www.codesjava.com";
 
	/**
	 * This method is used to show the use of indexOf() method.
	 * @author codesjava
	 */
	public void indexOfTest(){
		System.out.println(str.indexOf("o"));
	}
 
	/**
	 * This method is used to show the use of lastIndexOf() method.
	 * @author codesjava
	 */
	public void lastIndexOfTest(){
		System.out.println(str.lastIndexOf("a"));
	}
}
 
public class StringIndexTestExample {
	public static void main(String args[]){
		//creating TestString object
		TestString obj = new TestString();
 
		//method call
		obj.indexOfTest();
		obj.lastIndexOfTest();
	}
}

Output:

5
12

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.

 

Please follow and like us:
error
Posted in Java   








Copyright © 2019 CodesJava DMCA.com Protection Status