When checking to see if a variable is null, I have seen that the suggested coding style is if(null == a)
. What is the difference between this and if(a == null)
?
There is absolutely no difference in either semantics or performance. The == in this case is a reference inequality operation; it can never throw NullPointerException .
@arvin_codeHunk, null is an empty object, whereas "null" is an actual string containing the characters 'n', 'u', 'l', and 'l'. The String here is written as null telling you that you just took the String value of null which is equal to "null" . So a null will not be equal to "null" literal. @arvin_codeHunk..
Use “==” to check a variable's value. If you set a variable to null with “=” then checking that the variable is equal to null would return true. variableName == null; You can also use “!=
out. println("(Object)string == number: " + ((Object)string == number)); To conclude this post and answer the titular question Does null equal null in Java? the answer is a simple yes.
There isn't any.
People will sometimes write null == a
for historical reasons, because it removes the possibility of a typo-related bug in C. If you were to write:
if (a = NULL) { // note, only single =
...
in C, then that would execute the assignment statement a = NULL
, with the statement's result being the value assigned (ie, NULL). Thus, rather than checking a
's value, you set it to be NULL and then checked essentially if (NULL)
, which is always false. This compiles, but is almost certainly not what you want. And it's all due to a small typo of =
vs ==
.
If you put the NULL
first, then if (NULL = a)
is a compilation error, since you can't assign a value to the constant that NULL represents.
In Java, there's no need for this, since if (null) {...
doesn't compile. (You can still have the same bug in Java with boolean variables: if (someBooleanVar = someMethod())
. But that's a relatively rare pattern.)
This style is sometimes referred to as "Yoda conditions," since it's reminiscent of Yoda's quirky speaking style in Star Wars.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With