Understanding Static in Java - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Understanding Static in Java

Share This

In Java static keyword is used in many places. The use of static keyword is discussed in this tutorial with some example.

Static Instance Variables

If an instance variable is declared as static, only once the space is allocated in memory, even if multiple instances are created of that class. The static variables are shared by the objects of the class. Moreover, static variables are not allocated at the time of instance creation. The memory for the static variable is allocated at the time of class loading. Thus static variables can be accessed by the class name, instead of object.

When the value of a static variable is updated, the updated value is reflected everywhere.


public class A { int x; static int s = 0; }

public class Test { public static void main(String[] args) { // As 's' is a static variable, it can be accessed by class name System.out.println(A.s); // Similarly, the value of 's' can be set A.s = 10; System.out.println(A.s); // Though a new object is being created, the value of 's' remains same. // It is not being set to 0 (zero) A a1 = new A(); System.out.println(A.s); // a static variable can also be accessed by object reference a1.s = 20; System.out.println(A.s); A a2 = new A(); System.out.println(a2.s); } }


Static Methods


In the similarway, memory for a static method is also allocated at the time of class loading. Thus static methods can be called without creating an instance of the class. Thus, static methods are accessible by the class name.

A static method can deal with static variables (class level) only.



public class A { int x; static int s = 0; public static void print() { // System.out.println(x); // non-static variable can not be accessed in static method System.out.println(s); } }

public class Test { public static void main(String[] args) { A.print(); A a = new A(); a.print(); } }


Static Block


Java supports static block, which is nothing but a code block written in a class (not in method). This block is executed at the time of class loading. As a class is loaded in JVM once, the block is executed once.

Thus, a static block is executed even before calling a static method.



package test; public class A { static { System.out.println("I am in static block."); } public static void print() { System.out.println("I am in print."); } }

public class Test { public static void main(String[] args) { A.print(); } }


Happy Exploring!

No comments:

Post a Comment