Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

lastIndexOf()

Example

Look for the final instance of “planet” within a string.

String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.lastIndexOf("planet"));

Definition and Usage

The lastIndexOf() method retrieves the position of the last occurrence of specified character(s) in a string.

Hint: Utilize the indexOf method to obtain the position of the first occurrence of specified character(s) in a string.

Syntax

One of the following:

public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)
public int lastIndexOf(int char)
public int lastIndexOf(int char, int fromIndex)

Parameter Values

Parameter

Description

str

A string value indicating the string to search within.

fromIndex

An integer value indicating the starting index position for the search. If not specified, the default value is the length of the string.

char

An integer value representing a single character, for example, ‘A’, or a Unicode value.

Technical Details

Returns

An integer value indicating the index of the character’s first occurrence in the string, or -1 if it does not occur.

More Examples

Example

Locate the final instance of “e” in a string, commencing the search from position 5.

public class Main {
  public static void main(String[] args) {
    String myStr = "Hello planet earth, you are a great planet.";
    System.out.println(myStr.lastIndexOf("e", 5));
 }
}