(a! = null) or (null! = a)

Is there a difference in comparing a variable with nullor comparing nullwith a variable?

For example, which comparison is better (a != null)or (null != a)? I read somewhere that the second is faster, but did not find a reason for this.

+5
source share
6 answers

No, no one works faster. It's a lie. There is no benefit from using the second version. Only a deterioration in readability.

It all came from C, where you could have mistakenly written

if(x = 3) 

instead

if( x == 3)

, , , = ==, .

if(3 == x)

, , , , . , .

+25

, , 99,99% . , , - . if (a != null) - .

+9

.

if("abcd".equals(name)) NPE, if(name.equals("abcd")) , name null.

+4

:

( a = null ) //will not give error

( null = a ) //will give error

, , , .

+3

, , .

0

Actually, not in java, anyway. in older times, maybe C, you may accidentally forget the exclamation mark, and the code will compile fine. basically a = nullaccepted as an expression that assigns a null value for aand is always evaluated as true (since the assignment was successful).

Compilers are much more reliable today. Although old habits die, and I'm still writing null != a: -)

0
source

All Articles