DEV Community

Cover image for Difference Between Global Variable And Local Variable?
Arul .A
Arul .A

Posted on

Difference Between Global Variable And Local Variable?

Today we discuss about the difference between the global and local variable.First we talk about the Local Variable

1.LOCAL VARIABLE :

  • Declared inside a method, constructor, or block

  • Exists only while that method/block runs

  • JVM does NOT give default values

  • Lives in stack memory

Example:

class Demo {
    void show() {
        int x = 10;   // local variable
        System.out.println(x);
    }
}

Enter fullscreen mode Exit fullscreen mode

2.GLOBAL VARIABLE :

A) Instance Variable (Object-level):

  • Declared inside class but outside methods

  • Each object gets its own copy

  • Stored in heap memory

  • Has default values

Example:

class Student {
    int age;   // instance variable
}
Student s1 = new Student();
System.out.println(s1.age); // prints 0

Enter fullscreen mode Exit fullscreen mode

B) Static Variable (Closest to real global):

  • Declared using static

  • Single shared copy for the entire class

  • Loaded once when class is loaded

Example:

class College {
    static String name = "ABC College";
}
System.out.println(College.name);

Enter fullscreen mode Exit fullscreen mode

Key facts:

  • Shared across all objects

  • Accessible using class name

  • Misuse leads to tight coupling & bugs

Top comments (0)