Sunday 9 February 2014

Static Blocks

static blocks are used to initialize static variables. Static blocks are executed when the class gets loaded by a class loader.
    Syntax
    static{

    }

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
Example
class Person{
 static int minSalary;
 
 static{
  minSalary = 10000;
 }
 
 public static void main(String args[]){
  System.out.println(Person.minSalary);
 }
}

Output
10000
 
Some points to remember
1. A class can have any number of static blocks
    Example
class Person{
 static int minSalary;
 static int maxSalary;
 static int minAge;

 static{
  minSalary = 10000;
  maxSalary = 100000;
 }

 static{
  minAge = 21;
 }

 public static void main(String args[]){
  System.out.println(Person.minSalary +"\t" + Person.maxSalary);
  System.out.println(Person.minAge);
 }
}

Output    
10000 100000
21
     

2. Static blocks are executed in the order they defined
     Example
class Person{
 static int minSalary;
 static int maxSalary;
 static int minAge;

 static{
  System.out.println("I am the first static Block");
 }

 static{
  System.out.println("I am the second static Block");
 }

 static{
  System.out.println("I am the third static Block");
 }

 public static void main(String args[]){
  System.out.println("I am in main method");
 }
}
      
Output
I am the first static Block
I am the second static Block
I am the third static Block
I am in main method

3. You can't initialize a instance variable in the static block
     Example
class Person{
 String name;
 
 static{
  name = "Krishna";
 }
}

When you try to compile the above code, compiler throws the below error
Person.java:4: error: non-static variable name cannot be referenced from a static context
name = "Krishna";
^
1 error 
  



Initializer Blocks                                                 this keyword                                                 Home

No comments:

Post a Comment