Static Blocks Static Initialization

Static Blocks Static Initialization


Generally, a Java programmer initializes variables in a constructor (or init() method in case of applet). It is the best place chosen, as the constructor is called implicitly when an object is created. Programmer creates objects before anything is done in coding (as object is required to call an instance variable or method). Now read on Static Blocks.

In the place of a constructor, a static block can be chosen, if the programmer does not like to have a constructor. One more advantage is static block is executed even before main() method is executed. That is, Java execution starts from static blocks and not from main() method.

Three programs are given on static blocks; each differ slightly.

In the following program, the instance variables are static. As they are static, they called from main() without the help of an object.

After executing static block, main() is executed. Observe the screenshot.

The previous program can be modified where instance variables are not static. Then you require an object to call them from static main() method.

Multi Static Blocks

A program can have any number of static blocks.

Observe, purposefully, the main() method is not included in the program. Even then, the program compiles and runs as static blocks are called before main(). Look at the screenshot, the main() is checked by the JVM after calling all static blocks. As the main() is not available, an exception is thrown.

JDK 1.7 Modifications

From JDK 1.7, main() method is required to execute static block. Anyhow, static block is called before main() is executed.

Learn more on static Keyword – Philosophy.

22 thoughts on “Static Blocks Static Initialization

  1. Surya

    public class StaticClass
    {

    String name;
    int rollno;
    static int height = 56;
    static StaticClass s1;

    static
    {

    System.out.println(“Am static block am called first “);

    s1.name = “naresh”;
    s1.rollno = 16;
    System.out.println(height);

    }

    public static void main(String[] args)
    {

    System.out.println(“am main() method called after static block”);
    System.out.println(“above defined values are :” +s1.name + “” +s1.rollno);

    }
    }

    sir,

    i have declared everything correctly but it is showing me the error as Exception in initialiserError caused by NullpointerException.Could u please explain why???

    1. S. Nageswara Rao, Corporate Trainer Post author

      public class StaticClass
      {
      String name=””;
      int rollno;
      static int height = 56;

      static StaticClass s1 = new StaticClass();
      static
      {

      System.out.println(“Am static block am called first “);

      s1.name = “naresh”;
      s1.rollno = 16;
      System.out.println(height);
      }
      public static void main(String[] args)
      {
      System.out.println(“am main() method called after static block”);
      System.out.println(“above defined values are :” +s1.name + ” ” +s1.rollno);
      }
      }
      Do the code as above. You have not instantiated s1.

    2. sagar

      //Hey Surya try this..

      public class StaticClass
      {

      static String name;
      static int rollno;
      static int height = 56;
      static StaticClass s1;
      static
      {
      System.out.println(“Am static block am called first”);
      s1.name = “Naresh”;
      s1.rollno = 16;
      System.out.println(height);
      }
      public static void main(String args[])
      {
      System.out.println(“am main() method called after Satic block”);
      System.out.println(“above defined values are :” +s1.name + ” ” +s1.rollno);
      }
      }

  2. Jitendra Pandey

    advantage of static block it will execute before main method it means it loads when class is loaded. But from 1.7 VERSION of jdk onward Java people done some changes in JVM it will strictly searching for “public static void main(String[] args)” until and unless you do not provide main method it is not going to execute any code.

  3. pRaDeeP

    class Demo
    { static
    { System.out.println(“hiii”);
    }
    }

    this code will not be executed in jdk1.7.0 and it will executed if u use version below 1.7

  4. sandeep

    Actually sir , I have confused in jvm and jre .javac command is used to generate the bytecode i.e. .class file. and java command is used to run that .class file. According to me , jvm generate the bytecode and jre used to run that byte code(according to me ) .when we run the jar file.Actually jar file is a collection of .class file .To run the jar file we need only jre .but when jar file run using java command then which find/search for the main method “jre or jvm”. please give me reply as soon as possible .

  5. vikas

    thank u sir by the way ur site is superb i havent seen before this type of website .you touch the nerve of java students. the language you used over here is so simple that even a 5th standard student can understand it.
    i want to congratulate you and thank you for making this site .

    i dont know about others but i am regularly studying through this website seriusly if you open your classes in delhi then i would b the first one who will join you.

  6. vikas

    actually i have problm in static block whenever i am trying to run static block without main its every time show me the Error: Main method not found in class abc, please define the main method as: public static void main(String[] args)

    i m using jdk 1.7.0

    this same is happening with your program as well
    please tell me the reason why its not running in my pc

      1. vikas

        thanks sir for your reply,
        sir but here it is even not executing static block and giving error message
        i was tying this program
        class Demo
        {
        static
        {
        System.out.println(“hiii”);
        }
        }

        here the result that i was expecting is……..hiii with an exception that main not found

        but i was getting an error which i told you but no such display (hiii)

          1. vikas

            sir this is not the problm actually i find my ans. This progrm is easily running in jdk 5 means its displaying

            hiii
            Exception in thread “main” java.lang.NoSuchMethodError: main

            but in jdk 6 and 7 its not running means its showing

            Error: Main method not found in class abc, please define the main method as: public static void main(String[] args)

            sir you can also check out this

Leave a Reply

Your email address will not be published. Required fields are marked *