How to Check If a String Equals Another String in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to effectively compare strings in Java. Understanding string comparison is fundamental for various programming tasks. We will explore the standard equals() method for checking if two strings have the same character sequence, even if they are different objects in memory.

Furthermore, you will learn how to handle potential NullPointerException issues when comparing strings that might be null. Finally, we will cover the equalsIgnoreCase() method, which allows you to perform case-insensitive string comparisons, providing flexibility when the case of characters doesn't matter for your comparison logic.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/StringManipulationGroup -.-> java/strings("Strings") java/SystemandDataProcessingGroup -.-> java/string_methods("String Methods") subgraph Lab Skills java/strings -.-> lab-559983{{"How to Check If a String Equals Another String in Java"}} java/string_methods -.-> lab-559983{{"How to Check If a String Equals Another String in Java"}} end

Compare Strings Using equals() Method

In this step, we will learn how to compare strings in Java using the equals() method. Comparing strings is a fundamental operation in programming, and understanding how to do it correctly is crucial.

In Java, strings are objects, not primitive data types like integers or booleans. This means that when you compare strings, you are comparing the objects themselves, not just their values. Using the == operator to compare strings checks if the two string variables refer to the same object in memory. However, often you want to check if two strings have the same sequence of characters, even if they are different objects. For this, you should use the equals() method.

Let's create a simple Java program to demonstrate this.

  1. Open the HelloJava.java file in the WebIDE editor if it's not already open.

  2. Replace the entire contents of the file with the following code:

    public class StringComparison {
        public static void main(String[] args) {
            String str1 = "hello";
            String str2 = "hello";
            String str3 = new String("hello");
    
            System.out.println("Comparing str1 and str2 using equals(): " + str1.equals(str2));
            System.out.println("Comparing str1 and str3 using equals(): " + str1.equals(str3));
            System.out.println("Comparing str1 and str2 using ==: " + (str1 == str2));
            System.out.println("Comparing str1 and str3 using ==: " + (str1 == str3));
        }
    }

    In this code:

    • We declare three string variables: str1, str2, and str3.
    • str1 and str2 are created using string literals. Java often optimizes string literals so that identical literals refer to the same object.
    • str3 is created using the new String() constructor, which explicitly creates a new string object in memory, even if its content is the same as existing literals.
    • We use equals() to compare the content of the strings.
    • We use == to compare if the string variables refer to the same object.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Now, let's compile our program. Open the Terminal at the bottom of the WebIDE and make sure you are in the ~/project directory. Run the following command:

    javac StringComparison.java

    If the compilation is successful, you will see no output. A StringComparison.class file will be created in the ~/project directory.

  5. Finally, run the compiled program using the java command:

    java StringComparison

    You should see output similar to this:

    Comparing str1 and str2 using equals(): true
    Comparing str1 and str3 using equals(): true
    Comparing str1 and str2 using ==: true
    Comparing str1 and str3 using ==: false

    Notice that str1.equals(str2) and str1.equals(str3) both return true because the content of the strings is the same. However, str1 == str3 returns false because str1 and str3 refer to different string objects in memory, even though they contain the same characters. str1 == str2 returns true in this specific case due to string literal optimization, but relying on == for string comparison is generally discouraged as it can lead to unexpected results.

This demonstrates why using the equals() method is the correct way to compare the content of strings in Java.

Handle Null Strings in Equality Check

In this step, we will explore how to handle null strings when performing equality checks in Java. A null string means that the string variable does not refer to any object. Attempting to call a method on a null variable will result in a NullPointerException, which is a common error in Java.

When comparing strings, it's important to consider the possibility that one or both of the strings might be null. If you call the equals() method on a null string, your program will crash.

Let's modify our previous program to see how this works and how to handle it safely.

  1. Open the StringComparison.java file in the WebIDE editor.

  2. Modify the main method to include a null string:

    public class StringComparison {
        public static void main(String[] args) {
            String str1 = "hello";
            String str2 = "hello";
            String str3 = new String("hello");
            String str4 = null; // This string is null
    
            System.out.println("Comparing str1 and str2 using equals(): " + str1.equals(str2));
            System.out.println("Comparing str1 and str3 using equals(): " + str1.equals(str3));
            System.out.println("Comparing str1 and str2 using ==: " + (str1 == str2));
            System.out.println("Comparing str1 and str3 using ==: " + (str1 == str3));
    
            // Let's try comparing with the null string
            // System.out.println("Comparing str1 and str4 using equals(): " + str1.equals(str4)); // This line would cause a NullPointerException
            // System.out.println("Comparing str4 and str1 using equals(): " + str4.equals(str1)); // This line would also cause a NullPointerException
    
            // Correct way to compare when one string might be null
            System.out.println("Comparing str1 and str4 safely: " + (str1 != null && str1.equals(str4)));
            System.out.println("Comparing str4 and str1 safely: " + (str4 != null && str4.equals(str1)));
            System.out.println("Comparing str4 and null safely: " + (str4 == null));
        }
    }

    In the modified code:

    • We added a null string str4.
    • We commented out the lines that would cause a NullPointerException if executed.
    • We added examples of how to safely compare strings when one might be null. The safest way is to check if the string you are calling equals() on is not null before calling the method. A common pattern is (stringVariable != null && stringVariable.equals(anotherString)). Alternatively, you can call equals() on the known non-null string if possible, like "hello".equals(str4).
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac StringComparison.java
  5. Run the compiled program:

    java StringComparison

    You should see output similar to this:

    Comparing str1 and str2 using equals(): true
    Comparing str1 and str3 using equals(): true
    Comparing str1 and str2 using ==: true
    Comparing str1 and str3 using ==: false
    Comparing str1 and str4 safely: false
    Comparing str4 and str1 safely: false
    Comparing str4 and null safely: true

    The output shows that the safe comparisons correctly handle the null string without causing an error. The comparison between str1 and str4 (which is null) correctly evaluates to false.

This step highlights the importance of handling null values when working with objects in Java, especially strings, to prevent NullPointerException errors.

Use equalsIgnoreCase() for Case-Insensitive Comparison

In this final step, we will learn about the equalsIgnoreCase() method, which is used to compare strings without considering the case of the characters. This is very useful when you want to check if two strings are the same regardless of whether the letters are uppercase or lowercase.

The equals() method we used in the previous steps performs a case-sensitive comparison. This means "hello" is not equal to "Hello" when using equals(). The equalsIgnoreCase() method ignores the case, so "hello" and "Hello" would be considered equal.

Let's modify our program one last time to demonstrate equalsIgnoreCase().

  1. Open the StringComparison.java file in the WebIDE editor.

  2. Add some new string variables with different casing and use equalsIgnoreCase() to compare them:

    public class StringComparison {
        public static void main(String[] args) {
            String str1 = "hello";
            String str2 = "hello";
            String str3 = new String("hello");
            String str4 = null;
            String str5 = "Hello"; // Different casing
            String str6 = "HELLO"; // All uppercase
    
            System.out.println("Comparing str1 and str2 using equals(): " + str1.equals(str2));
            System.out.println("Comparing str1 and str3 using equals(): " + str1.equals(str3));
            System.out.println("Comparing str1 and str2 using ==: " + (str1 == str2));
            System.out.println("Comparing str1 and str3 using ==: " + (str1 == str3));
    
            // Safe comparison with null
            System.out.println("Comparing str1 and str4 safely: " + (str1 != null && str1.equals(str4)));
            System.out.println("Comparing str4 and str1 safely: " + (str4 != null && str4.equals(str1)));
            System.out.println("Comparing str4 and null safely: " + (str4 == null));
    
            System.out.println("\n--- Case-Insensitive Comparisons ---");
            System.out.println("Comparing str1 and str5 using equals(): " + str1.equals(str5));
            System.out.println("Comparing str1 and str5 using equalsIgnoreCase(): " + str1.equalsIgnoreCase(str5));
            System.out.println("Comparing str1 and str6 using equalsIgnoreCase(): " + str1.equalsIgnoreCase(str6));
            System.out.println("Comparing str5 and str6 using equalsIgnoreCase(): " + str5.equalsIgnoreCase(str6));
    
            // equalsIgnoreCase() also handles null safely if called on a non-null string
            System.out.println("Comparing str1 and str4 using equalsIgnoreCase(): " + str1.equalsIgnoreCase(str4));
            // System.out.println("Comparing str4 and str1 using equalsIgnoreCase(): " + str4.equalsIgnoreCase(str1)); // This would still cause a NullPointerException
        }
    }

    In the updated code:

    • We added str5 and str6 with different casing.
    • We added new print statements to demonstrate the difference between equals() and equalsIgnoreCase().
    • We also show that calling equalsIgnoreCase() on a non-null string with a null argument does not cause an error, similar to equals(). However, calling equalsIgnoreCase() on a null string variable will still result in a NullPointerException.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the program in the Terminal:

    javac StringComparison.java
  5. Run the compiled program:

    java StringComparison

    You should see output similar to this:

    Comparing str1 and str2 using equals(): true
    Comparing str1 and str3 using equals(): true
    Comparing str1 and str2 using ==: true
    Comparing str1 and str3 using ==: false
    Comparing str1 and str4 safely: false
    Comparing str4 and str1 safely: false
    Comparing str4 and null safely: true
    
    --- Case-Insensitive Comparisons ---
    Comparing str1 and str5 using equals(): false
    Comparing str1 and str5 using equalsIgnoreCase(): true
    Comparing str1 and str6 using equalsIgnoreCase(): true
    Comparing str5 and str6 using equalsIgnoreCase(): true
    Comparing str1 and str4 using equalsIgnoreCase(): false

    The output clearly shows that equalsIgnoreCase() returns true when comparing strings with the same characters but different casing, while equals() returns false.

You have now learned how to compare strings in Java using equals() for case-sensitive comparison, how to handle null strings safely, and how to use equalsIgnoreCase() for case-insensitive comparison. These are essential skills for working with strings in Java.

Summary

In this lab, we learned how to compare strings in Java. We started by understanding the difference between comparing string objects using the == operator and comparing their content using the equals() method. We saw that == checks for object identity, while equals() checks for character sequence equality.

We then explored how to handle potential NullPointerException when comparing strings by ensuring the string on which equals() is called is not null. Finally, we learned how to perform case-insensitive string comparisons using the equalsIgnoreCase() method.