String lastIndexOf returns the index of the last occurrence of the given String for specified conditions searching backward. String lastIndexOf method can be used with multiple types of parameters as shown below
1 2 3 4 |
public int lastIndexOf(int ch) public int lastIndexOf(int ch,int fromIndex) public int lastIndexOf(String str) public int lastIndexOf(String str,int fromIndex) |
1. int lastIndexOf(int ch) returns the index of the last occurrence of the specified character searching backward.
2. int lastIndexOf(int ch,int fromIndex) returns the index of the last occurrence of the specified character starting from the “fromIndex” searching backward
3. int lastIndexOf(String str) returns the index of the last occurrence of the specified String searching backward.
4. int lastIndexOf(String str,int fromIndex) returns the index of the last occurrence of the specified String from the “fromIndex” searching backward.
String lastIndexOf example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.kscodes.sampleproject; public class StringLastIndexOfExample { public static void main(String[] args) { String testStr1 = "This is test String for lastIndexOf example"; System.out.println("Using lastIndexOf(int) finding index of 'S' :: " + testStr1.lastIndexOf('S')); System.out.println("Using lastIndexOf(int,int) finding index of 'e' after 20 Charatcers :: " + testStr1.lastIndexOf('e', 20)); System.out.println("Using lastIndexOf(String) finding index of 'test' :: " + testStr1.lastIndexOf("test")); System.out.println("Using lastIndexOf(int) finding index of 'ex' after 15 characters :: " + testStr1.lastIndexOf("ex",15)); System.out.println("-----------------------"); System.out.println("Using lastIndexOf(String) finding index of '1234356' :: " + testStr1.lastIndexOf("123456")); } } |
Output
1 2 3 4 5 6 |
Using lastIndexOf(int) finding index of 'S' :: 13 Using lastIndexOf(int,int) finding index of 'e' after 20 Charatcers :: 9 Using lastIndexOf(String) finding index of 'test' :: 8 Using lastIndexOf(int) finding index of 'ex' after 15 characters :: -1 ----------------------- Using lastIndexOf(String) finding index of '1234356' :: -1 |
Before performing any operation on any dynamically generated String, check if the String is not null.
Else a NullPointerException is thrown.
Reference
1. String API