
138 views
String equals() and equalsIgnoreCase()
The Java equals()
and equalsIgnoreCase()
methods are used to compare strings for equality. They allow you to determine whether two strings have the same content. However, there are some differences between these two methods:
- equals() Method:
- The
equals()
method is used to compare two strings for exact content equality, including the case (i.e., it’s case-sensitive). - It returns a boolean value,
true
if the strings are equal, andfalse
otherwise. - The basic syntax is:
boolean result = str1.equals(str2);
Example:
String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equals(str2); // Returns false because of case difference
- equalsIgnoreCase() Method:
- The
equalsIgnoreCase()
method is used to compare two strings for content equality while ignoring the case (i.e., it’s case-insensitive). - It returns a boolean value,
true
if the strings are equal (ignoring case), andfalse
otherwise. - The basic syntax is:
boolean result = str1.equalsIgnoreCase(str2);
Example:
String str1 = "Hello";
String str2 = "hello";
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // Returns true because the case is ignored
It’s important to choose the appropriate method based on your specific comparison requirements. Here’s a summary of their use cases:
- Use
equals()
when you want to compare strings while considering case sensitivity. This method is useful when you want to ensure that two strings are identical, including their case. - Use
equalsIgnoreCase()
when you want to compare strings while ignoring case differences. This method is helpful when you want to check if two strings have the same content regardless of the letter casing.
Keep in mind that both methods are commonly used in various situations, such as user input validation, string matching, and string comparison tasks.