A static variable is one that’s associated with a class, not objects of that class.Static variable’s value is same for all the object(or instances) of the class or in other words you can say that all instances(objects) of the same class share a single copy of static variables.
Below is the syntax to declare static variable
static int salary ;
To understand this further lets look at teh e.g. below
class Calculator { static int initialValue=0; public void Add() { initialValue++; } public static void main(String args[]) { //Create 2 new instance of calculatro class Calculator obj1=new Calculator(); Calculator obj2=new Calculator(); obj1.Add(); obj2.Add(); System.out.println("Obj1: count is=" + obj1.initialValue); System.out.println("Obj2: count is=" + obj2.initialValue); } }
Output
Obj1: count is=2
Obj2: count is=2
As you can see in the above example that both the objects of class, are sharing a same copy of static variable that’s why they displayed the same value
I am learning java, This tutorial is very good for high school students who shy away from learning computer language.
It took me couple of iteration to understand this post. Thanks!!!!
1
Tricky concept, I would appreciate if you can share more use cases for static variable.
Superb!!!!!!!