6

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

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

1 Answers1

9

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?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • I believe this should be added to the javap command description. Doc says "When no options are used, then the javap command prints the package, protected and public fields, and methods of the classes passed to it. The javap command prints its output to stdout." http://docs.oracle.com/javase/8/docs/technotes/tools/windows/javap.html or are they implied in one of the items above? – uncaught_exception Feb 05 '16 at 17:41
  • @ShireResident - A static block is package-private scope defined, I believe. (Since there is no public/private/protected modifier on it) – OneCricketeer Feb 05 '16 at 17:43
  • I was actually focussed more on the "fields" and "methods". I didn't think static block was considered one of those. – uncaught_exception Feb 05 '16 at 17:46
  • @ShireResident - not sure I understand. A static block is like a method that runs once when the class is initialized. There are no fields in java.lang.Object – OneCricketeer Feb 05 '16 at 17:49
  • I was just asking with respect to the terminology because the Oracle docs are usually very specific - just to bolster my understanding. Methods https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4 are defined separately to "static block" https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.7 but then so are constructors. – uncaught_exception Feb 05 '16 at 17:56