Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null == foo versus foo == null [duplicate]

Tags:

java

null

This may just be a style question, but I'm reading a Java coding book ('Programming Android') and the writer all declares null first before a variable method, a practice I am not familiar with. For example:

if (null == foo) {
    //code here
}

or

if (null != foo) {
    //code here
}

instead of

if (foo == null) {
    //code here
}

I can't see how the order would make a difference semantically/syntactically, or am I wrong here? Really just curious.

like image 631
FugueWeb Avatar asked Nov 29 '22 15:11

FugueWeb


2 Answers

It's probably a habit left over from C/C++. In C, you would put constants on the left, because if you mistyped = instead of == there would be an error because you can't assign something to a constant. In Java, this is unnecessary because if (foo = null) also gives an error, which says that an object reference isn't a boolean.

like image 121
tbodt Avatar answered Dec 05 '22 13:12

tbodt


This is a holdover from C/C++. It was advantages to put the value on the left of the == operator in case you accidently used the assignment = operator. The C compiler will catch the 14 = var as an error, but var = 14 will compile, when you meant to type var == 14. There is not much reason to do this in Java, but some still do it.

like image 25
DrA Avatar answered Dec 05 '22 11:12

DrA