Static Variable in Java

Let’s see the Application of Static Variable in Java. Static variables are variable which belongs to the class and not to object (Instance of the class). Some facts about Static variables –

  • Static variables are initialized only once.
  • A single copy of Static Variables shared by all the instance of the class i.e Static variable value same for all the instance of the class.
  • A static variable can be accessed without the reference of the class. You can access the static variables using the class name.
  • Static variables are initialized when the class is loaded.
  • Static variables in a class are initialized before any static method of the class runs.


Application of Static Variable in Java

All instances of the same class share the same value of the static variables. Let’s understand this with an easy and simple example-


Value with first object is 12
Value with second object is 12


Video Tutorial in Automation Testing:


Static final Variable

Static final variables are Constants in Java. The static final variable is load with the class before the static method is called. The static final variable must be initialized otherwise the compiler will throw an error.

If you are not initializing the variable at the time of declaration then variable must be initialized in the constructor of the class.

0 Comment

Leave a Reply