Since equals is a built-in method in java, we need to make sure that it must be called with an object that does not have zero. so in case we call with null, we end up with a null pointer exception.
Example: suppose I need to check if the string a is "hai" and a is equal to the user.
then I'm not sure if "a" will be null or not. therefore, if I use a.equals("hai")
, then it is unsafe if a becomes null, but if you change the comparison, then it is always safe, whether it is null or not.
therefore always prefer "hai".equals(a)
be safe from null pointer exceptions.
source share