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
Java class can be private?
We can not declare top level class as private. Java allows only public and default modifier for top level classes in java. Inner classes can be private.
Famous Quotations
Do not confuse motion and progress. A rocking horse keeps moving but does not make any progress.
-- Alfred A. Montapert

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.