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?

+3
java jvm bytecode javac


source to share


No one has answered this question yet

See similar questions:

18
Default variable values โ€‹โ€‹versus default initialization

or similar:

3805
Avoidance! = Null
3545
Differences between HashMap and Hashtable?
2956
What is the difference between public, secure, batch and private in Java?
2583
Initializing an array in one line
1915
How do I declare and initialize an array in Java?
1873
What's the difference between @Component, @Repository and @Service annotations in Spring?
1823
What's the easiest way to print a Java array?
1498
Difference between StringBuilder and StringBuffer
636
What's the difference between JPA and Hibernate?
341
Create the perfect JPA object



All Articles
Loading...
X
Show
Funny
Dev
Pics