-4

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?

8
  • 8
    This is explained in the documentation. Also, why do you want to compare more characters when the first characters are already different? Commented Nov 20, 2024 at 18:30
  • 6
    I don't see a question here? Commented Nov 20, 2024 at 18:32
  • 1
    Welcome to StackOverflow! Please take the tour to learn how this site works, and read "How to Ask" and other pages of the help center. Then come back and clarify your issue, editing your question to add an actual question. Commented Nov 20, 2024 at 18:40
  • Welcome to Stack Overflow. How can you know which characters it compares and which not? In any case comparing the first character of each string, A with a, 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 and A), the method would need to look at the second char of each string. Commented Nov 21, 2024 at 5:53
  • 1
    Curious. When closely reading, deep down in the text you are correct. @OldDogProgrammer How useless. Commented Nov 21, 2024 at 20:59

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That is guaranteed by interface Comparable, which String does implement. But, you could improve the answer by including a response to this part of the O/P's question: "On which basis the output will be -32".
@OldDogProgrammer, I disagree. I think knowing why the answer will be -32 is actively harmful, as it's not something you should use, care about, or depend on in any way, and I'd strongly consider down voting any answer that did explain that.
That's reasonable. But, I have to wonder if whoever wrote the documentation for String#compareTo method agrees, since the documentation does describe how non-zero results are calculated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.