Java_Local&Global_Variable

Published: (February 10, 2026 at 09:34 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Local Variable

  • Declared inside a method, constructor, or block ({}).
  • Accessible only within that method or block.
  • Must be initialized before use.
  • Lifetime exists only while the method executes.
class Demo {
    void show() {
        int x = 10; // local variable
        System.out.println("Value of x: " + x);
    }

    public static void main(String[] args) {
        Demo obj = new Demo();
        obj.show();
    }
}

Global Variable (Instance Variable in Java)

Java does not have true global variables like C/C++. Instead, variables declared at the class level serve similar purposes.

Instance Variable (Non‑static)

  • Declared inside a class but outside any method.
  • Accessible by all methods of the class.
  • Each object gets its own copy.
  • Receives a default value (0, null, false, etc.) if not explicitly initialized.
class Demo {
    int y = 20; // instance variable

    void display() {
        System.out.println("Value of y: " + y);
    }

    public static void main(String[] args) {
        Demo obj = new Demo();
        obj.display();
    }
}

Static Variable (Class Variable)

  • Declared with the static keyword.
  • Shared among all instances of the class.
  • Typically accessed using the class name.
class Demo {
    static int z = 30; // static variable

    public static void main(String[] args) {
        System.out.println("Value of z: " + Demo.z);
    }
}
0 views
Back to Blog

Related posts

Read more »

Constructor in java

What is Constructors? A constructor is a special method in Java that is automatically executed when an object of a class is created. It is mainly used to initi...

Data Types in Java

Data types specify the different sizes and values that can be stored in a variable. Java is a statically‑typed language, so every variable must be declared with...