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) {

      * 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) {
                window = "window Windows_NT";

     public void show() {
public class TestStaticBlock {
     public static void main(String[] args) {
           StaticBlock block = new StaticBlock("Contructor 1!!");
           StaticBlock block1 = new StaticBlock("Contructor 2!!");

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

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();


Related Posts Plugin for WordPress, Blogger...