}

Which is the proper way to compare strings in Java?

Created:

Introduction

With Java you can use the == operator to compare strings so. However,you could find that == could work in unexpected way and using .equals() will work as expected.

In this tutorial we will explain what is == operator, what's the difference and when you should use each of them.

Strings in java and in other lenguages are immutable. An object is immutable if can't change it or modify. Java programs contains a lot of string references and they are cached these instances can decrease the memory footprint and increase the performance of the program.

Reference equality

When using == operator for string comparison you are not comparing the contents of the string but are actually comparing the memory address, if they are both equal it will return true and false otherwise. This will bring confusion to beginner developers.

The operator == will test for reference equality, this means that it will check if they are the same object.

On the other side .equals() will tests for value equality, which will use information that the object has.

When you should use equals()?

Everytime you want to test whether if two strings have the same value you havr to use Objects.equals().

Example code:

The next code will return true:

new String("tutorials").equals("tutorials")

However the next code will return false since each argument is a different object.

object new String("tutorials") == "tutorials"

What could create confusion is the next line of code, which will return true:

"tutorials" == "tutorials"

The code above will return true since the it will refer to the same object, since literal are interned .

Be careful with nulls == handles null strings fine, but calling .equals() from a null string will cause an exception.

The next code will raise an exception:

String string1 = null; 
String string2 = null; 
string1.equals(string2); 

References

Objects.equals()