You are on page 1of 9

What is Static Variable in Java?

Static variable in Java is variable which belongs to the class and initialized only
once at the start of the execution.

A static variable is common to all the instances (or objects) of the class
because it is a class level variable. In other words you can say that only a
single copy of static variable is created and shared among all the instances of
the class. Memory allocation for such variables only happens once when the
class is loaded in the memory.
Like variables we can have static block, static method and static class, to read
about them refer:

 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>

Note: main method is static, since it must be accessible for an application to run,


before any instantiation takes place.

Static variable Syntax


static keyword followed by data type, followed by variable name.

static data_type variable_name;


As I mentioned above that the static variables are shared among all the
instances of the class, they are useful when we need to do memory
management. In some cases we want to have a common value for all the
instances like global variable then it is much better to declare them static as
this can save memory (because only single copy is created for static
variables).

lets understand this with an example:

Static variable example in Java


class VariableDemo
{
static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
Output:

Obj1: count is=2


Obj2: count is=2
As you can see in the above example that both the objects are sharing a
same copy of static variable that’s why they displayed the same value of
count.

Example 2: Static Variable can be accessed


directly in a static method
class JavaExample{
static int age;
static String name;
//This is a Static Method
static void disp(){
System.out.println("Age is: "+age);
System.out.println("Name is: "+name);
}
// This is also a static method
public static void main(String args[])
{
age = 30;
name = "Steve";
disp();
}
}
Output:

Age is: 30

Name is: Steve

Static variable initialization
1. Static variables are initialized when class is loaded.
2. Static variables are initialized before any object of that class is created.
3. Static variables are initialized before any static method of the class
executes.

Default values for static and non-static variables are same.


primitive integers(long, short etc): 0
primitive floating points(float, double): 0.0
boolean: false
object references: null

Static final variables


The static final variables are constants. Lets have a look at the code below:

public class MyClass{


public static final int MY_VAR=27;
}
Note: Constant variable name should be in Caps! you can use
underscore(_) between.
1) The above code will execute as soon as the class MyClass is loaded, before
static method is called and even before any static variable can be accessed.
2) The variable MY_VAR is public which means any class can use it. It is
a static variable so you won’t need any object of class in order to access it.
It’s final so the value of this variable can never be changed in the current or in
any class.

Key points:
final variable always needs initialization, if you don’t initialize it would throw a
compilation error. have a look at below example-

public class MyClass{


public static final int MY_VAR;
}
Error: variable MY_VAR might not have been initialized

Purpose
The static keyword in Java is mainly used for memory management. The
static keyword in Java is used to share the same variable or method of a
given class. The users can apply static keywords with variables, methods,
blocks, and nested classes. The static keyword belongs to the class than an
instance of the class. The static keyword is used for a constant variable or a
method that is the same for every instance of a class.

Example of static method


// Java program to demonstrate that a static member
// can be accessed before instantiating a class

class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}

public static void main(String[] args)


{
// calling m1 without creating
// any object of class Test
m1();
}
}

Output : from m1
Another Example of static block and variable

// Java program to demonstrate use of static blocks

class Test
{
// static variable
static int a = 10;
static int b;

// static block
static {
System.out.println("Static block initialized.");
b = a * 4;
}

public static void main(String[] args)


{
System.out.println("from main");
System.out.println("Value of a : "+a);
System.out.println("Value of b : "+b);
}
}
Output
Static block initialized.
from main
Value of a : 10
Value of b : 40
What is Static Method in Java?
Static method in Java is a method which belongs to the class and not to the
object. A static method can access only static data.

 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
 A static method cannot refer to "this" or "super" keywords in anyway

Syntax :

<class-name>.<method-name>

Example: How to call static variables & methods

Step 1) Copy the following code into a editor

public class Demo{


public static void main(String args[]){
Student s1 = new Student();
s1.showData();
Student s2 = new Student();
s2.showData();
//Student.b++;
//s1.showData();
}
}

class Student {
int a; //initialized to zero
static int b; //initialized to zero only when class is loaded not for each object
created.
Student(){
//Constructor incrementing static variable b
b++;
}

public void showData(){


System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
//public static void increment(){
//a++;
//}

Step 2) Save & Compile the code. Run the code as, java Demo.

Step 3) Expected output show below

Following diagram shows, how reference variables & objects are created and
static variables are accessed by the different instances.
Step 4) It is possible to access a static variable from outside the class using the
syntax ClassName.Variable_Name. Uncomment line # 7 & 8 . Save , Compile &
Run . Observe the output.

Value of a = 0
Value of b = 1
Value of a = 0
Value of b = 2
Value of a = 0
Value of b = 3
Step 5) Uncomment line 25,26 & 27 . Save , Compile & Run.

error: non-static variable a cannot be referenced from a static context


a++;

Step 6) Error = ? This is because it is not possible to access instance variable "a"
from java static class method "increment".

Java Static Block


The static block is a block of statement inside a Java class that will be executed
when a class is first loaded into the JVM
class Test{
static {
//Code goes here
}
}

A static block helps to initialize the static data members, just like
constructors help to initialize instance members

Following program is the example of java static block.

Example: How to access static block

public class Demo {


static int a;
static int b;
static {
a = 10;
b = 20;
}
public static void main(String args[]) {

System.out.println("Value of a = " + a);


System.out.println("Value of b = " + b);

}
}

you will get following output of the program.

Value of a = 10
Value of b = 20

You might also like