Compare two strings in Java

compareTo(String anotherString) and compareToIgnoreCase(String anotherString) methods of String class can be used to compare two strings in Java.

Both these methods will return 0 when both the strings are equal and when they are not equal, returns the difference of first unequal character's ascii values in negative or positive integer.


CompareTo(String anotherString) method

Example 1

class StringTest{

public static void main(String args[]){

String str1=new String("C2N");

String str2=new String("C2N");

System.out.println("Returned value when comparing strings is "+str1.compareTo(str2));

}

}

Output 1

Returned value when comparing strings is 0


Example 2

class StringTest{

public static void main(String args[]){

String str1=new String("2CN");

String str2=new String("2aN");

System.out.println("Returned value when comparing strings is "+str1.compareTo(str2));

}

}

Output 2

Returned value when comparing strings is -30

Explanation 2

First unequal characters in above example is character 'C' and 'a'. Ascii values of 'C' is 67 and 'a' is 97. Difference of two is -30.


Example 3

class StringTest{

public static void main(String args[]){

String str1=new String("C2N");

String str2=new String("A2N");

System.out.println("Returned value when comparing strings is "+str1.compareTo(str2));

}

}

Output 3

Returned value when comparing strings is 2


compareToIgnoreCase(String anotherString) method

This compares strings but ignores uppercase and lowercase characters and considers both as same-case characters.

Example

class StringTest{

public static void main(String args[]){

String str1=new String("C2N");

String str2=new String("c2N");

System.out.println("Value when comparing strings is "+str1.compareToIgnoreCase(str2));

}

}

Output

Value when comparing strings is 0