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();

s.x;

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 x = s.id; // Print on the console. System.out.println(x); // Now Call static variable id using the class name. System.out.println(Student.id); } }

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

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 Flow of execution of above program: 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 increments 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 an 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 members from static area directly?

Instance members (non-static members) 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 variables from instance method and static method?

Yes, static members (static variables) 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 variables 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 an 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 the value of static variables 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 variables 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.