Doubt with the function compareTo

Asked

Viewed 805 times

3

When I run the code below the compareTo returns a value less than zero.

public class compare
{
 public static void main ( String [] args )
 {
    String str1 = "araraaaaaa";  
    String str2 = "asa";  

    int comp = str1.compareTo(str2);  

    System.out.println(""+comp) //  printa -1 na tela

 }
}

Theoretically, str1 is not greater than str2?
Why it returns negative?

  • If you want to compare the contents of these strings, use str1.equals(str2); that returns 'true' if they are equal.

1 answer

7

The method compareTo class String is used to sort the Strings alphabetically*, not by size. This way we have to "araraaaaaa" comes before "asa", and therefore the compareTo gives -1, because when comparing the first letter the two Strings are equal (a) and comparing the second, the r comes before the s.

To compare the Strings by size, you should invoke the method length of Strings and then compare sizes directly. (Suggestion from Marcelo Bonifazio)

It is also worth remembering that whenever we have a.compareTo(b) returning -1 (or some other negative number) means that a antecedent b, if it returns +1 (or some other positive number) then a happens b and if it returns 0 then a and b are similar. However, the exact definition of "antecede", "succeeds" and "similar" is at the discretion of each class that implements the compareTo. In the case of the class String the definition is given by alphabetical ordering*.


(*) - In fact the comparison is not exactly alphabetical, but rather is based on comparison of sequences of numerical values of codepoints Unicode.

  • an alternative would be nameDaString.length();

  • @Exact Marcelobonifazio

Browser other questions tagged

You are not signed in. Login or sign up in order to post.