Difference B/W Local, Instance & Static Variables
1. Local Variable
Local variable wah variable hai jise kisi method, constructor ya block ke andar declare kiya jata hai.
A local variable is declared inside a method, constructor, or block and exists only during its execution.
class Student { void display() { int age = 20; // Local variable System.out.println(age); } }
2. Instance Variable
Instance variable ko class ke andar, lekin methods aur constructor ke bahar declare kiya jata hai. Har object ki apni copy hoti hai.
An instance variable is declared inside a class, outside methods and constructors. Each object gets its own copy.
class Student { int age; // Instance variable public static void main(String[] args) { Student s1 = new Student(); Student s2 = new Student(); s1.age = 20; s2.age = 22; System.out.println(s1.age); System.out.println(s2.age); } }
3. Static Variable
Static variable ko class ke andar static keyword ka upyog karke declare kiya jata hai. Yeh sabhi objects ke beech share hota hai.
A static variable is declared inside a class using the static keyword and is shared across all instances of the class.
class Student { static String college = "Gautam"; public static void main(String[] args) { Student s1 = new Student(); Student s2 = new Student(); System.out.println(s1.college); System.out.println(s2.college); System.out.println(Student.college); } }
Bonus Example: Calling Static main() from Another Class
Kyunki main() ek static method hai, ise dusri class se seedhe class name ke saath call kiya ja sakta hai.
Because main() is static, another class can invoke it directly using A.main(args).
class A { public static void main(String[] args) { System.out.println("Hello from class A"); } } class B { public static void main(String[] args) { A.main(args); } }