Static Variables in Java Programming
OOPs in Java
In this lesson, we will understand what are Static Variables in Java Programming and how to create them along with some examples.
What are Static Variables in Java?
When we declare a variable with the static keyword, it is called Static Variable. It is declared in a class. The memory for the static variable is allocated only once when the class is loading in the memory.
When a static variable is declared in a class, it is shared between all the objects of that class. We can access a static variable from outside its class using its class name and a dot (.) operator.
Example
class Data
{
// creating instance variables
public String name;
public int age;
public static int count;
// Default Constructor
Data()
{
name="Thomas";
age=18;
count=count+1;
}
// Parameterized Constrcutor
Data(String name, int age)
{
this.name=name;
this.age=age;
count=count+1;
}
}
public class Example
{
public static void main(String args[])
{
// Creating an object x and y of the class Data
Data x = new Data();
Data y = new Data("William", 14);
System.out.println("Total number of objects created = " + Data.count);
}
}
Output
Total number of objects created = 2
In the above example, we created a class Data with two instance variables (name, age) and one static variable, count. In the default and parameterized constructors, we increment the static variable count by 1.
In the main method, we create two objects, x and y, which invoke the default and the parameterized constructors when running the program. As a result, the static variable count is incremented by 1 twice. So the total number of objects created is 2.