KnowledgeBoat Logo

Computer Applications

Differentiate between indexOf() and lastIndexOf().

Java String Handling

2 Likes

Answer

indexOf()lastIndexOf()
The indexOf() method returns the index of the first occurrence of the specified character in a string.The lastIndexOf() method returns the index of the last occurrence of the specified character in a string.
Example:
String str = "How are you?";
int index = str.indexOf('o');
System.out.println("Index = " + index);

The output is
Index = 1
Example:
String str = "How are you?";
int index = str.lastIndexOf('o');
System.out.println("Index = " + index);

The output is
Index = 9

Answered By

1 Like


Related Questions