Local Variable vs Global Variable in Java

In this post, we will learn the difference between Local Variables and Global Variables in Java. This is a frequently asked question in Java interviews for beginners. Let's dive into it.

Difference between Local Variable and Global Variable in Java

Local Variable Global Variable
A local variable is declared within a method, constructor, or block and is accessible only within that scope. A global variable (also known as an instance variable or field) is declared within a class and is accessible to all methods within that class.
Local variables are created when the method, constructor, or block is invoked and destroyed when it completes execution. Global variables are created when the object of the class is instantiated and destroyed when the object is garbage collected.
Local variables are stored on the stack memory. Global variables are stored on the heap memory along with the object they belong to.
Local variables must be initialized before use. Global variables are initialized with default values (e.g., 0 for numeric types, null for objects) if not explicitly initialized.
The scope of a local variable is limited to the method, constructor, or block in which it is declared. The scope of a global variable is the entire class, and it can be accessed by all methods in that class.
Local variables can be used to hold temporary data within a method. Global variables are typically used to store the state of an object and hold data that needs to be shared among multiple methods in a class.
Changes to the value of a local variable do not affect other parts of the program. Changes to the value of a global variable affect all methods in the class using that variable.
Local variables have no default values and must be assigned a value before being used. Global variables have default values based on their data type, as mentioned earlier.

Example

Let's create an example to illustrate the difference between local variables and global variables in Java, along with the output.
public class VariableExample {
    // Global variable (also known as instance variable)
    private int globalCount = 0;

    public void incrementGlobalCount() {
        globalCount++; // Accessing and modifying the global variable
    }

    public void printGlobalCount() {
        System.out.println("Global Count: " + globalCount); // Accessing the global variable
    }

    public void demonstrateLocalVariable() {
        // Local variable (declared within the method)
        int localCount = 0;
        localCount++; // Modifying the local variable

        System.out.println("Local Count: " + localCount); // Accessing the local variable
    }

    public static void main(String[] args) {
        VariableExample example = new VariableExample();

        example.incrementGlobalCount(); // Incrementing the global variable
        example.printGlobalCount(); // Output: Global Count: 1

        example.incrementGlobalCount(); // Incrementing the global variable again
        example.printGlobalCount(); // Output: Global Count: 2

        example.demonstrateLocalVariable(); // Output: Local Count: 1

        // Attempting to access the local variable outside its scope will result in a compilation error.
        // Uncomment the following line to see the error:
        // System.out.println("Attempt to access local variable outside its scope: " + localCount);
    }
}

Output:

Global Count: 1
Global Count: 2
Local Count: 1

Explanation:

In the main method, we create an instance of the VariableExample class named example.

We call the incrementGlobalCount() method, which increments the value of the global variable globalCount. After each call, the printGlobalCount() method is called to display the updated value of the global variable.

The output shows that the global variable retains its value between method calls. The first call to incrementGlobalCount() increases the globalCount from 0 to 1, and the second call increases it from 1 to 2.

Next, we call the demonstrateLocalVariable() method, which demonstrates the usage of a local variable localCount. The localCount variable is declared within the method and has a local scope limited to that method. It gets initialized each time the method is called and is independent of the global variable globalCount.

The output shows that the local variable localCount has a value of 1 after incrementing it within the demonstrateLocalVariable() method. However, if we attempt to access the local variable localCount outside its scope (e.g., in the main method), it will result in a compilation error as demonstrated in the commented code.

References

Related Posts




Comments