top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Static Variable in Java

Introduction 

Variables are essential for storing and manipulating data in programming. However, there are scenarios where a variable needs to retain its value across different instances of a class or doesn't rely on an instance at all. 

This is where static variables in Java, also called class variables, become useful. Unlike instance variables specific to objects, static variables are linked to the class. Learn more about the use case of static variables here. 

Overview

In this tutorial, we will delve into the concept of the static variable in Java, understand their behavior, and explore how to declare, initialize, and use them effectively.

Static Keyword in Java

The static keyword in Java declares a class member (such as a variable or method) associated with the class itself instead of a particular instance of the class. By marking a member as static, it becomes accessible and functional without requiring the creation of an object from the class.

Static Variable in Java

When a variable is declared static, it is called a static variable or class variable. These variables are shared by all instances of the class, meaning they maintain the same value across different objects. Static variables are declared using the syntax: 

static dataType variableName;

Advantages of Static Variable

Some advantages of using static variables in Java are:

  • They save memory by being shared among all instances.

  • They can be accessed directly without object instantiation.

  • They maintain values across instances, ensuring data sharing and preservation.

  • They effectively manage shared resources and configurations.

  • Using static variables reduces complexity by eliminating the need for data passing between objects.

Static Variable in Java Example

public class StaticVariableExample {
    // Static variable
    public static int count = 0;
    
    public static void main(String[] args) {
        // Accessing and modifying the static variable
        System.out.println("Initial count: " + count);
        
        count++;
        System.out.println("Updated count: " + count);
        
        // Creating multiple objects of the class
        StaticVariableExample obj1 = new StaticVariableExample();
        StaticVariableExample obj2 = new StaticVariableExample();
        
        // Accessing the static variable using different objects
        obj1.count++;
        obj2.count++;
        
        System.out.println("Count after incrementing through objects: " + count);
    }
}

In the above example, we have a class called StaticVariableExample with a static variable called count. The main method is the entry point of the program.

Inside the main method, we first print the initial value of count (which is 0), then we increment it by 1 and print the updated value.

Next, we create two objects of the class (obj1 and obj2) and increment the count variable using these objects. Since count is a static variable, it is shared among all instances of the class. Therefore, modifying it using one object affects the value seen by other objects and the class itself.

Finally, we print the final value of count, which is incremented by both the direct access and the access through objects, demonstrating the shared nature of the static variable.

Program of Counter Without Static Variable

In this example, the Counter class represents a simple counter. It has an instance variable count which stores the current count. The class provides methods to increment, decrement, and retrieve the count.

In the main method, we create an instance of the Counter class called counter. We print the initial count, which is 0. Then, we increment the count twice and decrement it once. Finally, we print the final count.

Program of Counter With Static Variable

public class Counter {
    private static int count;

    public Counter() {
        count = 0;
    }

    public static void increment() {
        count++;
    }

    public static void decrement() {
        if (count > 0) {
            count--;
        }
    }

    public static int getCount() {
        return count;
    }

    public static void main(String[] args) {
        System.out.println("Initial count: " + getCount());

        increment();
        increment();
        decrement();

        System.out.println("Final count: " + getCount());
    }
}

Now, in this program, the Counter class uses a static variable count to represent the counter. The methods increment(), decrement(), and getCount() are also defined as static.

In the main method, we directly access the static methods and variables without creating an instance of the Counter class. We print the initial count, which is 0. Then, we increment the count twice and decrement it once. Finally, we print the final count.

Static Method in Java

A static method in Java is associated with the class rather than instances of the class. Static methods can be called directly using the class name without creating an object. They are often used for utility functions or operations that don't require access to instance-specific data.

Static methods are declared using the syntax: 

static returnType methodName(parameters);

Example of Static Method

public class StringUtils {
    public static String reverseString(String str) {
        StringBuilder reversed = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {
            reversed.append(str.charAt(i));
        }
        return reversed.toString();
    }


    public static void main(String[] args) {
        String original = "upGrad teaches programming!";
        String reversed = StringUtils.reverseString(original);
        System.out.println("Original string: " + original);
        System.out.println("Reversed string: " + reversed);
    }
}

The StringUtils class contains a static method called reverseString that takes a string as a parameter and returns the reversed version of the string. In the main method, we create a string variable called original and assign it the value "upGrad teaches programming!". We then call the reverseString method and pass in original as the argument. The returned reversed string is stored in the reversed variable, and both the original and reversed strings are printed to the console.

The reverseString method is declared static, meaning it belongs to the class itself and can be accessed without creating class instances. Static methods are commonly used for utility functions or operations that do not require access to instance-specific data. In this example, the reverseString method operates solely on its input parameter str and does not rely on any instance variables.

Another Example of a Static Method That Performs a Normal Calculation

public class MathUtils {
    public static int sum(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int result = MathUtils.sum(5, 3);
        System.out.println("The sum is: " + result);
    }
}

The MathUtils class contains a static method called sum that takes two integers as parameters and returns their sum. In the main method, we call the sum method and pass in the values 5 and 3. The returned sum is stored in the result variable, and then we print it to the console.

The sum method is declared static using the static keyword. Static methods can be called directly on the class without creating an object of the class. In this example, we call the sum method using the class name MathUtils.sum().

Restrictions for the Static Method

Static methods in Java have the following restrictions:

  • They cannot directly use instance variables or methods.

  • They cannot use the "this" keyword to refer to the current instance.

  • They cannot be overridden in subclasses.

  • Subclasses can have their own static methods with the same name but do not override the superclass method.

  • They cannot be declared as abstract.

Java Static Block 

In addition to variables and methods, Java also allows the creation of static blocks. A static block is a set of statements enclosed in curly braces and preceded by the "static" keyword in Java. It is executed when the class is loaded into memory and is commonly used for static initialization tasks.

Example of A Static Block

The MyClass class contains a static block that is executed only once when the class is first loaded into memory. In this example, the static block initializes the static variable count to 0 and prints a message to the console.

The MyClass also has a constructor called each time an object of the class is created. In the constructor, the count variable is incremented.

In the main method, two objects of MyClass are created, which triggers the execution of the static block only once. After creating the objects, the getCount static method is called to retrieve the value of the count variable, which is then printed to the console.

Can We Execute a Program Without the main() Method?

Using a static block, you can execute a program without a main() method. When the Java ClassLoader loads the class into memory, it is commonly used for static initialization tasks. By placing the desired code within a static block, it will be executed without the need for a main() method. 

Important Points for Static Variables

To efficiently use static variables in Java, keep these important pointers in mind:

  • They are shared among all instances and maintain the same value across objects.

  • They are typically initialized during declaration or in a static block.

  • They are allocated memory only once, reducing memory consumption.

  •  They can be directly accessed and modified using the class name.

  • They have a class-level scope and exist throughout the program's lifespan.

  • Synchronization should be implemented for concurrent access to ensure thread safety.

Storage Area of Static Variable in Java 

Static variables in Java are stored in a special area of memory called the "Method Area" or "Class Area". This area is shared by all class instances and is allocated when the class is loaded into memory. Static variables exist for the entire program duration and are accessible by all class instances.

Initialization of Static Final Variables in Java

Static final variables, also known as constants, are initialized at the time of declaration or in a static block. Once initialized, their values cannot be changed. The initialization of static final variables is typically done at the class level and is performed only once when the class is loaded into memory.

Static vs. Non-Static 

The differences between static and non-static variables have been elucidated below:

Class Containing Static Members and Non-Static Members

public class upGradTutorials {
    private static int staticVariable;   // Static variable
    private int nonStaticVariable;       // Non-static variable


    public static void staticMethod() {
        System.out.println("This is a static method.");
    }


    public void nonStaticMethod() {
        System.out.println("This is a non-static method.");
    }

    public static void main(String[] args) {
        staticVariable = 10;   // Accessing the static variable
        staticMethod();        // Calling the static method

        upGradTutorials obj = new upGradTutorials();
        obj.nonStaticVariable = 20;   // Accessing the non-static variable
        obj.nonStaticMethod();        // Calling the non-static method
    }
}

Memory Management of the Above Program

When the class upGradTutorials is loaded into memory, the static variable staticVariable is allocated memory in the static data area, and the static method staticMethod() is also loaded into memory. These static members are associated with the class and are available for use without creating an instance of the class.

When an instance of upGradTutorials is created using the new keyword, memory is allocated to store the non-static variable nonStaticVariable within the instance. Each class instance has its own separate copy of the non-static variable.

In the main() method, we first access the static variable and call the static method using the class name. Since they are associated with the class, we can access them without creating an instance.

Next, we create an object obj of upGradTutorials and access the non-static variable and call the non-static method using the object reference obj. Non-static members are accessed through instances of the class.

Memory for the objects created using new is allocated on the heap, and when the objects are no longer referenced, they become eligible for garbage collection, and the Java runtime reclaims their memory. The static members persist throughout the execution of the program and are cleaned up when the program terminates.

Static Nested Classes in Java

A static nested class is a class that is defined within another class but marked with the static keyword. It is a nested class associated with the outer class itself rather than any specific instance of the outer class.

Conclusion

A static variable in Java provides a shared value across all instances of a class, allowing for storing data common to all objects. They offer a convenient way to access and manipulate shared information, enhancing code efficiency and reducing memory usage. 

To learn more about static variables and their usage, you can sign up for a professional course offered by upGrad.

FAQs

1. Can a static variable in Java be changed?

Yes, a static variable in Java can be changed by modifying its value directly or through methods that have access to the static variable.

2. Why do we need static variables in Java?

We need static variables in Java to store data shared among all class instances. It is a convenient way to access and manipulate common information.

3. What will happen if we do not use static variables in Java?

Not using static variables in Java will lead to unnecessary memory usage and potentially inconsistent or redundant data.

Leave a Reply

Your email address will not be published. Required fields are marked *