Java: String compareToIgnoreCase(String anotherString) method

In this article, we will discuss how to compare two strings using String’s compareToIgnoreCase() method which ignores CASE difference while comparing

 

compareToIgnoreCase(String anotherString) method: This String method compares 2 string lexicographically ignoring CASE differences and returns an integer value

  • Returns 0, if str1 == str2 (both strings are lexicographically equal)
  • Returns +ve value, if str1 > str2 (1st string lexicographically greater than 2nd string)
  • Returns -ve value, if str1 < str2 (1st string lexicographically lesser than 2nd string)

Note: This is same as that of String’s compareTo(String anotherMethod), but it ignores CASE differences while comparing 2 strings

Method Signature:

public int compareToIgnoreCase(String anotherString);

Returns:

  • Returns an integer value after lexicographical comparison

 

Examples on compareTo() method:

  • Below piece of code depicts lexicographical comparison

StringCompareToIgnoreCaseMethod.java

package in.bench.resources.string.methods;

public class StringCompareToIgnoreCaseMethod {

	public static void main(String[] args) {

		String str1 = "STAR";  
		String str2 = "star";
		String str3 = "OneStAR";
		String str4 = "ONEStar";

		// compare 1: lexicographically comparing ignoring CASE
		int compare1 = str1.compareToIgnoreCase(str2);

		// printing to console
		System.out.println("String comparison of str1 and str2 : " 
				+ compare1);

		// compare 2: lexicographically comparing ignoring CASE
		int compare2 = str3.compareToIgnoreCase(str4);

		// printing to console
		System.out.println("String comparison of str3 and str4 : " 
				+ compare2);
	}
}

Output:

String comparison of str1 and str2 : 0
String comparison of str3 and str4 : 0

 

References:

 

Happy Coding !!
Happy Learning !!

Java: String concat(String str) method
Java: String compareTo(String anotherString) method