JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Java String lastIndexOf() Sample Code


Description:

Below example shows how to get index of a given character or string from a string in the reverse order, means last occuring index. By using lastIndexOf() method you can get last occurence of the the reference string or character. Also lastIndexOf() method gives last occurence based on a specific position.


Code:
package com.myjava.string;

public class MyStrLastIndexOf {

    public static void main(String a[]){
    
        String str = "Use this string for testing this";
        System.out.println("Basic lastIndexOf() example");
        System.out.println("Char 's' at last occurance: "+str.lastIndexOf('s'));
        System.out.println("String \"this\" at last occurance: "+str.lastIndexOf("this"));
        /**
         * Returns the last occurance from specified start index, 
         * searching backward starting at the specified index.
         */
        System.out.println("first occurance of char 's' from 24th index backwards: "
							+str.lastIndexOf('s',24));
        System.out.println("First occurance of String \"this\" from 26th index backwards: "
							+str.lastIndexOf("this",26));
    }
}

Example Output

Basic lastIndexOf() example
Char 's' at last occurance: 31
String "this" at last occurance: 28
first occurance of char 's' from 24th index backwards: 22
First occurance of String "this" from 26th index backwards: 4

Other String Function Examples

Knowledge Centre
Difference between while and do-while
The while statement verifies the condition before entering into the loop to see whether the next loop iteration should occur or not. The do-while statement executes the first iteration without checking the condition, it verifies the condition after finishing each iteration. The do-while statement will always execute the body of a loop at least once.
Famous Quotations
The greatest obstacle to discovery is not ignorance; it is the illusion of knowledge.
-- Daniel J. Boorstin

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.