Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

obj == null vs null == obj

Tags:

java

oop

I have always used to check for null like

if(null==obj)

When I compiled my code and looked into .class file after decompiling, I could see that my code got changed to

if(obj==null)

I know in java null==obj and obj==nulldoesn't matter. But I'm curious to know why compiler changed it?

like image 733
bajji Avatar asked Dec 07 '17 18:12

bajji


1 Answers

The compiler did not change anything. It faithfully compiled if (null == obj) and if (obj == null) into different bytecodes, which decompilers converted back to the same Java code.

Comparison with null on the right, i.e.

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

gets translated to this byte code with ifnonnull instruction:

0: aload_0
1: ifnonnull     ...

Comparison with null on the left, i.e.

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

gets translated to a different bytecode with if_acmpne instruction:

0: aconst_null
1: aload_0
2: if_acmpne     ...

In theory, decompiler has enough information to figure out which way the arguments are ordered in the source file. However, they produced the same code for both orderings.

like image 72
Sergey Kalinichenko Avatar answered Oct 21 '22 04:10

Sergey Kalinichenko