Static Variable in Java

(Last Updated On: March 17, 2019)

Learn Static variables in java with example and how it is different than non-static variables of a class in java programming. For better understanding, we will use static and non static (instance variables) both in example.

STATIC VARIABLES

A static variable is shared by all objects of the class. Meaning, static variable has only copy and all objects know this copy. Whereas, this is not the case with instance variables(non-static).

All objects have their own copy of instance variables and they don’t share the value of instance variables to other objects.

 

Lets understand static variables by example.

Consider a simple example, that show how static variable and non-static variable also known as instance variable are declared in a class.

In below Student class, numberOfStudentEnrolled is static and String variable “name” is non-static and known as instance variable.

 

Static variable has only one copy in the memory and all objects of the class share the same copy.

Non- static or instance variable has their own separate copy in the memory and is not shared between different objects.

For example,

If you create objects of the class in java as below.

Student peter = new Student(“Peter”);
Student john = new Student(“John”);
Student linda = new Student(“Linda”);

All students Peter, John and Linda objects are in different memory on the heap and have their own copy of “String name” variable. So, in every memory, name is unique and not sharable to each other.

Whereas the static variable “static int numberOfStudentEnrolled is seen by all the objects peter, john and linda. Means, all objects will see the same value of numberOfStudentEnrolled.

 

“Static variable is seen by all objects whereas no object can see value of others instance variable”

NOTES:

  • Static variables can be accessed by both non static method and static method in java program .
  • Instance variable can be accessed by only non static method.
  • Static method can access only static variable.

 

Example of Static Variable in Java

In below java example, Static variable numberOfStudentEnrolled is incremented in constructor by 1. When ever you create an object of the class student, then it will be increased by 1 automatically.

name and roll number is supplied at the time of creating an object.

You can notice that all name and roll number are unique as all objects resides in different memory.

if you fetch value of numberOfStudentEnrolled using any object, then you will see the updated value of this static variable as all objects are sharing this variable.

 

Output:
Name :Peter
Roll Number :123
Name :John
Roll Number :234
Name :Linda
Roll Number :345
Total Enrolled Student :3