Computer Applications

What will be the output of the following program snippet?
str1 = "AMAN";
str2 = "AMIT";
System.out.println(str1.compareTo(str2));

  1. 8
  2. 0
  3. -8
  4. 2

Java String Handling

28 Likes

Answer

-8

Reason — compareTo() returns a negative value if the first string is smaller than the second string in terms of the ASCII values of the corresponding characters.
"AMAN" and "AMIT" differ at the third character with 'A' and 'I', respectively. So, output of compareTo() method will be ASCII Code of 'A' - ASCII Code of 'I' ⇒ 65 - 73 ⇒ -8.

Answered By

15 Likes


Related Questions