Best way to compare 2 strings

Since equals is a built in method in java , we need to make sure that it should be called with object not with null. so in case if we call with null then we will endup with Null pointer exception.

Ex : assume i need to check whether string a is equal to “hai” and variable ‘a’ is coming from user.

then i am not sure whether ‘a’ will be null or not. so if i use

  1.  a.equals("hai")

then its not safe if a becomes null but if you reverse the comparison then it is always safe no matter a is null or not.

so always prefer “hai”.equals(a) to be safe from null pointer exception.

About the Author

Founder of
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to

Connect with me on Facebook for more updates

Share this article on