Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Arrays Gotchas and Wins Sorting

Why does `"Apple".compareTo("apple");` return -32 and not 1, 0 or -1?

As the title says "Apple".compareTo("apple"); returns -32. Similarly, "apple".compareTo("Apple"); returns 32.

Why is this different from the described return values of 1, 0, and -1?

For reference, "APPLE".compareTo("apple"): returns -32 and "apple".compareTo("APPLE"); also returns 32.

1 Answer

Tonnie Fanadez
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tonnie Fanadez
UX Design Techdegree Graduate 22,796 Points

Hello Dylan Cascio

Good Question.

The compareTo()method defines the natural order - the default way for ordering objects of a class. The comparison is based on the Unicode Value of each character in the Strings being compared.

Please refer to this link for Unicode Character Table - http://sticksandstones.kstrom.com/appen.html

You will note that the Unicode value for "a" is 097 and "A" is 065 .... "b" is 98 and "B" is 66. and so forth. Since compareTo() is subtracts one value from another, the difference between a Capital Letter and a Lowercase Letter is always -32 for the same letter. The difference is always +32 for (Lowercase - Uppercase) when dealing with the same letter.

It is not a must for 1 or -1 to be returned - unless the letters being tested follow each other in case of "a" and "b" or "c" and "d" or "y" and "z"- Java documentation don't specify it is 1 or -1 to be returned but rather says a positive or a negative integer. 0 is only returned if objects are equal e.g. "d"=="d"

Hope this helps.

Cheers

Thank you! That's so much clearer now. I see now that I just hadn't written out enough examples in jshell. It looks like even something like "apple".compareTo("orange"); evaluates to -14 and "apple".compareTo("czzzzzzz"); returns -2.