ICSE Class 10 Computer Applications Question 15 of 46

String Handling — Question 15

Back to all questions
15
Question

Question 3(iv)

Differentiate between indexOf() and lastIndexOf().

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