Home >>Java String Methods >Java String compareTo() method
The compareTo() method for the java string compares the given string lexicographically with the current string. It gives positive number, negative number or 0 back.
It compares strings based on the Unicode value of the individual characters in strings.
If the first string is lexicographically larger than the second string it returns positive number (character value difference). If the first string is lexicographically less than the second string it returns negative number and if the first string is lexicographically equal to the second string it returns 0.
if n1 > n2, it returns positive number
if n1 < n2, it returns negative number
if n1 == n2, it returns 0
public boolean equals(Object anObject)
{
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int x = value.length;
if (x == anotherString.value.length) {
char n1[] = value;
char n2[] = anotherString.value;
int i = 0;
while (x-- != 0) {
if (n1[i] != n2[i])
return false;
i++;
}
return true;
}
}
return false;
}
public int compareTo(String anotherString)
anotherString : String to be matched with present string
an integer value
public class CompareToExample
{
public static void main(String args[])
{
String n1="welcome";
String n2="welcome";
String n3="to";
String n4="Phptpoint";
String n5="world";
System.out.println(n1.compareTo(n2));
System.out.println(n1.compareTo(n3));
System.out.println(n1.compareTo(n4));
System.out.println(n1.compareTo(n5));
}}
When comparing string with blank or empty string it returns the string length. If the second string is zero, then the result is positive. If the first string is empty then the result is negative.
public class CompareToExample2
{
public static void main(String args[])
{
String n1="Phptpoint";
String n2="";
String n3="world";
System.out.println(n1.compareTo(n2));
System.out.println(n2.compareTo(n3));
}}