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
- a.equals("hai")
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.