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
Rewrite the following code using the if-else statement:
int m = 400; double ch = (m>300) ? (m / 10.0) * 2 : (m / 20.0) - 2;Give the output of the following program segment:
int n = 4279; int d; while(n > 0) { d = n % 10; System.out.println(d); n = n / 100; }Consider the given array and answer the questions given below:
int x[ ] = {4, 7, 9, 66, 72, 0, 16};
(a) What is the length of the array?
(b) What is the value in x[4]?
Name the following:
(a) What is an instance of the class called?
(b) The method which has same name as that of the class name.