Display the position of a Substring in Java

To display the position of a Substring in Java, we use the lastindexOf() method in Java. The lastindexOf() method returns the rightmost occurrence of the substring within a particular StringBuffer object.

If the substring occurs more than once in the StringBuffer object, the index of the first character of the rightmost occured substring is returned. If the substring is not found, the lastIndexOf() method returns -1.

Declaration − The java.lang.StringBuffer.lastIndexOf() method is declared as follows−

public int lastIndexOf(String s)

where s is the substring whose index needs to be found

Let us see a program which displays the position of a Substring.


 Live Demo

public class Example {
   public static void main(String[] args) {
      StringBuffer sb= new StringBuffer("Welcome to Java .Version Java 7");
      int pos = sb.lastIndexOf("Java");