Wednesday, 27 March 2013

Static Keyword in Java

The static keyword can be used in 3 scenarios -
  • static variables
  • static methods
  • static blocks

static keyword in General

There are some things that must immediately come to our mind when we speak of static keyword. First of all a resource defined as static belongs to class as a whole rather that individual objects of the class. These resources are loaded when the class is loaded by the JVM unlike non-static case where memory is allocated only when we create an object of the class.

static variables

  •  Java instance variables are given separate memory for storage. If there is a need for a variable to be common to all the objects of a single java class, then the static modifier should be used in the variable declaration.
  • It is a variable which belongs to the class and not to object(instance).
  • Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables.
  • A single copy to be shared by all instances of the class.
  •  A static variable can be accessed directly by the class name and doesn’t need any object.
  • Syntax : <class-name>.<variable-name>
  • Any java object that belongs to that class can modify its static variables.

static methods

  • It is a method which belongs to the class and not to the object(instance).  
  • A static method can access only static data. It can not access non-static data (instance variables)
  • A static method can call only other static methods and can not call a non-static method from it
  • A static method can be accessed directly by the class name and doesn’t need any object.
  • Syntax : <class-name>.<method-name>.
  • A static method cannot refer to “this” or “super” keywords in anyway.

Example code on static variables and methods

Code for class  StaticDemo.java -

package greetings;

public class StaticDemo {

    private int a;// initialized to zero
    static int b;// initialized to zero only when class is loaded not for each
                    // object created.

    public StaticDemo() {
        b++;// Constructor incrementing static variable b
    }

    public void displayData() {
        System.out.println("Value of a = " + a);
        System.out.println("Value of b = " + b);

    }

}
Code for class TestStaticDemo.java -
package greetings;

public class TestStaticDemo {

    public static void main(String args[]) {
        System.out
                .println("Value of the static variable b before object creation is "
                        + StaticDemo.b);

        StaticDemo s1 = new StaticDemo();
        System.out.println("Printing data on object creation \n");
        s1.displayData();
    }
}


Output



Understanding the code

       Let understand our StaticDemo class first. We have defined two variables a and b. a is static while b is non static which means a belongs to the whole StaticDemo class as a whole. It is initialized to 0 (default value) right when the class is loaded by the JVM. Hence in the output we can see its value as 0 even before we have created any object of the class.Next we have the constructor which increments the value of our static variable b. So now when we create an object s1 of the class our static variable b whose value is 0 is incremented by one so new the value of b for each object that will be created will be 1.
    Again as we know a is an instance variable it is initialized to default values( 0 in case of int). So we can see it's value as 0 in the output. So when we create an object and print the values of our variables we get a = 0 and b = 1. TestStaticDemo is just to run the program and the code is self explanatory. Just review the way we access a static variable(and is same how we access a static function).

Note :  It is perfectly legal to access a static variable using class object but is not recommended because it destroys the very purpose of defining a variable as static. To restrict anyone from modifying our static variables we can define our variable as final  eg private final static int a. Note convention and access levels of access modifiers are still applicable.

To get the clear picture of how static keyword works refer to the following image - 


static block

  • The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM.
  • A static block helps to initialize the static data members, just like constructors help to initialize instance members.

Example for static block usage

public class Greetings
{
    static {
       //code goes here
     }
}
t> UA-39527780-1 back to top