OutputHard2 marks
Give the output of the following String class methods: (a) "COMMENCEMENT".lastIndexOf('M') (b) "devote".compareTo("DEVOTE")
Topic: lastIndexOf() and compareTo()
Previous-year question practice database
Answer
Exam answer
(a) 8 (b) 32
Explanation
(a) lastIndexOf() searches from the END and returns the position of the final occurrence. Index the word: C=0, O=1, M=2, M=3, E=4, N=5, C=6, E=7, M=8, E=9, N=10, T=11. The last M is at index 8. (indexOf would have given 2 — that contrast is the point.) (b) compareTo() stops at the first differing character and returns the difference of the ASCII codes. Here 'd' is 100 and 'D' is 68, so 100 - 68 = 32. The value is positive because lowercase letters come after uppercase in the ASCII table. Remember 32 as the constant gap between any uppercase letter and its lowercase partner.
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