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

indexOf()

Example

Find the first occurrence of “planet” within a string.

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

Definition and Usage

The indexOf() method retrieves the position of the first occurrence of specified character(s) within a string.

Tip: Utilize the lastIndexOf method to obtain the position of the last occurrence of specified character(s) within a string.

Syntax

“Choose one from the following options:”

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

Parameter Values

Description

Parameters

str

“A String value representing the string to be searched for.”

fromIndex

“An integer value representing the starting index position for the search.”

char

“An integer value representing a single character, such as ‘A’, or a Unicode value.”

Technical Details

Returns

Return an integer value indicating the index of the first occurrence of the character in the string, or -1 if it is not found.

More Examples

Example

Locate the first instance of the letter “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.indexOf("e", 5));
  }
}