compareTo#

Sumit Rawal answered on May 23, 2023 Popularity 9/10 Helpfulness 1/10

Contents


More Related Answers

  • Comparisons#

  • compareTo#

    0

    compareTo compares two strings lexicographically, i.e., in alphabetical order. Unlike the other methods we have used above, compareTo returns an integer and that integer is the mathematical difference between the strings. If the strings are identical, 0 is returned. If a positive number is returned, that means that string1 is greater than string2. If a negative number is returned, that means that string1 is less than string2.

    string2 is subtracted from string1.

    A question arises; how can strings be less than or greater than other strings if they aren’t numbers?

    Every character, from letters to numbers to symbols, has a unique Unicode value. Using these values, we can perform mathematical operations on strings.

    For example, "a" has a Unicode value of U+0061 which is equivalent to a decimal value of 97. "1" has a Unicode value of U+0031 which is equivalent to a decimal value of 49. Hence, when we subtract "1" from "a", we are actually subtracting 49 from 97 giving us a difference of 48.

    You don’t need to memorize these values, the table of the official Unicode standard is readily available.

    compareTo compares each character of string1 with the character in the same position as string2. The syntax is as follows.

    Popularity 9/10 Helpfulness 1/10 Language scala
    Source: Grepper
    Tags: scala
    Link to this answer
    Share Copy Link
    Contributed on May 23 2023
    Sumit Rawal
    0 Answers  Avg Quality 2/10


    X

    Continue with Google

    By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
    X
    Grepper Account Login Required

    Oops, You will need to install Grepper and log-in to perform this action.