In Java I am told that when doing a null check one should use == instead of .equals(). What are the reasons for this?
◎위챗 : speedseoul
http://stackoverflow.com/questions/4501061/java-null-check-why-use-instead-of-equals
13 4 | |
add comment |
25 | They're two completely different things. For instance:
| ||||||||||||||||
|
8 | if you invoke So it is always advisble to check nullity before invoking method where ever it applies
Also See | ||||||||||||||||
|
2 | In Java 0 or null are simple types and not objects. The method equals() is not built for simple types. Simple types can be matched with ==. | ||||
|
1 | You could always do
This will first check the object reference and then check the object itself providing the reference isnt null. | ||||||||
|
0 | If an Object variable is null, one cannot call an equals() method upon it, thus an object reference check of null is proper. | ||
add comment |
0 |
What happens if foo is null? You get a NullPointerException. | ||
add comment |
0 | If you try calling equals on a null object reference, then you'll get a null pointer exception thrown. | ||
add comment |
0 | Because equal is a function derived from Object class, this function compares items of the class. if you use it with null it will return false cause cause class content is not null. In addition == compares reference to an object. | ||
add comment |
0 | According to sources it doesn't matter what to use for default method implementation:
But you can't be sure about |
equals()
and see. When you try it will instantly be obvious – Goran Jovic Dec 21 '10 at 15:50