DEV Community

Cover image for Global Variables vs Local Variables in Java
Harini
Harini

Posted on

Global Variables vs Local Variables in Java

When learning Java, one of the most important concepts to understand is how variables work. Among them, global variables and local variables play a key role in writing efficient and clean programs.

In this blog, we’ll break down these concepts in a simple and beginner-friendly way.

What Are Global Variables in Java?

Global variables in Java are variables that are declared inside a class but outside any method. They can be accessed by all methods within that class.

Types of Global Variables

  • Non-Static Variables(Instance) – Belong to an object
  • Static Variables – Shared across all objects

Example

class Demo {
   int x = 10;        // Instance variable
   static int y = 20; // Static variable

   void display() {
     System.out.println(x);
     System.out.println(y);
   }

   public static void main(String[] args) {
       Demo obj = new Demo(); // create object
       obj.display();         // call method
   }
}
Enter fullscreen mode Exit fullscreen mode

Output

Step-by-step flow

  1. main() starts execution
  2. Object is created → Demo obj = new Demo();
  3. display() method is called
  4. Prints: 10 20

Key Characteristics

  • Declared inside the class, outside methods
  • Accessible throughout the class
  • Automatically assigned default values
  • Longer lifetime (until object or class exists)

What Are Local Variables in Java?

Local variables are declared inside a method, constructor, or block and can only be used within that specific area.

Example

class Demo {
    void display() {
        int a = 5;
        System.out.println(a);
    }

    public static void main(String[] args) {
        Demo obj = new Demo(); // create object
        obj.display();         // call method
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Step-by-step flow

  1. main() starts execution
  2. Object is created
  3. display() is called
  4. Output: 5

Key Characteristics

  • Declared inside methods or blocks
  • Limited scope (only within method)
  • No default values (must be initialized)
  • Short lifetime (exists only during execution)

Top comments (0)