java.lang.StringBuffer lastIndexOf(String str,int fromIndex)

Syntax:

public int lastIndexOf(String str,int fromIndex)

Java Code Example :

This java example source code demonstrates the use of lastIndexOf(String str,int fromIndex) method of StringBuffer class. Initially the code assigns a string “javatutorialhq.com” as initial contents of the string buffer. Then we use the lastIndexof method to get the last index on the stringbuffer object where we find the string “a” in cosideration with another method argument fromIndex.

This is very useful to work with substring method of StringBuffer class. On this example we will also learn how to use the lastIndexOf method to work with substring.

package com.javatutorialhq.java.examples;

/*
 * This example source code demonstrates the use of 
 * lastIndexOf(String str,int fromIndex) method of StringBuffer class
 */

public class StringBufferLastIndexOfStringFromIndex {

	public static void main(String[] args) {

		// initialize the StringBuffer object
		StringBuffer sb = new StringBuffer("javatutorialhq.com");
		System.out.println("Contents of buffer:" + sb);

		// get the index of "a" string from the stringbuffer object
		String str = "a";
		int fromIndex = 3;
		int index = sb.lastIndexOf(str,fromIndex);		
		System.out.println("index:" + index);
		// incorporate substring method
		String result = sb.substring(0, index);
		System.out.println("Results:" + result);

	}
}

Sample Output :

Running the above example source code will give the following output

lastIndexOf(String str,int fromIndex) method example

lastIndexOf(String str,int fromIndex) method example

Suggested Reading List :

References :