Java String LastIndexOf Example

There are four different versions of the lastIndexOf() method of the String class. All four versions return the index of a position, but each take different parameters as input. The lastIndexOf() method will return an integer that represents the last occurrence of a string or character within a string.

Method Parameters Return Type Exceptions Description
lastIndexOf() char int none Returns the index within this string of the last occurrence of the specified character.
lastIndexOf() int
int
int none Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
lastIndexOf() String int none Returns the index within this string of the last occurrence of the specified substring.
lastIndexOf() String
int
int none Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.


Java String LastIndexOf Source Code

The sample code below gives an example of each of the four instances of the lastIndexOf() method.

package com.jcd.java.tutorials;

public class JavaStringLastIndexOf 
{

	public static void main(String[] args) 
	{

		//There are 2 'C' in the string, but it will return the index of the last one.
		String jcdString1 = "Java Code Depot Com";
		int jcdInt1 = jcdString1.lastIndexOf('C');
		System.out.println("Index of last 'C' in the string: "+jcdInt1);
		
		
		//There are 2 'C' in the string, setting the indexOf to 10, the first 'C' becomes th last one found
		String jcdString2 = "Java Code Depot Com";
		int jcdInt2 = jcdString2.lastIndexOf('C', 10);
		System.out.println("Index of last 'C' in the string: "+jcdInt2);
		
		
		//Will return the index of the start to 'Depot' in the string
		String jcdString3 = "Java Code Depot Com Depot";
		int jcdInt3 = jcdString3.lastIndexOf("Depot");
		System.out.println("Index of last 'Depot' in the string: "+jcdInt3);
		
		
		//There are 2 'Depot' in the string, setting the indexOf to 10, the first 'Depot' becomes the last one found
		String jcdString4 = "Java Code Depot Com Depot";
		int jcdInt4 = jcdString4.lastIndexOf("Depot", 10);
		System.out.println("Index of last 'Depot' in the string: "+jcdInt4);

	}

}


Java String LastIndexOf Output

Index of last 'C' in the string: 16
Index of last 'C' in the string: 5
Index of last 'Depot' in the string: 20
Index of last 'Depot' in the string: 10


Add a Comment

Your email address will not be published. Required fields are marked *