Home / Questions / Give the output of the following String class methods: (a) "COMMENCEMENT".lastIndexOf('M') (b) "devote".compareTo("DEVOTE")
Explanatory Question

Give the output of the following String class methods:

(a) "COMMENCEMENT".lastIndexOf('M')

(b) "devote".compareTo("DEVOTE")

👁 76 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

(a) "COMMENCEMENT".lastIndexOf('M')

Output

8

Explanation

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")

Output

32

Explanation

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).