String Handling — Question 8
Back to all questionsQuestion 8
If:
String x = "Computer";
String y = "Applications";What do the following functions return?
(i) System.out.println(x.substring(1,5));
(ii) System.out.println(x.indexOf(x.charAt(4)));
(iii) System.out.println(y + x.substring(5));
(iv) System.out.println(x.equals(y));
(i) System.out.println(x.substring(1,5));
Output
ompu
Explanation
x.substring(1,5) will return a substring of x starting at index 1 till index 4 (i.e. 5 - 1 = 4).
(ii) System.out.println(x.indexOf(x.charAt(4)));
Output
4
Explanation
charAt() method returns the character at a given index in a String. Thus, x.charAt(4) will return the character at the 4th index i.e., u. indexOf() method returns the index of the first occurrence of a given character in a string. Thus, it returns the index of u, which is 4.
(iii) System.out.println(y + x.substring(5));
Output
Applicationster
Explanation
x.substring(5) will return the substring of x starting at index 5 till the end of the string. It is "ter". This is added to the end of string y and printed to the console as output.
(iv) System.out.println(x.equals(y));
Output
false
Explanation
equals() method checks for value equality, i.e., whether both objects have the same value regardless of their memory location. As the values of both x and y are different so it returns false.