Home » Java programming language

Java StringBuilder lastlastIndexOf() method with example

StringBuilder Class lastIndexOf() method: Here, we are going to learn about the lastIndexOf() method of StringBuilder Class with its syntax and example.
Submitted by Preeti Jain, on December 22, 2019

Syntax:

    public int lastIndexOf (String s);
    public int lastIndexOf (String s, int st_idx);

StringBuilder Class lastIndexOf() method

  • lastIndexOf() method is available in java.lang package.
  • lastIndexOf (String s) method is used to search the index within this string of the occurrence of the given string from the rightmost side.
  • lastIndexOf (String s, int st_idx) method is used to search the index within this string of the occurrence of the given substring from the rightmost side and searching will start from st_idx.
  • These methods may throw an exception at the time of returning then the last index of occurrence string.
    NullPointerException – This exception may throw when the given string parameter is null.
  • These are non-static methods, it is accessible with the class object only and, if we try to access these methods with the class name then we will get an error.

Parameter(s):

  • In the first case, String s – represents the substring to search for.
  • In the second case, String s, int st_idx
    • String s – Similar as defined in the first case.
    • int st_idx – represents the index to start the searching for.

Return value:

The return type of this method is int, it returns the index within this object of the last occurrence of the given substring.

Example:

// Java program to demonstrate the example 
// of lastIndexOf () method of StringBuilder class

public class LastIndexOf {
    public static void main(String[] args) {
        // Creating an StringBuilder object
        StringBuilder st_b = new StringBuilder("Java World ");

        // Display st_b 
        System.out.println("st_b = " + st_b);

        // By using lastIndexOf("a") method is to return the last index of 
        // given string "a" in st_b object 
        // (first a at index 1 and second a at index 3)
        // it returns 3
        int index1 = st_b.lastIndexOf("a");

        // Display st_b index
        System.out.println("st_b.lastIndexOf(String) = " + index1);

        // By using lastIndexOf("a",1) method is to return the last index of 
        // given string "a" in st_b object 
        // (first a at index 1 and second a at index 3)
        // it returns 3 and searching starts at index 1
        int index2 = st_b.lastIndexOf("a", 1);

        // Display st_b index
        System.out.println("st_b.lastIndexOf(String, int) = " + index2);
    }
}

Output

st_b = Java World 
st_b.lastIndexOf(String) = 3
st_b.lastIndexOf(String, int) = 1


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.