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 Data Structures - Retired Organizing Data Interfaces

Chandrakanth R
Chandrakanth R
2,540 Points

Question on compareTo

I tried to run the command in java-repl and i get the corresponding output

java> "banana".compareTo("apple")
java.lang.Integer res0 = 1
java> "banana".compareTo("cranapple")
java.lang.Integer res1 = -1
java> "banana".compareTo("banaan")
java.lang.Integer res2 = 13
java> "banana".compareTo("banaana")
java.lang.Integer res3 = 13
java> "banana".compareTo("d")
java.lang.Integer res4 = -2
java> "banana".compareTo("e")
java.lang.Integer res5 = -3

but, according to the video, it is supposed to return values -1,0 and 1. Is this something different that is happening here or the way i typed the command is wrong?

1 Answer

Florian Tรถnjes
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Florian Tรถnjes
Full Stack JavaScript Techdegree Graduate 50,856 Points

Hi Chandrakanth,

from the Java docs:

The compareTo method returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Kind Regards, Florian

Chandrakanth R
Chandrakanth R
2,540 Points

Thank you for your time to reply, Floran

I understand what you are saying, but the code outputs 13 for "banana".compareTo("banaan") if you have noticed. Is it something that i am doing wrong?