Null != obj Vs obj != Null

Whats is different between

if(obj != null) and if (null != obj)

only readability or ?

[105 byte] By [meqa] at [2007-11-27 10:43:20]
# 1

no difference

Maris_Orbidansa at 2007-7-28 19:59:46 > top of Java-index,Java Essentials,Java Programming...
# 2

Hey Maris! Long time no see, hope you are well.

cotton.ma at 2007-7-28 19:59:46 > top of Java-index,Java Essentials,Java Programming...
# 3

Some coders prefer to put the constant value (or in this case 'null') to the left-hand side in case they accidentally try an assignment rather than a test for equality:

if ( null = object) { // gives a compile-time error, rather than misbehaving at runtime

...

I don't normally bother though. I know a developer who will take the time to swap the variable and the constant around if he forgets. Hmmmm

georgemca at 2007-7-28 19:59:46 > top of Java-index,Java Essentials,Java Programming...
# 4

No difference.

It comes from C/C++, in order to turn typos on the programmer's part from runtime errors (harder to track down) to compile-time errors (easier to track down). If you did if (x = 5) (Note the single =) you could inadvertently assign 5 to x, but the compiler wouldn't let you do if (5 = x) because you can't set the value of the literal 5.

In Java, that's not necessary, because if (x = 5) won't compile.

There are only two cases where something like that matters in Java

if ("something".equals(theStr)) or if ("".equals(theStr))

Since the string literal inside "" is obviously not null, you can't get NullPointerException.

if (true == x)

Booleans are the only type where you can inadvertently assign with if (x = true). Flipping the order gives a compile time error, which is what you'd want. However, this is pointless, since you should never write if (x == true) or if (true == x). You should just write if (x).

As far as if (x == null), the "x == null" order is generally preferred, bcause it looks more natural that the value you're testing comes first. In normal English speech, "If x is null" "If the box is empty" etc.

jverda at 2007-7-28 19:59:46 > top of Java-index,Java Essentials,Java Programming...