Sobes.tech
Junior — Middle

Under what conditions does the compareTo method return -1 and when does it return 1?

sobes.tech AI

Answer from AI

The compareTo method in Java returns:

  • -1 (or any negative number) if the current object is less than the object being compared to.
  • 1 (or any positive number) if the current object is greater than the object being compared to.

For example, for comparing numbers:

Integer a = 5;
Integer b = 10;
int result = a.compareTo(b); // result will be negative (-1), since 5 < 10

result = b.compareTo(a); // result will be positive (1), since 10 > 5

It is important to note that the method can return any negative or positive number, not necessarily exactly -1 or 1, as long as the sign of the result indicates the order of comparison.