Computer Applications
If
String x = "Computer";
String y = "Science";
What will the following return?
(a) System.out.print(x.substring(2,6));
(b) System.out.print(x.indexOf(x.charAt(5)));
Answer
(a)
Output
mput
Explanation
The substring() method returns a substring beginning from the startindex and extending to the character at index endIndex - 1. Here, startindex is 2 and end index is 5 (6 - 1). Since the string starts from index 0, the extracted substring is "mput". Thus, "mput" is printed on the screen.
(b)
Output
5
Explanation
charAt() method returns a character from the string at the index specified as its argument. indexOf() method returns the index of the first occurrence of the specified character within the string or -1 if the character is not present. Thus, the given expression is evaluated as follows:
x.indexOf (x.charAt (5) )
⟹ x.indexOf ( 't' )
⟹ 5