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
ServletOuptputStream Vs PrintWriter
ServletOutputStream: ServletResponse.getOutputStream() returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data, it sends the raw data as it is.

PrintWriter: ServletResponse.getWriter() returns PrintWriter object which sends character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response's character encoding has not been specified then it does default character encoding.
Famous Quotations
Millions long for immortality who do not know what to do with themselves on a rainy Sunday afternoon.
-- Susan Erz

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.