Global Variable VS Local Variable

Published: (April 6, 2026 at 07:20 AM EDT)
1 min read
Source: Dev.to

Source: Dev.to

Global Variable in Java

Java does not support true global variables. Instead, it uses class‑level variables, which behave similarly.

Types of Class‑Level Variables

  • Static Variable → Shared by all objects
  • Instance Variable → Separate copy for each object

Example

class Test {
    static int x = 10;   // class‑level (global‑like)

    public static void main(String[] args) {
        System.out.println(x);
    }
}

Output

Output

Local Variable in Java

A local variable is declared inside a method, constructor, or block and can only be used within that scope.

Example

class Test {
    public static void main(String[] args) {
        int y = 5; // local variable
        System.out.println(y);
    }
}

Output

Output

Key Characteristics of Local Variables

  • Declared inside a method or block
  • Accessible only within that method/block
  • Memory is allocated when the method starts and released when it ends
  • Must be initialized before use
0 views
Back to Blog

Related posts

Read more »

OpenJDK: Panama

Project Panama: Interconnecting JVM and native code We are improving and enriching the connections between the Java virtual machine and well‑defined but “forei...