There are a few ways we can use to compare Strings in Java:
- Using the equals() method from the String class
- Using the == operator
- Using the static equals() method from the Objects class
- Using the equalsIgnoreCase() method from the String class
Let’s explore each of them.
1. Using equals() method from the String class to compare Strings in Java
The equals() method from the String class checks for value equality. It tests if both Strings contain the same literal value.
We need first to check for null to avoid the NullPointerException. For more information on handling exceptions, check out our tutorial on Exception Handling in Java.
Example
public class Test { public static void main(String[] args) { String str1 = "Hello"; String str2 = "Hello"; String str3 = null; if (str1 != null) { System.out.println(str1.equals(str2)); } System.out.println(str1.equals(str3)); } }
2. Using the == operator to compare Strings in Java
Using the == operator, we can test for reference equality (whether the Strings are the same object). This is useful if we create Strings using the new keyword instead of assigning the literal value.
Example
Let’s create two Strings with the new keyword and test the equality using the == operator and the equals() method.
public class Test { public static void main(String[] args) { String str1 = new String("Hello"); // creating the first object String str2 = new String("Hello"); // creating the second object System.out.println(str1 == str2); System.out.println(str1.equals(str2)); } }
3. Using the static equals() method from the Objects class
The Objects.equals() is a null safe method. If both parameters are null, true will be returned. If the first argument is not null, equality is determined by calling its equals() method with the second argument provided. Otherwise, false will be returned.
Example
import java.util.Objects; public class Test { public static void main(String[] args) { String str1 = "java"; String str2 = new String("java"); System.out.println(Objects.equals(str1, str2)); System.out.println(Objects.equals(null, str1)); System.out.println(Objects.equals(null, null)); } }
4. Using the equalsIgnoreCase() method from the String class
If we need to ignore the cases, we can use the equalsIgnoreCase() method from the String class.
Example
public class Test { public static void main(String[] args) { String str1 = "strings"; String str2 = "StriNgS"; System.out.println(str1.equals(str2)); // regular equals() method System.out.println(str1.equalsIgnoreCase(str2)); // ignoring case considerations } }