What is the difference in comparison?

Possible duplicate:
Zero check in Java

I'm just wondering what's the difference between

if (null == something) {...}

and

if (something == null) {...}

assuming that in both cases somethingis the same object. Presumably, it should not be, except for reading the code.

+1
source share
4 answers

There is no difference.

The idea of ​​placing a constant first helps protect against inadvertent assignment in a state. For example, in some languages ​​you can say:

if (i = 42) {
    ...
}

i is assigned, and the condition is true. If you did not want to do this, there are no compiler errors, and it can be difficult to find.

If you instead always set the constant first:

if (42 == i) {
    ...
}

Then the day you accidentally do:

if (42 = i) {
    ...
}

, .

+6

.

equals, null .

if( "A".equals(someString) ) { ... }

null, , someString null.

if( someString.equals("A") ) { ... }

, , someString null.

+7
+3

.

= ==.

if (true = something) {...}

,

if (something = true) {...}

does not accept if somethingis a boolean variable.

0
source

All Articles