In this guide, you will learn about the String equalsIgnoreCase() method in Java programming and how to use it with an example.
1. String equalsIgnoreCase() Method Overview
Definition:
The equalsIgnoreCase() method in Java's String class is used to compare two strings for content equality, ignoring case considerations.
Syntax:
str1.equalsIgnoreCase(str2)
Parameters:
- str2: The string to be compared with str1.
Key Points:
- This method returns true if the argument string represents the same sequence of characters as the string object, irrespective of their case.
- The method is particularly useful when comparing strings in scenarios where a case shouldn't affect the outcome, such as user-input validation.
- Unlike the equals() method, equalsIgnoreCase() is not case-sensitive.
- If the str2 is null, the method will return false.
2. String equalsIgnoreCase() Method Example
public class EqualsIgnoreCaseExample {
public static void main(String[] args) {
String sample1 = "Java";
String sample2 = "JAVA";
String sample3 = "JaVa";
// Comparing two strings with different cases
boolean areEqual1 = sample1.equalsIgnoreCase(sample2);
System.out.println("Are sample1 and sample2 equal ignoring case? " + areEqual1);
// Comparing two strings with mixed cases
boolean areEqual2 = sample1.equalsIgnoreCase(sample3);
System.out.println("Are sample1 and sample3 equal ignoring case? " + areEqual2);
// Attempting to compare with a null string
boolean equalsNull = sample1.equalsIgnoreCase(null);
System.out.println("Is sample1 equal to null ignoring case? " + equalsNull);
}
}
Output:
Are sample1 and sample2 equal ignoring case? true Are sample1 and sample3 equal ignoring case? true Error: Cannot compare a string with null.
Explanation:
In the example:
1. We first compare the string "Java" with "JAVA". Though they differ in case, their content is identical when a case is ignored, resulting in true.
2. Next, we compare "Java" with "JaVa", which has mixed cases. Again, since the equalsIgnoreCase() method ignores the case, the output is true.
3. Finally, we intentionally attempt to compare a string with null. The equalsIgnoreCase() method returns false when compared to null.
Related Java String Class method examples
- Java String charAt() example
- Java String concat() example
- Java String contains() example
- Java String endsWith() example
- Java String equals() example
- Java String equalsIgnoreCase() example
- Java String getBytes() example
- Java String indexOf() example
- Java String isEmpty() example
- Java String lastIndexOf() example
- Java String length() example
- Java String replace() example
- Java String split() example
- Java String startsWith() example
- Java String substring() example
- Java String toLowerCase() example
- Java String toUpperCase() example
- Java String trim() example
- Java String valueOf() example
Comments
Post a Comment
Leave Comment