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.
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.
Open the
HelloJava.javafile in the WebIDE editor if it's not already open.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, andstr3. str1andstr2are created using string literals. Java often optimizes string literals so that identical literals refer to the same object.str3is created using thenew 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.
- We declare three string variables:
Save the file (Ctrl+S or Cmd+S).
Now, let's compile our program. Open the Terminal at the bottom of the WebIDE and make sure you are in the
~/projectdirectory. Run the following command:javac StringComparison.javaIf the compilation is successful, you will see no output. A
StringComparison.classfile will be created in the~/projectdirectory.Finally, run the compiled program using the
javacommand:java StringComparisonYou 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 ==: falseNotice that
str1.equals(str2)andstr1.equals(str3)both returntruebecause the content of the strings is the same. However,str1 == str3returnsfalsebecausestr1andstr3refer to different string objects in memory, even though they contain the same characters.str1 == str2returnstruein 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.
Open the
StringComparison.javafile in the WebIDE editor.Modify the
mainmethod to include anullstring: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
nullstringstr4. - We commented out the lines that would cause a
NullPointerExceptionif 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 callingequals()on is notnullbefore calling the method. A common pattern is(stringVariable != null && stringVariable.equals(anotherString)). Alternatively, you can callequals()on the known non-null string if possible, like"hello".equals(str4).
- We added a
Save the file (Ctrl+S or Cmd+S).
Compile the modified program in the Terminal:
javac StringComparison.javaRun the compiled program:
java StringComparisonYou 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: trueThe output shows that the safe comparisons correctly handle the
nullstring without causing an error. The comparison betweenstr1andstr4(which is null) correctly evaluates tofalse.
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().
Open the
StringComparison.javafile in the WebIDE editor.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
str5andstr6with different casing. - We added new print statements to demonstrate the difference between
equals()andequalsIgnoreCase(). - We also show that calling
equalsIgnoreCase()on a non-null string with anullargument does not cause an error, similar toequals(). However, callingequalsIgnoreCase()on anullstring variable will still result in aNullPointerException.
- We added
Save the file (Ctrl+S or Cmd+S).
Compile the program in the Terminal:
javac StringComparison.javaRun the compiled program:
java StringComparisonYou 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(): falseThe output clearly shows that
equalsIgnoreCase()returnstruewhen comparing strings with the same characters but different casing, whileequals()returnsfalse.
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.



