1

Does this code get called for every object creation in Java, because every object extends Object ? Or does the JVM optimize it in some way to avoid the creation of some many Object's object in the heap.

What exactly happens in this method registerNatives().

package java.lang;  

public class Object {
  private static native void registerNatives();
  static {
    registerNatives();
  }
sij
  • 296
  • 3
  • 13
  • This code won't compile. –  Jul 27 '12 at 09:54
  • :) No, not my code. This is copied from Jdk source code. – sij Jul 27 '12 at 09:55
  • 1
    possible duplicate of http://stackoverflow.com/questions/335311/static-initializer-in-java – Alonso Dominguez Jul 27 '12 at 09:56
  • 1
    You seem to be confusing things. The static block will be run the first time an object of type Object (strictly, excluding subclasses) will be loaded by the JVM. But it will NOT be run if another type is loaded, even if it extends Object. – assylias Jul 27 '12 at 10:02

3 Answers3

2

Static blocks are only executed once, when the class is loaded.

As explained here or here, a block that will be executed every time an object of the class is initialized can also be defined : just remove the static keyword.

Community
  • 1
  • 1
Autar
  • 1,589
  • 2
  • 25
  • 36
1

It does n't matter what registerNatives(). does. What does matter here is that you have enclosed it in static block. Static Blocks loaded and run when java Class Loader loads classes. So it is guaranteed to run exactly once per JVM.

Ahmad
  • 2,110
  • 5
  • 26
  • 36
0

1. The question here is not about Constructor chaining, but about static.

2. static variable will be initialized when the JVM loads the class, and JVM loads the class when the class is instantiated or any static method of that class is called.

3. So this static block will run every one time the JVM loads the class.

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75