Computer Applications

Give the output of the following String class methods:

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

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

Java

Java String Handling

ICSE 2023

46 Likes

Answer

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

Answered By

26 Likes


Related Questions