Static Variable in Java with Example

In this tutorial, we will learn about static keyword, and static variable in Java with the help of examples. 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 of class is created, data storage is created and methods become available. Sometimes, we need a method that is not associated with any particular object of the class and can call even if no objects are created.

For this purpose, we can fulfill both needs with the help of static keyword in Java.

When we declare a member as static, it means that 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.

main( ) method is declared as static because it must be called before any objects exist.

In this tutorial, we will cover the following topics one by one based on the static keyword in java.

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

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 inside a 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 instances of the class.

Features of Static Keyword in Java


There are several important features of static keyword in java that must keep in mind. They are as follows:

1. Static keyword in Java can be applied with variables, methods, inner classes, and blocks.

2. We cannot declare a class with static keyword but the inner class can be declared as static.

3. It belongs to the class than an 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.

5. Static members get memory once when the class is loaded into the memory. But instance members get the memory after the object creation of the class.

Therefore, when we call an instance member within the static area, it means that 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: 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.

Use of Static Keyword in Java


There are mainly two uses of java static keyword that are as follows:

1. The main purpose of using static keyword 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 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


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. It stores the value for a variable in a common memory location.

The static variable can be declared in Java 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 a static variable in Java. They are as follows:

1. A static variable can be accessed inside any other class using the class name. The general syntax to access a static variable is as follows:

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 take an example program where we will declare a variable as static and access it by using class name and object reference variable.

Program 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; 

// Main method. 
  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 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, the static variable is created and initialized into the common memory location 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 change the initialized value of 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 take an example program where we will initialize a static variable x is equal to 0 and increment static variable by 1 for each object creation. Look at the source code to understand better.

Program code 2:

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

// Declare a constructor. 
  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

The flow of execution of the above program is shown in the below figure.
Static variable in Java

Explanation:

1. 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 JVM before any counter instances are created.

When a counter instance is created, the counter constructor executes and increments the static variable by 1 and result is 1.

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

3. 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 and creating three counter objects in the main() method, then the result will be as follows:

Output:
       1
       1 
       1

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 with the help of an example program.

Program code 3:

package staticVariable; 
public class Employee 
{ 
// Declare instance variables. 
   String name; 
   int id; 
// Declare a static variable companyName of data type String and assign value IBM which is common for all the objects. 
   static 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 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 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 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 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?


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 a static variable stores values into the memory before the object creation whereas an 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 and Static Methods?


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.

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

Program code 4:

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() 
  { 
 // 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(); // 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 an example program related to this concept.

In this example, we will declare 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.

Program code 5:

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?


We 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 take an example program in which we will change the value of static variables from constructor, static block, static, and instance methods.

Program 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


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 (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 a 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. It is not serialized in Java whereas, instance variable is serialized in Java.


Key Points:

1. Static variable (also known as class variable) in Java is simply like another variable but it is common to all instances of the class.

2. It can be accessed and modified by any other objects of class.

3. A static variable can be directly accessed by class name within static and non-static methods of the class.

4. It can be used with public and final modifiers to make constant value.


In this tutorial, you have learned static keyword, and static variable in Java with the help of important example programs. Hope that you will have understood the basic concept of static variable and practiced all example programs.
Thanks for reading!!!

⇐ Prev Next ⇒

Please share your love