Monday, 20 July 2015

Static blocks

Static blocks

static block/clause which can be used for static initializations of a class.
The code inside static block is executed only once when you load the class first time (creating object or static variable initialization).

Develop an application which runs only on Windows if user is using operating system operating system then the application will terminates.

Check what operating system is installed on user machine?

We are using getenv() method of System class which returns value of environment variable name of which is passed an as argument to it. Windows_NT is a family of operating systems which includes Windows XP, Vista, 7, 8 and others.


public class StaticBlock {
     public StaticBlock(String contructor) {
           System.out.println(contructor);
     }

     /**
      * static context will share for all object.
      * Once assigned a value will same for all objects.
      */
     static String window;

     static {
           String os = System.getenv("OS");
           if(os.equals("Windows_NT") == true) {
                System.out.println("Windows_NT");
                window = "window Windows_NT";
           }
     }

     public void show() {
           System.out.println(window);
     }
}
public class TestStaticBlock {
     public static void main(String[] args) {
           StaticBlock block = newStaticBlock("Contructor 1!!");
           StaticBlock block1 = newStaticBlock("Contructor 2!!");
           block.show();
           block1.show();
     }
}

Output :
     Windows_NT
     Contructor 1!!
     Contructor 2!!
     window Windows_NT
     window Windows_NT



Keys:
static variable can only use in static block.

static block execute only once while our class is loaded.

static blocks are executed before constructors.

static block can be used to check conditions before execution of main begin.

1 comment:

  1. When we want to execute static block before making the decision object should create or not..
    StaticClass.class.newInstance(); this is more preferebal
    Over StaticClass staticClass=new StaticClass();

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...