Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Object class have static block?

I want to just know about why Object,String etc. have static{} block at the end.what is the use of static block in Object Class.

Open the cmd prompt and type

javap java.lang.Object

enter image description here

like image 706
MUSTKEEM MANSURI Avatar asked Feb 05 '16 17:02

MUSTKEEM MANSURI


1 Answers

What you are looking at is just all the method and field declarations. Since the static block is somewhat like a method, you will just see the empty declaration of a static-initalizer.

If you look at the OpenJDK source code for java.lang.Object on line 40, the code actually says this

public class Object {

     private static native void registerNatives();
     static {
         registerNatives();
     }

A simple explanation of the static block is that the block only gets called once, no matter how many objects of the type you create.


If you want more information from the command line, javap -verbose java.lang.Object outputs this

  static {};
    descriptor: ()V
    flags: ACC_STATIC
    Code:
      stack=0, locals=0, args_size=0
         0: invokestatic  #16                 // Method registerNatives:()V
         3: return
      LineNumberTable:
        line 41: 0
        line 42: 3
}

Or, less verbose javap -c java.lang.Object

  static {};
    Code:
       0: invokestatic  #16                 // Method registerNatives:()V
       3: return

If you want to read about what registerNatives() does, you can read this post.

What does the registerNatives() method do?

like image 76
OneCricketeer Avatar answered Oct 16 '22 23:10

OneCricketeer