Java String.equals()
Learn to compare the content of two String objects in a case-sensitive manner using the String.equals() API. For case-insensitive comparison, we can use the equalsIgnoreCase() method.
Never use ‘==‘ operator for checking the strings equality. It verifies the object references, not the content, which is undesirable in most cases.
The String.equals() in Java compares a string with the object passed as the method argument. It returns true if and only if:
- the argument object is of type String
- the argument object is not null
- represents the same sequence of characters as the current string
String str1 = "alex"; String str2 = "alex"; String str3 = "alexa"; Assertions.assertTrue(str1.equals(str2)); Assertions.assertFalse(str1.equals(str3));
2. Throws NullPointerException
The equals() does not support null argument and throws NullPointerException.
String str1 = "alex"; Assertions.assertThrows(NullPointerException.class, () -> < str1.contains(null); >);
3. Only Case-sensitive Comparisons
The following Java program demonstrates that equals() method does the content comparison in a case-sensitive manner. If we change the case, strings are considered different.
String str1 = "alex"; Assertions.assertTrue(str1.equals("alex")); Assertions.assertFalse(str1.equals("Alex")); //different case is used
4. Difference between Equals Operator and equals() Method
As mentioned earlier, ‘==’ operator checks for the same object references. It does not check for string content. Whereas equals() method strictly checks for string content only.
In the following Java program, we have created two String objects. First we are comparing the objects using the equals operator which results in false because both are different objects in memory.
Then we check the content of strings using the equals() that returns true because even though objects are different, their content is same.
String strObj1 = new String("test"); String strObj2 = new String("test"); Assertions.assertFalse(strObj1 == strObj2); Assertions.assertTrue(strObj2.equals(strObj2));