2(viii)
Give the output of the following:
(a) "ROSE".compareTo("ROJA")
(b) "DEDICATE".replace('D', 'L')
Show SolutionHide Solution↓
(a)
9
The method compareTo() compares two strings lexicographically by evaluating the Unicode value of each character from left to right until a mismatch is found.
- 'R' (82) vs 'R' (82) → same.
- 'O' (79) vs 'O' (79) → same.
- 'S' (83) vs 'J' (74) → difference = 83 - 74 = 9.
Since a mismatch occurs at the third character, the comparison stops; therefore, the characters 'E' and 'A' are not compared.
Hence, the method returns 9.
(b)
LELICATE
The replace('D', 'L') method substitutes every occurrence of the character 'D' in the string "DEDICATE" with 'L', resulting in "LELICATE".