0

since static variable got memory at the time of class loading,here I am assigning it by creating new A(),which will assign at run time after loading the class.How jvm assign value of new A() at the time of class loading?

public class A{
static A objA =new A();
public static void main(String x[]){}
}
1
  • i suggest you to read Inside jvm by bill venners Commented Apr 9, 2015 at 10:55

2 Answers 2

2

When a class is loaded, the JVM calls a method in the class called <clinit>()V This method sets all initial values and in your case, it sets the static field.

It can create instances while the method is being called, but it does mean you can't assume in a constructor that all the static fields have been set if you do this.

Sign up to request clarification or add additional context in comments.

1 Comment

Example showing this behavior ideone.com/N3lyW7 (when class is loaded its fields are set at first to their default values and then are initialized from top to bottom).
2

There's nothing strange here. The class is loaded, then new A() is created and assigned to objA. How it actually happens internally is not really relevant, and may vary between JVMs.

5 Comments

Since static variable share common memory area among several object of same class,so static variable got memory once for several object. one more point object are created later not at time of class loading how jvm can assign it at the time of class loading?
@ArpitDubey - Not class loading. The class is already loaded. static fields are assigned values / initialized during class initialization. So the class definition is already there in the JVM / method area.
@TheLostMind thanks man. Your mean static variable got memory at the time of class loading but, they initialized at the time of initialisation then jvm picked code from method area.
@ArpitDubey - No. Class loading means - what the class should contain and meta data is added to the method area. Class initialization means -static fields are initialized.
@TheLostMind I get confused, please specify which code is going in i)-method area ii)-Heap memory iii)-stack

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.