This documentation is archived and is not being maintained.

java.lang.String.compareTo(String str)

Visual Studio 2005

Compares two java.lang.String objects for equality.


public int compareTo(String str)

Parameters

Parameter Description

str

A String object to compare with the current String object for equality.

Less than zero if the current String object is less than str, zero if the two String objects are equal, or greater than zero if str is greater than the current String object.

// string_compareto.jsl

public class Program
{
    public static void main(String[] args)
    {
        String str1 = "This is string 1";
        String str2 = "This is string 2";

        // Compare the two strings.
        int result = str1.compareTo(str2);

        // Display the results of the comparison.
        if (result < 0)
        {
            System.out.println("\"" + str1 + "\"" +
                " is less than " +
                "\"" + str2 + "\"");
        }
        else if (result == 0)
        {
            System.out.println("\"" + str1 + "\"" +
                " is equal to " +
                "\"" + str2 + "\"");
        }
        else // if (result > 0)
        {
            System.out.println("\"" + str1 + "\"" +
                " is greater than " +
                "\"" + str2 + "\"");
        }
    }
}

/*
Output:
"This is string 1" is less than "This is string 2"
*/
Show: