Generally, when we create a class, we are describing how objects of that class look and how will they behave. 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. 

But 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. That is when you say something is static, it means that the data or method is not tied to any particular object of that class rather than to individual object or instance. Let's discuss the static keyword in more details.

What is Static in Java?

In Java, Static is a keyword which is used for memory management mainly. Static means single copy storage for variable or method. The members that are declared with the static keyword in the class can be accessed even if no instance of the class exist 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 variable, method, inner class, and block. 
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 the ambiguity. 

For example:
  public class Teststatic{
     private int a=10; // an 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 the static methods or fields from the instance method.

What is the purpose/use of static in Java?

1. The purpose of static keyword in Java is that we can access the data, method or block of the class without any object creation. Let's understand 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 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 in Java with Example

If you declare any variable with static modifier, it is known as a static variable. Static variable is also known as a class variable.
For example
     private static int age;

When you declare an instance variable, 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.
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 static variable in Java. They are as follows:
1. 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. A static variable can also be accessed by the object reference but an instance variable can only be accessed by the object reference. 
For example:
I have a class name as Student. Now we can create the object of the Student class.
    Student s=new Student();
Let's see a simple example program.
Program source code 1: 
    package staticvariable; public class Student { // Declare an static variable id with data type int and assign it the value 20. static int id=20; public static void main(String[] args) { // Create the object of the class Student Student s=new Student(); // Call the static variable using object reference variable s and store it by x variable with data type int. int; // Print on the console. System.out.println(x); // Now Call the 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

There are the following important points 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 see an example to understand the concept.
Program source code 3:
    package com.scientecheasy; 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(); } }
You can see the below image to understand the concept.

    Output: 1 2 3
When the above code executes, the static variable x is set to zero when the class is first loaded 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 instance of the class and will never change during the execution of the program. Let's understand the concept by a simple example program.
Program source code 2:
    package com.scientecheasy; public class Employee { // Declare instance variables. String name; int id; // Declare the 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
Static variable in Java.

Can we access the instance member from the static area directly?

➲ Instance member(non-static member) can be accessed only from instance area directly and we cannot access the static area directly. That is 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 member by static member as they are not present in the memory, it will give the compile-time error.

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

Yes, the Static member (static variable) can be accessed from both instance and the static area (instance and static method) directly using the class name or without the class name but outside the class, we can call only using the class name. 
Program source code 4:
    package com.scientecheasy; 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(); 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 the static variable in Java by using class name from another class. See the example program.
Program source code 5: In this example, we will declare the 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 com.scientecheasy; public class Calculation { static int x=20; static int y=30; }
    package com.scientecheasy; public class CalculationTest { void addition(){ // Call S.V. using class name. int a=Calculation.x; 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 using static method. Let's take a simple program to understand the concept.
Program source code 6:
    package staticvariable; public class Demo { static int a=20; static int b=50; static int c=100; Demo(){ a=3; } 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

It 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

1. A static variable is also known as class variable whereas Instance variable is also known as non-static variable.
2. It 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. It 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 article has covered all the important topics related to the Static variable in Java with practical example program. We hope that you have enjoyed this article.
Thanks for reading!

⏪ Prev Next ⏩