Static variable in java

In the last post, we have discussed the static keyword in java. A static keyword can be used with variable, block, method, and class. In this post, we will discuss the static variable in java. Most of us already knew some things about static, but to get more clarity we will discuss it in detail.

Here is the table content of the article will we will cover this topic.
1. What is the static variable?
2. Properties of static variable?
3. How to declare a static variable?
4. How to access the static variable?
5. How to use a static variable with example?
6. How does the static variable work?

What is a static variable?

When we use a static keyword with a variable it is called a static variable in java. When we declare a variable with static keyword the JVM loads it during the class loading. A static variable is known as a class variable also because the static variable belongs to class instead of the instance/objects. It means a static variable is common to all the objects of the class.
I know you must hear this line thousands of times, but I will tell you what the mean of the above line is.
Each non-static variable belongs to an object. It means when we create an object, a copy of non-static members stored in memory and associated with the object. It means each object has its own non-static variables. That is called variable is belongs to the object.
But a static variable doesn’t belong to an object. It means when we create an object, the static variable doesn’t store with object memory and it stores in a static pool. The static variable associated with class, that means each object shares the same variable from a single memory location.

Properties of static variable

A static variable in java has some unique proprieties that make it different from another variable. A static variable totally differs from other variables. To get more clarity we need to understand all the properties of the static variables.

1. Static variable memory

A static variable always stores in the static pool. It is the memory area that stores the static variables only. As you know static variables belong to a class, so these variables are common for each object that why they are stored in the separate memory pools.

2. Initialization of static variable

The Initialization of the static field totally different from other fields. When JVM loads the class, it loads all the Static variables and initialized them. It means when a class gets executed the static variable is also initialized at the same time. When a class gets destroyed the static variable is also destroyed at the same time. Initialization of Static Variable is not Mandatory. Its default value is depending on the data type of variable.

3. static variable belongs to class

The static variable associated with class rather than instance/object. A static member doesn’t create a separate copy for each instance. It is shared for all the instances because it is stored in a static pool which common for each instance.

4. Common for all objects

As you know static variable stores in the static pool and the static pool are accessible by each object. A static variable is common for all the objects, it is not associated with objects. Unlike the instance variable is doesn’t create a copy for each object. If any object makes a change in the value of a static variable, then it will reflect for all objects

5. Scope

You can’t declare a static variable within the method, a block of code, constructor. because the static variable always binds with the class. It should be declared on class level because JVM binds it at the time of class loading.

6. Access of static variable

A static variable is accessible by the class name. Unlike instance variables, we don’t need to create an object to access them. If we access the static variable through an object the compiler will show the warning message. The compiler will replace the object name to the class name automatically.

How to declare it?

We can declare a static variable by use of the static keyword. When we declare a variable with the static keyword, the static keyword indicates the JVM to load it when the class will be load. You can initialize it at the time of declaration but if you don’t initialize it the JVM provides it default value according to the data type.

static dataType variableName = value; 

static is a reserved word or keyword in java.
datatype is the type of data that you want to be stored in a variable.
variableName is the name of the variable.
Value you can provide the value to a static variable.

How to access it?

To access a static variable we don’t need to create an object. The static variable can directly access the class name.

ClassName.variableName

ClassName, the name of the class in which the static variable is declared.
.(dot), is used to access to variable through class name.
variableName, the name of the static variable which you want to access.

How to use a static variable with example

Let’s see how we can declare a static variable and how we can access it. We will declare some static variable.

public class StaticVariableExample 
{
	// Declaring static variable 
	static int a;
	static int b = 1;
	static String s;
	static String s1 = "Hi";
	
    public static void main(String[] args) 
    {
    	// Access of static variable by class name
    	System.out.println("Value of a : "+ StaticVariableExample.a);
    	System.out.println("Value of b : "+StaticVariableExample.b);
    	System.out.println("Value of s : "+StaticVariableExample.s);
    	System.out.println("Value of s1 : "+StaticVariableExample.s1);
    }    
}

How does the static variable work?

A static variable in Java is common to all the objects of the class. Because the static variable is associated with a class. When a static variable is loaded in memory (static pool) it creates only a single copy of static variable and shared among all the objects of the class. Memory allocation of variables only happens once when the class is loaded in the memory.
If you made any changes in the value of a variable by any object, then it will be reflected in other objects also. We will discuss this by scenario.

Example: Let’s take an example. The user wants to count how many numbers of objects are calling the same function.

Firstly, we will discuss without static

class ExampleWithoutStatic
{
	int numberOfClick = 0;
	
	public void incrementCountAndPrint()
	{
		numberOfClick++;
		System.out.println("Value of count = " +numberOfClick );
	}

	public static void main(String args[])
	{
		ExampleWithoutStatic object1 = new ExampleWithoutStatic();
		object1.incrementCountAndPrint();
		
		ExampleWithoutStatic object2 = new ExampleWithoutStatic();
		object2.incrementCountAndPrint();
		
		ExampleWithoutStatic object3 = new ExampleWithoutStatic();
		object3.incrementCountAndPrint();
	}
}

Output:
Value of count = 1
Value of count = 1
Value of count = 1

Memory presentation:

We declared an instance/class variable count. Each object creates(Objects always created in heap memory) its own copy in memory. When we called the incrementCountAndPrint() method by object1 then it increments the value of count. But it doesn’t make any change in other object’s value. So, when we called the same method by object2 it makes changes its own memory.

Now, we will discuss it with a static variable

public class ExampleWithStatic
{
	static int numberOfClick = 0;
	
	public void incrementCountAndPrint()
	{
		numberOfClick++;
		System.out.println("Value of count = " +numberOfClick );
	}

	public static void main(String args[])
	{
		ExampleWithStatic object1 = new ExampleWithStatic();
		object1.incrementCountAndPrint();
		
		ExampleWithStatic object2 = new ExampleWithStatic();
		object2.incrementCountAndPrint();
		
		ExampleWithStatic object3 = new ExampleWithStatic();
		object3.incrementCountAndPrint();
	}
}

Output: Value of count = 1
Value of count = 2
Value of count = 3

Memory presentation:

static variable in Java

We declared a static variable count. The static variable always stored in a static pool. Each object shares the variable from a static pool. When we called the incrementCountAndPrint() method by object1 then it increments the value of count and stored in the static pool. Now, object2 will access the incremented value of count. So, when we called the same method by object2 it will increment the value again.

7 thoughts on “Static variable in java”

  1. Thanks java Goal .I found the best website.I have cleared my all doubts .This website provide best content .
    very impressive and you are doing great job.

    Reply
  2. Hi,
    Can you share with me an example for the below point.
    6. Access of static variable

    A static variable can direct class by use of the class. Unlike instance variables, we don’t need to create an object to access them. If we access the static variable through an object the compiler will show the warning message. The compiler will replace the object name to the class name automatically.

    Reply

Leave a Comment