Difference Between Local, Global and Static Variables in Java
By Bhau Automation • Understand Java Variable Types Practically
🎯 What You Will Learn in This Video
- What are variables in Java?
- Types of variables: local, global (instance), and static
- Memory allocation and lifetime of variables
- Difference between local, instance, and static variables
- Real-time examples of each variable type
- Practical demonstration in Eclipse IDE
💡 Pro Tip: Understanding how Java variables work is key to mastering memory management and writing efficient code.
📘 What is a Variable in Java?
In Java, a variable is a container that holds data during program execution. Every variable has a data type, name, and scope. Based on where it is declared, it can be categorized into three types.
🔹 Types of Variables in Java
- Local Variables: Declared inside methods, constructors, or blocks. They are created when the method is invoked and destroyed when it ends.
- Instance (Global) Variables: Declared inside a class but outside any method. Each object has its own copy.
- Static Variables: Declared using the
statickeyword. Shared among all objects of a class.
💻 Java Example Demonstrating All Three
class VariableDemo {
int instanceVar = 100; // Instance (global) variable
static int staticVar = 200; // Static variable
void display() {
int localVar = 50; // Local variable
System.out.println("Local Variable: " + localVar);
System.out.println("Instance Variable: " + instanceVar);
System.out.println("Static Variable: " + staticVar);
}
public static void main(String[] args) {
VariableDemo obj1 = new VariableDemo();
obj1.display();
VariableDemo obj2 = new VariableDemo();
obj2.instanceVar = 300;
VariableDemo.staticVar = 400;
obj2.display();
}
}
📊 Key Differences
| Feature | Local Variable | Instance (Global) Variable | Static Variable |
|---|---|---|---|
| Declared Inside | Method/Block | Class (Outside Methods) | Class with static keyword |
| Memory Location | Stack | Heap | Method Area |
| Default Value | None (must be initialized) | Default values provided | Default values provided |
| Scope | Within method only | Accessible throughout object | Accessible throughout class |
| Lifetime | Till method execution ends | Till object is destroyed | Till program ends |
| Shared Between Objects | No | No (each object has copy) | Yes |
🎥 Watch the Complete Video Tutorial
👉 Watch on YouTube: Local, Global, and Static Variables in Java
🧠 Key Takeaways
- Local variables exist only inside methods and must be initialized manually.
- Instance variables belong to objects — each object has its own copy.
- Static variables are shared among all objects and belong to the class.
- Understanding variable scope helps manage memory efficiently.
⚡ Next Steps: Practice declaring all three variable types in your own Java class and observe their behavior during runtime.
🚀 Created with ❤️ by Bhau Automation