Static Variable in Java (with Examples)

In this tutorial, we will learn about the static keyword, and static variable in Java with the help of various example programs. Generally, when we create a class in Java, we don’t know anything about its members until we create an object of that class using the new keyword.

Once the object of the class is created, memory is allocated for its variables, and its methods become accessible. However, sometimes, we need a method or variable that is not associated with any particular object of the class and can call even if no objects are created.

For this purpose, Java provides a static keyword which can fulfill both needs. When we declare a class member as static, it means that it is shared among all objects of the class. It belongs to the class itself rather than any instance.

In simple words, when you declare a class member as a static, it is not tied to any particular object of that class. It can be accessed before any objects of its class are created and without reference to any object.

We can declare methods, variables, and blocks to be static. The most common example of a static member inside a class is main() method. The main( ) method is declared as static because it must be called before any objects of the class exist.

The following topics will be covered one by one based on the static keyword in Java.

  • What is static keyword in Java?
  • Features of static keyword
  • Use of static keyword
  • Static variable (class variable) in Java
  • How to access static variable in Java?
  • Static variable initialization
  • Use of static variables
  • Can we access instance members from the static area directly?
  • Can we access static variables from instance and static methods?
  • How to access static variable in Java from another class?
  • Difference between static variable and instance variable.

What is Static Keyword in Java?


In Java, static is a keyword that is mainly used for memory management. It means that only a single copy storage for variables or methods per class is created and shared across all instances of the class.

The members that are declared with the static keyword inside a class are called static members in Java. These members belong to the class itself rather than any specific object. Therefore, they can be accessed without creating an instance of the class.

Since static members are not tied to any particular object, they are shared among all instances of the class and exist independently of object creation.

Features of Static Keyword in Java


There are several important features of static keyword in Java that you should keep in mind. They are as follows:

  • Static keyword in Java can be applied with variables, methods, blocks, and inner classes.
  • We cannot declare a top-level class with static keyword, but the inner classes can be declared as static.
  • A static member belongs to the class rather than to any specific instance of the class.
  • One basic rule when you work with static keyword is that you cannot directly call instance members within the static area because the static members are associated with the class, not with any object.
  • Static members get memory only once, when the class is loaded into the memory by JVM. In contrast, instance members get the memory only after the object creation of the class.

When we call an instance member within the static area, it results in a compile-time error. This is because when a class is loaded into the memory, the static member also loaded into the memory.

After loading, it will look the instance member in its class that is not in existence because we have not created any object till now. Hence, there is ambiguity. For example:

public class SaticTest 
{ 
  private int a = 10; // Instance field. 
  public static void main(String[] args) 
  { 
    int b = a; // Error: Cannot access non-static variable 'a' from a static context. 
  } 
}

In the above example, the main() method is static. Therefore, it cannot access the instance variable a directly. Doing so will cause a compile-time error. However, we can access static methods or static fields from the instance methods without any problem because static members are already loaded with the class and available for use.

Use of Static Keyword in Java


There are two main uses of static keyword in Java that are as follows:

1. Accessing Members Without Object Creation:

The main purpose of using static keyword is that we can access the variables, methods, or blocks of the class without any object creation. Let’s understand it with a simple example.

As you know that the main() method is declared as a static in Java so that the Java Virtual Machine (JVM) can invoke it without creating an object of the class. The object is not required to call the static method. If the main() method was a non-static, the JVM would need to create an object first and then it will call the main() method.

This would lead to unnecessary memory usage and a circular dependency problem, i.e., needing an object to start execution, but needing execution to create the object.

2. Memory Efficiency:

The static keyword helps to make Java programs more memory-efficient by ensuring that static members are shared across all objects of a class. Only one copy of a static variable or method is created, regardless of how many objects of the class exist. This reduces memory usage and improves performance.

Static Variable in Java


If we declare any instance variable with a static modifier, it is known as static variable in Java. A static variable is also known as class variable in Java, because it belongs to the class rather than any specific instance of the class.

A static variable stores its value in a common memory location, and that value is shared among all instances (objects) of the class.

Syntax to Declare a Static Variable in Java

The general syntax to declare a static variable in Java as follows:

access_ modifier static data_type variable_name = value;

Examples:

static int num;  // Default access modifier  
private static int age; // Private access modifier
public static String name = "John"; // Public access modifier

When we declare an instance variable in Java, a separate copy is created for each object of the class. But in the case of a static variable, only a single copy is created at the class level and it is shared by all objects of that class. This helps in saving memory and maintaining shared data across all objects.


Key Point:

A local variable cannot be declared as static. If you try to declare a local variable as static, the compiler will throw an error.

public void myMethod() {
   static int count = 0; // Compile-time error
}

Reason: Static variables belong to the class and are initialized when the class is loaded, whereas local variables belong to the method stack and exist only during the execution of a method.

How to Access Static Variable in Java?


In Java, there are two ways to access a static variable. They are as follows:

1. Using the Class Name (Recommended)

A static variable can be accessed from any other class using the class name. This is the most common and recommended approach because it clearly indicates that the variable belongs to the class, not to an instance. The general syntax to access a static variable in Java is as follows:

ClassName.variableName;

Example:

A.x; // Here, 'A' is the class name, and 'x' is a static variable declared in that class.

2. Using an Object Reference (Not Recommended)

Static variables can also be accessed using an object reference, although this is not recommended because it may mislead you into thinking the variable is instance-specific. For example, we have a class named Student. We can create the object of the Student class and access static variable x like this:

Student s = new Student();
s.x; // Legal, but not recommended

Note: You can access static variables in both ways, but you can only access instance variables through object references (not via the class name).

Example of Accessing Static Variable


Example 1: Let write a Java program in which we will declare a variable as static and access it by using class name and object reference variable.

package staticVariable; 
public class Student 
{ 
// Declare a static variable id of type int and assign it the value 20. 
   static int id = 20; // static variable declaration and initialization.

// Main method. 
   public static void main(String[] args) 
   { 
  // Create an object of the class Student. 
     Student s = new Student(); 
  
  // Accessing static variable using object reference variable s and store it by variable x of data type int.
  // This approach is not recommended. 
     int x = s.id; 

  // Print on the console. 
     System.out.println(x); 
  
  // Now accessing static variable id using the class name (Recommended). 
     System.out.println(Student.id); 
   } 
}
Output: 
       20 
       20

As you can see in the above program, we have printed the value of id by using object reference and class name.

Static Variable Initialization


There are the following important points to keep in mind about static variable initialization in Java. They are:

1. When a class is loaded into the memory at runtime, its static variables are created and initialized in the common memory location and his happens only once. In other words, static variables get loaded into the memory at the time of class loading.

2. Static variables are initialized before the creation of any instance of that class.

3. Static variables are initialized before the execution of any static method of the class. You can modify the initialized value of a static variable inside a static method.

4. If any object changes the value of the static variable, the new value is reflected across all instances because the variable is shared. If we increment a static variable by 1 in the constructor, it will retain its value across objects and increase by 1 for each new object created.

Example: How Static Variables Are Shared Among Objects?

Example 2: Let’s take a Java program where we initialize a static variable x with the value 0 and increment it by 1 for each object creation. Look at the following code to understand it better.

package staticVariable; 
public class Counter 
{ 
// Create a static variable and initialize it 0.
   static int x = 0; // It gets memory only once and retain its value.

// Declare a constructor which increments static variable. 
   Counter() 
   { 
     x++; // It will increment the static variable by 1 for each object creation. 
   }
// Declare an instance method. 
   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

This example shows that how static variable is shared and retains its value across all objects. It is incremented with each object’s creation. The flow of execution of the above program is shown in the below figure.
Diagram shows that how static variable in Java is shared across all objects and retains its value.

Explanation:

1. When the above code will execute, the static variable x will set to zero when the class is first loaded in the memory by JVM before any counter instances are created. When the first counter instance is created, the counter constructor executes and increments the static variable by 1. So, the result is 1.

2. When the second object is created, the constructor executes again and increments the static variable x by 1. Now, result is 2.

3. Similarly, when the third object is created, the result becomes 3.

Now imagine if we declare the variable x as an instance variable (i.e. non-static variable) and create three counter objects inside the main() method, then the result would be different. This is because each object has its own copy of an instance variable, x would be initialized to 0 for each object, and incremented independently. Therefore, the output would be:

Output:
       1
       1 
       1

Each constructor call increments its own copy of x, resulting in 1 for every object.

Uses of Static Final Variable in Java


The most common use of a static variable in a class is to hold predefined constants 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 this concept with the help of an example program.

Example 3:

package staticVariable; 
public class Employee 
{ 
// Declare instance variables. 
   String name; 
   int id; 
// Declare a static and final variable companyName of type String
// and assign a value IBM to it which is common for all the objects. 
   static final String companyName = "IBM"; 

// Declare a two-parameters constructor with parameters named n and i. 
   Employee(String n, int i) 
   { 
      name = n; 
      id = i; 
   } 
// Declare an instance method named display. 
   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 two argument values to its constructor. 
   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 two arguments to its constructor. 
   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 objects because companyName is a static variable and it will get memory only once in a common memory location.

Can We Access Instance Members from Static Area Directly?


No, you cannot access instance members (non-static variables or methods) directly from a static area. You can access instance members only from an instance area directly. This is because:

  • Static members are loaded into memory when the class is first loaded, even before any object is created.
  • Instance members are loaded into memory only after an object of the class is created.

Therefore, when a static method tries to access an instance member directly, it results in a compile-time error, as the instance member does not yet exist in memory.

In short, you cannot call an instance member from a static method or block directly, because instance members are not present in the memory until an object is created.

Example 4:

package staticVariable;
public class Test {
   int a = 10; // Instance variable

  public static void main(String[] args) {
     System.out.println(a); // Compile-time error
  }
}

Correct way:

package staticVariable;
public class Test {
   int a = 10; // Instance variable

  public static void main(String[] args) {
     Test obj = new Test(); // Creating object 
     System.out.println(obj.a); // Correct access
  }
}

Can We Access Static Variables from Instance and Static Methods?


Yes, static members (such as static variables) can be accessed from both instance and static area (i.e. instance and static methods). Inside the class, you can access static variables:

  • Directly
  • Using the class name

Outside the class, you can access static variables only using class name.

Example 5:

Let’s take a program where we will access a static variable from both instance and static methods in Java.

package staticVariable; 
public class Test 
{ 
// Instance area.
   int a = 10; // instance variable. 
   static int b = 30; // static variable 

// 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 static variable directly from instance area. 
     System.out.println(b); 
   } 
// Declare a static method.
   static void m2() 
   { 
  // We cannot call instance member from static area. 
     System.out.println(a); // Compile time error because the object of the class is not created at this time.
   } 
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(); // Calling static method.
   } 
}
Output: 
        10 
        30 
        10 
        Compile time error

How to Access Static Variable from Another Class?


We can access a static variable in Java by using class name from another class. Let’s take a program in which we will declare two static variables in a class Calculation and call them 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.

Example 6:

package staticVariable; 
public class Calculation 
{ 
  static int x = 20; // static variable
  static int y = 30; // static variable
}
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 Value of Static Variable?


In Java, we can change the value of the static variable by using a constructor and static block but not inside a static method. Let’s take an example program in which we will change the value of static variables from constructor, static block, static, and instance methods.

Example 7:

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) 
{ 
// Creating an instance of Demo class.
   Demo d = new Demo(); 
   d.m1(); // Calling instance method.
 } 
}
Output: 
       3 
       10 
       100

Advantage of Class Variable


A class variable makes program memory efficient. That is, it saves memory. All 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 and instance variable in Java. They are as:

1. Definition:

  • A static variable is also known as class variable whereas, instance variable is also known as non-static variable.

2. Access Scope:

  • Class variable can be accessed inside a static block, instance block, static method, instance method, and method of the inner class.
  • Instance variable can be accessed only from the instance block, instance method, and method of the inner class.

3. Memory Allocation:

  • Memory is allocated once when the class is loaded.
  • Memory is allocated separately for each object.

4. Resolved At:

  • Class variable is always resolved during compile time whereas, instance variable is resolved during the runtime after the object creation.

5. Serialization:

  • By default, static variable is not serialized in Java whereas, instance variable is serialized by default if the class implements Serializable.

6. Object Sharing:

  • Class variable is shared across all objects of the class.
  • In the case of instance variable, each object has its own separate copy.

7. Access Method:

  • Can be accessed with or without object.
  • Must be accessed through an object.

Key Points About Static Variables:

  • Static variable (also known as class variable) in Java is simply like another variable that is common to all instances of the class.
  • It can be accessed and modified by any object of the class.
  • A static variable can be directly accessed by class name within both static and non-static methods of the class.
  • Static variables can be used with public and final modifiers to make constant values.