最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

String compareTo() in java - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question edited Nov 21, 2024 at 5:59 Anonymous 86.4k15 gold badges162 silver badges177 bronze badges asked Nov 20, 2024 at 18:24 Manish AgarwalManish Agarwal 11 8
  • 8 This is explained in the documentation. Also, why do you want to compare more characters when the first characters are already different? – Sweeper Commented Nov 20, 2024 at 18:30
  • 6 I don't see a question here? – Sören 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. – the busybee 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. – Anonymous Commented Nov 21, 2024 at 5:53
  • 1 Curious. When closely reading, deep down in the text you are correct. @OldDogProgrammer How useless. – Anonymous Commented Nov 21, 2024 at 20:59
 |  Show 3 more comments

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论