String equals and equalsIgnoreCase are used for comparing 2 Strings in java.Both these methods works exactly similar except for equalsIgnoreCase compares String ignoring case consideration.
example:
We have 2 String as defined below
1 2 |
String str1 = "This is Test String"; String str2 = "THIS IS TEST STRING"; |
Now using
str1.equals(str2) will result as “false”
But using
str1.equalsIgnoreCase(str2) will give us the output as “true”
Complete Example of String equals and equalsIgnoreCase
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.kscodes.sampleproject; public class StringEqualsExample { public static void main(String[] args) { String testStr1 = "This is Test String"; String testStr2 = "THIS IS TEST STRING"; String testStr3 = "This is Test String"; System.out.println("Comparing testStr1 and testStr2 using equals() :: " + testStr1.equals(testStr2)); System.out.println("Comparing testStr2 and testStr3 using equals() :: " + testStr2.equals(testStr3)); System.out.println("Comparing testStr1 and testStr3 using equals() :: " + testStr1.equals(testStr3)); System.out.println("-----------------------------------------------"); System.out.println("Comparing testStr1 and testStr2 using equalsIgnoreCase() :: " + testStr1.equalsIgnoreCase(testStr2)); System.out.println("Comparing testStr2 and testStr3 using equalsIgnoreCase() :: " + testStr2.equalsIgnoreCase(testStr3)); System.out.println("Comparing testStr1 and testStr3 using equalsIgnoreCase() :: " + testStr1.equalsIgnoreCase(testStr3)); } } |
Output
1 2 3 4 5 6 7 |
Comparing testStr1 and testStr2 using equals() :: false Comparing testStr2 and testStr3 using equals() :: false Comparing testStr1 and testStr3 using equals() :: true ----------------------------------------------- Comparing testStr1 and testStr2 using equalsIgnoreCase() :: true Comparing testStr2 and testStr3 using equalsIgnoreCase() :: true Comparing testStr1 and testStr3 using equalsIgnoreCase() :: true |
Please Note:
Both these methods can throw a NullPointerException if the String on which you are using these methods is NULL. So before performing any operation on String please check if the String is not null.
If one of the 2 Strings that you are going to compare is Static, then you should use the Static String to compare other String.
Example:
If str1 is a static String and str2 is going to be dynamic, then you should use
str1.equals(str2) to avoid NullPointer exception.
Both these methods can throw a NullPointerException if the String on which you are using these methods is NULL. So before performing any operation on String please check if the String is not null.
If one of the 2 Strings that you are going to compare is Static, then you should use the Static String to compare other String.
Example:
If str1 is a static String and str2 is going to be dynamic, then you should use
str1.equals(str2) to avoid NullPointer exception.