Manish Agarwal
Manish Agarwal

Reputation: 11

String compareTo() in java

Consider:

String s1 = "ABc";
String s2 = "abc";
System.out.println(s1.compareTo(s2));

On which basis the output will be -32 if only the first character decimal value of s1 and s2 are compared? Is this the correct way?

If String contains more than 1 character, then we should compare each character, but compareTo() method only compares the first character. Isn’t this a bug?

Upvotes: -4

Views: 105

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198391

compareTo guarantees that it returns some negative number if s1 comes before s2 in lexicographic order.

When comparing "apple" and "banana", for example, you only need to look at the first character to determine that "apple" comes before "banana", because a comes before b.

Upvotes: 0

Related Questions