KnowledgeBoat Logo
|

Computer Applications

What is the output of the statement given below?

"ANGER".compareTo("ANGEL")

  1. 3
  2. -6
  3. 6
  4. 0

Java

Java String Handling

5 Likes

Answer

6

Reason — The compareTo() method compares two strings lexicographically by comparing their characters one by one. It returns the difference between the first pair of characters that differ in the two strings.

Here, comparing "ANGER" and "ANGEL":

  • Characters 'A', 'N', 'G', and 'E' are the same in both strings at positions 0 to 3.
  • At position 4, 'R' (ASCII value 82) in "ANGER" is compared with 'L' (ASCII value 76) in "ANGEL".
  • The difference is 82 - 76 = 6.

Thus, the output is 6.

Answered By

1 Like


Related Questions