DEV Community

Cover image for Java Tidbits: Compare your Strings wisely!
Abhinav Nath
Abhinav Nath

Posted on

Java Tidbits: Compare your Strings wisely!

Welcome to the first installment of Java Tidbits, a series where I share small and simple Java tips to help with day-to-day development and help developers avoid common mistakes.

Let's begin

In Java, string comparison is a fundamental task, yet it often leads to subtle bugs if not done correctly. A common mistake among both new and experienced Java developers is using the .equals() method improperly during String comparisons.

In this blog, we'll explore why "SOME_STRING".equals(someObj.getText()) is a safer and more reliable way of comparing strings than someObj.getText().equals("SOME_STRING").

Understanding .equals() in Java

The equals() method in Java is used to compare the content of two strings for equality. Unlike the == operator, which checks if two references point to the same object, .equals() compares the actual characters in the strings.

String str1 = new String("hello");
String str2 = new String("hello");

System.out.println(str1 == str2); // false
System.out.println(str1.equals(str2)); // true
Enter fullscreen mode Exit fullscreen mode

The Common Pitfall

A common pattern you might see is:

if (someObj.getText().equals("SOME_STRING")) {
    // do something
}
Enter fullscreen mode Exit fullscreen mode

At first glance, this seems perfectly fine. However, this approach has a hidden danger: if someObj.getText() returns null, it will throw a NullPointerException!

To avoid the risk of a NullPointerException, it is better to write the comparison as:

if ("SOME_STRING".equals(someObj.getText())) {
    // do something
}
Enter fullscreen mode Exit fullscreen mode

Here's why this is better:

  1. Null Safety: When "SOME_STRING" is a string literal, it is guaranteed to be non-null. Therefore, calling .equals() on it ensures that the method is always invoked on a valid object, even if someObj.getText() returns null. This prevents the dreaded NullPointerException.

  2. Readability and Intent: Writing "SOME_STRING".equals(someObj.getText()) makes it immediately clear that you are comparing a constant value against a variable value. This enhances readability and intent of the code.

  3. Consistency: Adopting this pattern consistently across your codebase helps in maintaining uniformity and reduces the chances of null-related bugs.

Conclusion

Both new and experienced developers can overlook this simple yet crucial detail. It's an easy mistake to make, especially when you're confident that the method (like someObj.getText()) won't return null.

Facing a NullPointerException because of this mistake can lead to the coding equivalent of slipping on a banana peel. It is an embarrassing stumble that can be easily avoided with a bit of defensive programming!


Support me if you liked this post

Top comments (0)