Computer Applications

Give the output of the following:

(a) "ROSE".compareTo("ROJA")

(b) "DEDICATE".replace('D', 'L')

Java

Java String Handling

4 Likes

Answer

(a)

9

Working

The method compareTo() compares two strings lexicographically by evaluating the Unicode value of each character from left to right until a mismatch is found.

  1. 'R' (82) vs 'R' (82) → same.
  2. 'O' (79) vs 'O' (79) → same.
  3. '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

Working

The replace('D', 'L') method substitutes every occurrence of the character 'D' in the string "DEDICATE" with 'L', resulting in "LELICATE".

Answered By

2 Likes


Related Questions