obj == null vs null == obj

bajji :

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?

dasblinkenlight :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=439630&siteId=1