How to compare two Strings using equalsIgnoreCase() Method in Java?

In the last tutorial, We have learned how to compare two strings using equals() method. But there is one limitation of the equals() method. By default equals() method check the content including case also i.e. The comparison is case sensitive. If the comparison is case insensitive it returns false. To overcome this problem we can use the equalsIgnoreCase() method in Java. Let's first see the example of, what the problem to use equals() method.

class StringCompare{
	public static void main(String args[]){
		String str1 = "Javastudypoint";
		String str2 = new String("JAVA");
		String str3 = new String("Javastudypoint");
		String str4 = "Java";
		System.out.println(str1.equals(str3)); //true
		System.out.println(str2.equals(str4)); //false
		System.out.println(str1.equals(str2)); //false
		
	}
}

Output:
true
false
false

The problem with the above code is it check the case also. In the above code, the str2 and the str3 have the same content but the case is different therefore the equals() method returns false.



equalsIgnoreCase() in Java:

To overcome the above problem, we can use the equalsIgnoreCase() method. This method is used to perform the comparison that ignores the case differences. When it compares two strings, it considered A-Z the same as a-z. 

Syntax: The syntax of the equalsIgnoreCase() is given below:

public boolean equalsIgnoreCase()


Comparison of two strings using the method equalsIgnoreCase()

Let's understand the equalsIgnoreCase() method in Java with an example.

class StringCompare{
	public static void main(String args[]){
		String str1 = "Javastudypoint";
		String str2 = "javaSTUDYpoint";
		String str3 = "JAVASTUDYPOINT"; 
		String str4 = "Java Tutorial";
               //true because content and case are same
		System.out.println(str1.equalsIgnoreCase(str3));
               //false because content and case are not the same.
		System.out.println(str2.equalsIgnoreCase(str4)); 
               //true because content and case are same
		System.out.println(str1.equalsIgnoreCase(str2)); 
		
	}
}

Output:
 compare two Strings using equalsIgnoreCase() Method in Java?
How to compare two Strings using equalsIgnoreCase() Method in Java? How to compare two Strings using equalsIgnoreCase() Method in Java? Reviewed by Prashant Srivastava on January 03, 2020 Rating: 5

No comments:

Powered by Blogger.