Give the output of the following String class methods:
(a) "COMMENCEMENT".lastIndexOf('M')
(b) "devote".compareTo("DEVOTE")
Give the output of the following String class methods:
(a) "COMMENCEMENT".lastIndexOf('M')
(b) "devote".compareTo("DEVOTE")
(a) "COMMENCEMENT".lastIndexOf('M')
8
The lastIndexOf('M') method searches for the last occurrence of the character 'M' in the string "COMMENCEMENT." In this string, the last 'M' appears at the index 8, counting from 0-based indexing. So, the method returns the index 8 as the output, indicating the position of the last 'M' in the string.
(b) "devote".compareTo("DEVOTE")
32
compareTo() method compares two strings lexicographically. It results in the difference of the ASCII codes of the corresponding characters. The ASCII code for 'd' is 100 and the ASCII code for 'D' is 68. The difference between their codes is 32 (100 - 68).
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.