Field initialization with null vs is not initialized: what's the difference?
I wonder if there is any difference between assigning a value null
to a field or not assigning it.
Let's compile a simple class (using javac or ecj):
public class Test {
Object obj;
}
Now let's look at its bytecode:
$ javap -c Test.class
Compiled from "Test.java"
public class Test {
java.lang.Object obj;
public Test();
Code:
0: aload_0
1: invokespecial #10 // Method java/lang/Object."<init>":()V
4: return
}
Now let's initialize the field:
public class Test {
Object obj = null;
}
Now the body of the constructor looks different:
Compiled from "Test.java"
public class Test {
java.lang.Object obj;
public Test();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: aconst_null
6: putfield #2 // Field obj:Ljava/lang/Object;
9: return
}
Both compilers don't just ignore initialization, they add an explicit constructor aconst_null/putfield
to the constructor. So my question is, could this addition have any runtime consequences? Can I distinguish at runtime if the object field has been initialized to null
or not initialized at all? If not, why can't compilers just ignore this initialization?
source to share
No one has answered this question yet
See similar questions:
or similar: