0

Can anyone explain jvm program execution of object in static and instance block?

how an object goes into stack and comes out?

30th Nov 2019, 7:05 PM
Ajoh Pv
Ajoh Pv - avatar
6 Réponses
+ 3
Static initializer blocks are executed at the time of class loading so they run before your main method. Instance initializer block inside a class is executed after the call to the super() from the constructor of the calling class. Also remember that static initializer block is executed only once whereas instance initializer block is executed every time an instance of the class is created. And an object is created in the heap memory and not in the stack. Generally all the local variables and function calls are stored in the stack.
30th Nov 2019, 7:36 PM
Avinesh
Avinesh - avatar
+ 2
zemiak I added a static and instance block inside the super class. https://code.sololearn.com/cEQxrfgwgdaZ/?ref=app
1st Dec 2019, 10:41 AM
Denise Roßberg
Denise Roßberg - avatar
+ 1
https://code.sololearn.com/cRKxAwr2rE6t/?ref=app
30th Nov 2019, 7:46 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
I added test to call super() before initializer block (and then constructor) class SuperExample { public SuperExample() { System.out.println("Super constructor"); } } class Example extends SuperExample { public Example() { System.out.println("Constructor\n"); } { System.out.println("Instance"); } static { System.out.println("Static"); } } class Program { public static void main(String[] args) { for(int i = 0; i < 5; i++){ Example e = new Example(); } } }
1st Dec 2019, 10:08 AM
zemiak
+ 1
Denise Roßberg Good example.
1st Dec 2019, 10:45 AM
Avinesh
Avinesh - avatar