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

How does compareTo works? What does it checks and return the values ?

How does compareTo works? What does it checks and return the values ?

3 Answers

Zhoubing Yang
Zhoubing Yang
1,399 Points

obj.compareTo(secondObj) returns -1, 0 and 1 for obj is less than, equals to and greater than secondObj

x.compareTo(y) if x is an int than if x = 1, and int y = 1, it will return 0, meaning they are ==. -1 if x < y, and 1 if x > y.

if x and y are strings containing chars, than if x = "abcdefg" and y = "bcdefghijklmnop", it will return 1, because a comes before b alphabetically. if it was reverse, and x started with say.. c, or d, or any letter after b, it would return -1. because x would therefore be < y.