Consider:
String s1 = "ABc";
String s2 = "abc";
System.out.println(s1pareTo(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?
Consider:
String s1 = "ABc";
String s2 = "abc";
System.out.println(s1pareTo(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?
1 Answer
Reset to default 0compareTo
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
.
A
witha
, suffices for knowing that a negative value must be returned. Which is all that the documentation promises us. Only if the first chars are the same (say,A
andA
), the method would need to look at the second char of each string. – Anonymous Commented Nov 21, 2024 at 5:53