Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 'a == null' and 'null == a'

Tags:

java

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)?

like image 411
Raysen Jia Avatar asked Feb 18 '15 21:02

Raysen Jia


People also ask

What is the difference between null == object and object == NULL in Java?

There is absolutely no difference in either semantics or performance. The == in this case is a reference inequality operation; it can never throw NullPointerException .

What is the difference between null and null?

@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..

Can you use == for null?

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 “!=

Is null and null same in Java?

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.


1 Answers

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.

like image 171
yshavit Avatar answered Oct 02 '22 19:10

yshavit