Generally, when we create a class, we don't know anything until we create an object of that class using the new keyword. Once the object is created at that time, data storage is created and methods become available.

If we need a method that is not associated with any particular object of the class and can call even if no objects are created. In this case, we can achieve both with the help of static keyword in Java programming.

When we declare variable or method as static, it means that the variable or method is not tied to any particular object of that class rather than to individual object or instance. In this chapter, we will learn static keyword in java, purpose of using static modifier, static variable with practical example programs.

Static Keyword in Java

In Java, static is a keyword that is used for memory management mainly. Static means single copy storage for variables or methods. The members that are declared with the static keyword in the class are called static members in java. 

These members can be accessed even if no instance of the class exists because static members are not tied to a particular instance. They are shared across all the instances of the class.

Points to remember:

1. Static keyword in Java can be applied with variables, methods, inner classes, and blocks. 
2. You cannot declare a class with static but the inner class can be declared as the static.
3. It belongs to the class than the instance of the class.

4. One basic rule of working with static keyword is that we cannot directly call instance members within the static area because the static members are linked with the class and they get memory once when the class is loaded but Instance members get the memory after the object creation of the class.

Therefore, when we call any instance members within the static area, it means that when the class is loaded into the memory, the static members also loaded into the memory and it will look the instance members that are not in existence because we have not created any object till now. Hence, there is an ambiguity.

For example:
    public class SaticTest { private int a=10; // Instance field. public static void main(String[] args) { int b=a; // error: won't compile. } }
Here, main method is static. So, we cannot access the instance variable a. However, we can access static methods or fields from the instance method.

What is use of Static Keyword in Java?

1. The purpose of using static keyword in Java programming is that we can access the data, method or block of the class without any object creation. Let's understand it with a simple example. 

As you know that the main method is static in Java because the object is not required to call the static method. If it is a non-static method then the JVM will create an object first and then it will call the main() method which creates the problem of an extra memory location.
2. It is used to make the programs more memory efficient.

Static Variable (Class variable) in Java with Example

If you declare any variable with a static modifier, it is known as a static variable. A static variable is also known as class variable.

Declaration of Static Variable in Java

The declaration of static variable is as follows:
           Access_ modifier  static variable_name;
For example:
1. static int num;  // Default access modifier.   
2. private static int age; // Private access modifier.

When we declare an instance variable in java, a separate copy will be created for every object but in the case of a static variable, a single copy is created at the class level and shared by all objects of that class.

Key point:
A local variable cannot be declared as static. JVM will display modifier error at compile time.

How to access Static variable in Java?

There are two ways to access the static variable in Java. They are as follows:
1. A static variable can be accessed in any other class using the class name.
For example:
         A.x; // A is the class name and "x " is a static variable declared in that class.

2. Static variables can also be accessed by the object reference but an instance variable can only be accessed by the object reference.
For example:
We have a class named Student. We can create the object of the Student class like this;
    Student s=new Student();
Let us create a program where we will declare a variable as static and access it by using class name and object reference variable.
Program source code 1:
    package staticVariable; public class Student { // Declare a static variable id having data type int and assign it the value 20. static int id=20; public static void main(String[] args) { // Create an object of the class Student. Student s=new Student(); // Call static variable using object reference variable s and store it by variable x with data type int. int; // Print on the console. System.out.println(x); // Now Call static variable id using the class name. System.out.println(; } }
    Output: 20 20
As you can see in the above program, we printed the value of id by using object reference and by using the class name.

Static variable initialization in Java

The following important points have to keep in mind about static variable initialization in Java. They are:
1. When a class is loaded into the memory at runtime, the static variable is created and initialized into the memory only once. In other words, it gets loaded into the memory at the time of class loading. 
2. Static variables in a class are initialized before the creation of any instance of that class.

3. Static variables in a class are initialized before the execution of any static method of the class. Therefore, we cannot initialize the static variable inside the static method.
4. If any object changes the value of the static variable, it will retain its value and increments by 1 for every object creation.

Let's create a program where we will initialize a static variable x is equal to 0 and increment static variable by 1 for each object creation.
Program source code 2:
    package staticVariable; public class Counter { static int x=0; // It will get memory only once and retain its value. Counter(){ x++; // It will increment the static variable by 1 for each object creation. } void display(){ System.out.println(x); } public static void main(String[] args) { Counter c1=new Counter(); c1.display(); Counter c2=new Counter(); c2.display(); Counter c3=new Counter(); c3.display(); } }
    Output: 1 2 3
Explanation with diagram:
Static variable in java
When the above code will be executed, the static variable x will set to zero when the class is first loaded in the memory by the JVM before any counter instances are created. When a counter instance is created, the counter constructor executes and increment the static variable by 1 and the result is 1.

When the second object is created, counter constructor again executes and increment the static variable by 1. Now the result is 2.  Similarly, when the third object is created, the result will be 3.

Now imagine what would happen in the above program if x is a instance variable i.e non-static variable. In this case, still it will create three counter objects in the main(), but the result will be a compile-time error.

Uses of Static variable in Java with Example

The most common use of a static variable in a class is to hold predefined constant or unchanging values that are the same for all the instances of the class and will never change during the execution of the program. Let's understand the concept by a practical example program.
Program source code 3:
    package staticVariable; public class Employee { // Declare instance variables. String name; int id; // Declare a static variable companyName with data type String and assign value IBM which is common for all the objects. static String companyName="IBM"; // Declare a two-parameter constructor with parameters named n and i. Employee(String n, int i){ name=n; id=i; } // Declare an instance method display and print the output on the console. void display() { System.out.println("Name: "+name+ " " +"Id= "+id+ " " +"Company Name:"+ " " +companyName); } public static void main(String[] args) { // Create the first object of the class and pass the two arguments with type string and int. Employee e=new Employee("Shubh", 123); // Call the display method using reference variable e. e.display(); // Similarly, create the second object of the class and pass the two arguments. Employee e1=new Employee("Deep", 321); e1.display(); } }

    Output: Name: Shubh Id= 123 Company Name: IBM Name: Deep Id= 321 Company Name: IBM
In this example, companyName refers to the "common property" of all the objects because companyName is a static variable and it will get memory only once.

Can we access instance member from static area directly?

Instance member (non-static member) can be accessed only from instance area directly but we cannot access it from the static area directly. In other words, we cannot call instance member from the static member because static variable stores into the memory before the object creation and instance variable stores into the memory after the object creation.

So, when we access instance members by static members as they are not present in the memory, it will give the compile-time error.

Can we access static variable from instance method and static method?

Yes, static member (static variable) can be accessed from both instance and static area (i.e. instance and static methods) directly using the class name or without the class name but outside the class, we can call only using class name only.
Let's make a program where we will access static variable from both instance and static method.
Program source code 4:
    package staticVariable; public class Test { // Instance area int a=10; //Instance variables. static int b=30; // S.V. // Declare an instance method. void m1() { // We can call instance variable directly from instance area without any object reference variable. System.out.println(a); // Call the static variable directly from instance area. System.out.println(b); } static void m2(){ // Static area. // We cannot call instance member from static area. System.out.println(a); // Here, compile time error because at this time, the object of the class is not created. so we cannot call the instance variable using object reference variable. } public static void main(String[] args){ // Static area. Test t=new Test(); // Object creation. t.m1(); // Here, we can call instance member using object reference variable t in the static area. System.out.println(t.a); m2(); } }
    Output: 10 30 10 Compile time error

How to access static variable in Java from another class?

You can access static variables in Java by using class name from another class. Let's take an example program related to this concept.

Program source code 5: 
In this example, we will declare static variables in a class Calculation and will call in another class CalculationTest using the class name. After that, we will perform a simple addition and subtraction operation and print output on the console. 
    package staticVariable; public class Calculation { static int x=20; static int y=30; }
    public class CalculationTest { void addition() { // Call S.V. using class name. int a=Calculation.x; // Since the returning value is integer, we will store it by using a variable a of type int. int b=Calculation.y; int c=a+b; System.out.println(c); } void subtraction() { int p=Calculation.x; int q=Calculation.y; int r=p-q; System.out.println(r); } public static void main(String[] args) { CalculationTest ct=new CalculationTest(); ct.addition(); ct.subtraction(); } }
    Output: 50 -10

How to change the value of static variable in Java?

You can change the value of the static variable in Java by using a constructor and static block but not inside a static method. Let's make a program and change value of static variable from constructor, static block, static and instance methods.
Program source code 6:
    package staticVariable; public class Demo { static int a=20; static int b=50; static int c=100; Demo() { a=3; // Changed value of variable. } static { b=10; } void m1() { System.out.println(a); System.out.println(b); System.out.println(c); // It will print 100. } static void m2() { c=200; } void m3() { c=200; } public static void main(String[] args) { Demo d=new Demo(); d.m1(); } }
    Output: 3 10 100

Advantage of Static variable in Java

Class variable makes program memory efficient. i.e It saves memory. All the static variables are stored in PermGen space of the heap memory.

Difference between Static variable and Instance variable

There are the following differences between static variable (class variable) and instance variable.
1. A static variable is also known as class variable whereas Instance variable is also known as non-static variable.

2. Class variable can be accessed inside the static block, instance block, static method, instance method, and method of the inner class whereas Instance variable can be accessed inside the instance block, instance method, and method of the inner class.

3. Class variable is always resolved during compile time whereas Instance variable is resolved during the runtime.
4. They are not serialized in Java whereas Instance variables are serialized in Java.

Final words
Hope that this tutorial has covered almost all the important points and topics related to the Static variable in Java with practical example programs. I hope that you will have understood this tutorial and enjoyed programming.
Thanks for reading! Next ➤ Static Method in Java ⏪ Prev Next ⏩