How to Compare Strings in Java Correctly?

How to Compare Strings in Java Correctly?, I know many of you are using == to compares two strings in Java.Well, the == is correct.In ==, reference equality will be matched.Means that, it is checking that, they are same objects or not.
We have to use the .equals() for actually matching the values. .equals(), value equality will be matched.Means that,it is checking that, they are logically equal or not.
To Compare Strings in Java Correctly, we can use either of them, as per the situations.
ALso,if you want to check whether two strings have the same value, Objects.equals() is the one you are looking for.

That comes to an conclusion.You can,almost and always want to use Objects.equals().And when you are dealing with interned strings you can use “==”.
Hope,that helps.

Leave a Comment

Your email address will not be published. Required fields are marked *