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
Where can we use serialization?
Whenever an object has to sent over the network, those objects should be serialized. Also if the state of an object is to be saved, objects need to be serilazed.
Famous Quotations
The pessimist complains about the wind; the optimist expects it to change; the realist adjusts the sails.
-- William Arthur Ward

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.