Luigi2405
Luigi2405

Reputation: 777

When the reference to an object is created in Java?

class myClass{
    public myClass(){
        // INITIALIZATION
    }
    ...
}
...
myClass a;
...
a = new myClass();

When does the reference to object a stop being null? As soon as the constructor is invoked or when it completes?

Upvotes: 0

Views: 96

Answers (3)

Alexander Pushkarev
Alexander Pushkarev

Reputation: 1145

In the line a = new myClass(); several things are happening:

  1. new myClass(); creates an instance of the new object. a would still be null at this point. Strictly speaking, it is not even a null, it is not initialized state.
  2. Assignment operator = assigns a a new value, which is a link to the object, created in step 1

So a has proper value only after the assignment is completed.

If you have a look at the bytecode, you can see that the actual assignment happens on line 13. Bytecode:

Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: new           #2                  // class a$MyClass
       7: dup
       8: aload_0
       9: aconst_null
      10: invokespecial #3                  // Method a$MyClass."<init>":(La;La$1;)V
      13: astore_1
      14: return

Upvotes: 1

Nexevis
Nexevis

Reputation: 4667

You can test this by using a static field to print out the value of the Object during the construction.

class Test {    
    public static Test t;
    
    public Test() {
        System.out.println(t);
    }
    
    public static void main(String[] args) 
    {
        t = new Test();
        System.out.println(t);
    }
}   

Output:

null

test.Test@7852e922

The output shows null from the print inside the constructor, because the static object t has not been assigned yet, but after completion of t = new Test() it appears that t has now been assigned.

Upvotes: 0

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

Declaring a variable in separate line is just a syntactic sugar and has no effect on the bytecode. The javac compiler will process your code the same way as myClass a = new myClass();.

Consider following example, added System.out as an example code:

myClass a;
System.out.println("b");
a = new myClass();

which produces following bytecode (javap -v Main.class):

    Code:
      stack=2, locals=2, args_size=1
         0: getstatic     #7                  // Field java/lang/System.out:Ljava/io/PrintStream;
         3: ldc           #13                 // String b
         5: invokevirtual #15                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
         8: new           #21                 // class myClass
        11: dup
        12: invokespecial #23                 // Method myClass."<init>":()V
        15: astore_1
        16: return

where System.out was executed before a was ever processed.

Upvotes: 0

Related Questions