Display the position of a Substring in Java

Java 8Object Oriented ProgrammingProgramming

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");


Published on 03-Jan-2019 11:35:59