Saturday, May 19, 2012

Static variables vs Static Block vs Static Methods



Static variables

All the static variables are shared by all the instances, which are global variables.Hence the variable or method which we need to declare as global can be declared as static.
below is the syntax for declaring a member as static.
static int width=30;
static int length=20;

Static Block   

static{} block is executed when the class which contain static block is loaded into memory. 
i.e before the main method is called static block is used for Initialization of static members.
static{} block is not inside any method and this block will get executed only once while loading the class.

Example :

public class StaticExample {

 static{
  System.out.println("Hello");
 }
 
 public static void main(String args[]){
  
 }
}

When we run this program it will print Hello.















Static Methods

They are executed when those methods are called from another static class or method


They methods which can be invoked without creating the object of the class.
Common error while using static method:
If we try to refer any method or variable which are not static from the static  method, we will get compilation error .

static() has several restrictions:
1. Can ONLY call other static ()
2. MUST ONLY access static data
3. cant refer to super or this

Example :

public class StaticExample {

 static void printString(){
  System.out.println("Hello");
 }
 
 static void testStaticMethod(){
  printString();
 }
 
 public static void main(String args[]){
  testStaticMethod();
 }
}




Order of execution of Staic variable ,static block and  static method

As soon as the class is loaded, all of the static statements will run first .then the static block will execute.
Consider the below code to understand this much more clearly.

public class StaticTest { 
static int width=30;
static int length=20;
static void myMethod(int x)
{
System.out.println(“Value passed is = ” + x);
System.out.println(“Width = ” + width);
System.out.println(“Length = ” + length);
}
static
{
int area;
System.out.println(“Static block initialized.”);
area = width* length;
System.out.println(“Area is “+area);
}
public static void main(String args[]) {
myMethod(60);
}
}
Output of the above code is
Static block initialized.
Area is 600
Value passed is = 60
Width = 30
Length = 20


No comments:

Post a Comment