OutputHard2 marks
Give the output of the following string functions: (i) "MISSISSIPPI".indexOf('S') + "MISSISSIPPI".lastIndexOf('I') (ii) "CABLE".compareTo("CADET")
Topic: indexOf(), lastIndexOf() and compareTo()
Previous-year question practice database
Answer
Exam answer
(i) 12 (ii) -2
Explanation
(i) Index the word: M=0, I=1, S=2, S=3, I=4, S=5, S=6, I=7, P=8, P=9, I=10. indexOf('S') searches forward and finds the first S at index 2. lastIndexOf('I') searches backward and finds the last I at index 10. Both return ints, so the + adds them: 2 + 10 = 12. (ii) compareTo() stops at the first differing character: C and A match, then 'B' (66) meets 'D' (68), giving 66 - 68 = -2. The negative sign shows "CABLE" comes first alphabetically.
More from String Manipulation
To extract the word NOW from the word "ACKNOWLEDGEMENT", the Java statement "ACKNOWLEDGEMENT".substring(3, ____) is used. Choose the correct number to fill in the blank.2026String a[] = {"Atasi", "Aditi", "Anant", "Amit", "Ahana"};
System.out.println(a[1].charAt(1) + "*" + a[2].charAt(2));
The output of the above statement is:2026Which of the following String methods returns a negative value?2026Assertion (A): The substring() method modifies the original String.
Reason (R): The substring() method can extract part of a String starting from a specific index.2026Give the output of the following program segment:
String S = "GRACIOUS".substring(4);
System.out.println(S);
System.out.println("GLAMOROUS".endsWith(S));2026Name the following:
(a) The return data type of the method equals().
(b) The String method which has no parameter and returns a String.2026