InterviewSolution
| 1. |
What Happens If You Compare An Object To Null Using Equals()? |
|
Answer» When a null object is passed as an argument to equals() method, it should return false, it must not throw NullPointerException, but if you call equals method on REFERENCE, which is null it will throw NullPointerException. That’s why it’s better to use == operator for COMPARING null e.g. if(object != null) object.equals(anohterObject). By the WAY, if you comparing STRING literal with another String object then you better call equals() method on the String literal rather than known object to AVOID NPE, one of those simple tricks to avoid NullPointerException in Java. When a null object is passed as an argument to equals() method, it should return false, it must not throw NullPointerException, but if you call equals method on reference, which is null it will throw NullPointerException. That’s why it’s better to use == operator for comparing null e.g. if(object != null) object.equals(anohterObject). By the way, if you comparing String literal with another String object then you better call equals() method on the String literal rather than known object to avoid NPE, one of those simple tricks to avoid NullPointerException in Java. |
|