Menu
Topics Index
...
`

String CompareTo Demo - Java Example Program


String CompareTo Demo
class CompareToTest
{
    public static void main(String[] args)
    {
        String str1 = "The best way to predict your future is to create it";
        String str2 = "The best way to predict ";
        String str3 = "your future is to create it";
        //comparing str1 with str2 + str3
        compare(str1, str2 + str3); // LINE A
        //comparing str1 with str2
        compare(str1, str2); // LINE B
        //comparing str1 with str3
        compare(str1, str3); // LINE C
    }
    
    public static void compare(String one, String two)
    {
        int result = one.compareTo(two);
        if (result == 0)
        {
            System.out.print("Invoking string and argument string are equal.");
        }
        else if (result < 0)
        {
            System.out.print("The invoking string follows the argument string.");
        }
        else
        {
            System.out.print("The invoking string precedes the argument string.");
        }
        System.out.println(" The comparision value is : " + result);
    }
}
OUTPUT

Invoking string and argument string are equal. The comparision value is : 0
The invoking string precedes the argument string. The comparision value is : 27
The invoking string follows the argument string. The comparision value is : -37

DESCRIPTION

In the first comparision both the strings are lexicographically equal, 0 is returned at LINE A.
At LINE B, case 2, as mentioned above holds. str2 lexicographically precedes str1. The difference of the lengths is returned.
At LINE C, str1 precedes str3 as 'T' precedes 'y' in the unicode character list. It returns the difference of the unicode values of 'T' and 'y' i.e. -37.

THINGS TO TRY
  • Compare two similar strings, one in lowercase and the other in uppercase.
    For e.g., "Learn Java" vs "LEARN JAVA".
  • Try with the below code.
    String str1 = "Merit Campus";
    String str2 = "Merit Campus";
    boolean result = str1.equals(str2);
    System.out.println(result);
    int comparisionValue = str1.compareTo(str2);
    System.out.println(comparisionValue);
    The output for the above code is as shown.
    true
    0
    The return type of equals method is boolean. compareTo method compares the strings character by character if all the characters match it returns 0 otherwise it returns the difference between the comparing character to compared character. So the return type is int.

© meritcampus 2019

All Rights Reserved.

Open In App