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
What is race condition?
A race condition is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled. Race conditions can lead to unpredictable results and subtle program bugs. A thread can prevent this from happening by locking an object. When an object is locked by one thread and another thread tries to call a synchronized method on the same object, the second thread will block until the object is unlocked.
Famous Quotations
When I do good, I feel good; when I do bad, I feel bad, and that is my religion.
-- Abraham Lincoln

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.