π Variables Kya Hain?
Variable = Named memory location jahan value store hoti hai int age = 25; β β β type name value
Java mein 3 types:
LOCAL β Method ke andar β Stack Memory INSTANCE β Class ke andar β Heap Memory (per object) STATIC β Class level β Method Area (one copy)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β JVM MEMORY β β β β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββββββ β β β STACK β β HEAP β β METHOD AREA β β β β β β β β β β β β Local vars β β Instance varsβ β Static vars β β β β Method calls β β Objects β β Class info β β β β β β β β β β β β Fast access β β Slower β β Shared globally β β β β Auto cleanup β β GC cleanup β β Class load/unloadβ β β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββββββ β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Simple Analogy:
STACK = Aapki desk β Kaam karte waqt use karo, kaam khatam delete HEAP = Cupboard β Objects rakhte hain, GC saaf karta hai METHOD AREA = Notice Board β Sabko dikhta hai, ek hi copy, class level
Deep Explanation:
class MyClass { void myMethod() { int x = 10; β LOCAL VARIABLE // x sirf yahan exist karta hai } // x yahan exist NAHI karta! }
5 Important Rules:
Rule 1: Method / Constructor / Block ke ANDAR declare hota hai Rule 2: STACK memory mein store hota hai Rule 3: JVM default value NAHI deta β USE SE PEHLE INITIALIZE KARO! Rule 4: Method khatam β variable automatically destroy Rule 5: Sirf us block mein visible jahan declare kiya
Default value NAHI milti:
int x; System.out.println(x); // β COMPILE ERROR! // "variable x might not have been initialized"
Stack mein kaise kaam karta hai:
main() calls methodA() calls methodB() STACK: βββββββββββββββ β methodB() β β top (current) β int c=30 β βββββββββββββββ€ β methodA() β β int b=20 β βββββββββββββββ€ β main() β β bottom β int a=10 β βββββββββββββββ methodB() khatam β c destroy methodA() khatam β b destroy
public class LocalVar1 { void showLocal() { // LOCAL variable - method ke andar int age = 25; // local String name = "Rahul"; // local double salary = 50000; // local System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary); // Method khatam hone par age, name, salary destroy ho jaayenge } public static void main(String[] args) { LocalVar1 obj = new LocalVar1(); obj.showLocal(); // age, name, salary yahan accessible NAHI hain! // System.out.println(age); // β ERROR - cannot find symbol } }
age, name, salary sirf showLocal() method ke andar exist karte hain. Method khatam β variables destroy. Bahar access karna compile error dega.public class LocalVar2 { public static void main(String[] args) { // Rule: Initialize karna MANDATORY hai use se pehle! int a = 10; // β declared + initialized int b; // β declared only (abhi use nahi kar sakte) // System.out.println(b); // β COMPILE ERROR! b = 20; // β ab initialize kiya, ab use kar sakte System.out.println("a = " + a); System.out.println("b = " + b); // Block scope - if block mein local variable if (true) { int blockVar = 100; // sirf is block ka System.out.println("Inside block: " + blockVar); } // System.out.println(blockVar); // β ERROR - out of scope! // Loop variable - sirf loop ke andar for (int i = 0; i < 3; i++) { int loopLocal = i * 10; // har iteration naya variable System.out.println("i=" + i + " loopLocal=" + loopLocal); } // System.out.println(i); // β ERROR! // System.out.println(loopLocal); // β ERROR! } }
{} ka apna scope hota hai. Bahar declare kiya toh andar accessible hai, but andar declare kiya toh bahar accessible NAHI.public class LocalVar3 { void methodA() { int x = 100; // methodA ka local System.out.println("methodA: x = " + x); methodB(); // methodB call kiya // methodB ka y yahan nahi dikhta } void methodB() { int y = 200; // methodB ka local - alag variable! System.out.println("methodB: y = " + y); // x yahan accessible NAHI hai // System.out.println(x); // β ERROR! } public static void main(String[] args) { LocalVar3 obj = new LocalVar3(); obj.methodA(); // Stack visualization: // methodB() β y=200 (top) // methodA() β x=100 // main() β obj reference (bottom) } }
methodA ka x aur methodB ka y dono alag stack frames mein hain. Ek method doosre ka local variable access NAHI kar sakta.public class LocalVar4 { // Same naam ka local variable vs instance variable String name = "Instance Name"; // instance variable void showShadowing() { String name = "Local Name"; // local variable - SAME NAAM! // Local variable "shadows" instance variable System.out.println("name = " + name); // Local Name System.out.println("this.name = " + this.name); // Instance Name } void noShadowing() { // Local variable nahi hai, isliye instance accessible System.out.println("name = " + name); // Instance Name } public static void main(String[] args) { LocalVar4 obj = new LocalVar4(); System.out.println("--- Shadowing ---"); obj.showShadowing(); System.out.println("\n--- No Shadowing ---"); obj.noShadowing(); } }
this.name se instance variable access kar sakte hain.public class LocalVar5 { public static void main(String[] args) { // Local variables different blocks mein same naam rakh sakte hain { int x = 10; System.out.println("Block 1: x = " + x); } // x yahan destroy { int x = 20; // VALID! naya block, naya scope System.out.println("Block 2: x = " + x); } // x yahan destroy // Constructor mein local variable System.out.println("\n--- Method local variable lifecycle ---"); for (int i = 1; i <= 3; i++) { int temp = i * i; // har iteration mein naya temp create & destroy System.out.println("Iteration " + i + ": temp = " + temp); } // temp ka lifecycle: create β use β destroy (every iteration!) } }
Deep Explanation:
class Student { String name; β INSTANCE VARIABLE int age; β INSTANCE VARIABLE double marks; β INSTANCE VARIABLE void study() { int hours = 5; // local variable } }
5 Important Rules:
Rule 1: Class ke andar, methods ke BAHAR declare hota hai Rule 2: HEAP memory mein - HAR OBJECT KA ALAG COPY hota hai! Rule 3: JVM AUTOMATICALLY default value deta hai Rule 4: Object create β memory milti hai (new keyword) Rule 5: Object destroy β GC memory release karta hai
Default Values:
int, byte, short, long β 0 float, double β 0.0 boolean β false char β '\u0000' (null char) Object references β null
Har Object Ka ALAG Copy:
Student s1 = new Student(); β s1.name, s1.age (HEAP location A) Student s2 = new Student(); β s2.name, s2.age (HEAP location B) s1.name = "Rahul" β sirf s1 ka name badla s2.name = "Priya" β sirf s2 ka name badla Dono independent hain!
public class InstanceVar1 { // INSTANCE VARIABLES - class ke andar, method ke bahar String name; // default: null int age; // default: 0 double salary; // default: 0.0 boolean active; // default: false void display() { System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary); System.out.println("Active: " + active); } public static void main(String[] args) { // Object create kiya - instance variables ko memory mili InstanceVar1 emp = new InstanceVar1(); System.out.println("--- Default Values (JVM ne diye) ---"); emp.display(); System.out.println("\n--- After Assignment ---"); emp.name = "Rahul"; emp.age = 30; emp.salary = 75000; emp.active = true; emp.display(); } }
public class InstanceVar2 { // Instance variables String name; int marks; String grade; // Constructor se initialize karna best practice hai InstanceVar2(String name, int marks) { this.name = name; this.marks = marks; // grade calculate karo if (marks >= 90) this.grade = "A+"; else if (marks >= 75) this.grade = "A"; else if (marks >= 60) this.grade = "B"; else if (marks >= 35) this.grade = "C"; else this.grade = "F"; } void display() { System.out.println(name + " | Marks: " + marks + " | Grade: " + grade); } public static void main(String[] args) { // HAR OBJECT KA ALAG COPY! InstanceVar2 s1 = new InstanceVar2("Rahul", 92); InstanceVar2 s2 = new InstanceVar2("Priya", 78); InstanceVar2 s3 = new InstanceVar2("Amit", 45); System.out.println("--- All Students ---"); s1.display(); s2.display(); s3.display(); // s1 ka marks badlao - s2, s3 affect NAHI hoge s1.marks = 95; System.out.println("\nAfter changing s1 marks:"); s1.display(); s2.display(); // unchanged! s3.display(); // unchanged! } }
s1.marks = 95 sirf s1 object ka marks badla. s2 aur s3 ke marks same rahe β yahi "Har object ka ALAG copy" ka proof hai!public class InstanceVar3 { // Instance variables - Heap mein store int id; String brand; double price; int quantity; InstanceVar3(int id, String brand, double price, int quantity) { this.id = id; this.brand = brand; this.price = price; this.quantity = quantity; } double getTotalValue() { return this.price * this.quantity; // instance vars use kiye } void restock(int addQuantity) { this.quantity += addQuantity; // instance var modify System.out.println(brand + " restocked. New qty: " + quantity); } void display() { System.out.printf("ID:%d | %-10s | Rs.%-8.2f | Qty:%-4d | Total:Rs.%.2f%n", id, brand, price, quantity, getTotalValue()); } public static void main(String[] args) { InstanceVar3 p1 = new InstanceVar3(101, "Apple", 79999, 10); InstanceVar3 p2 = new InstanceVar3(102, "Samsung", 49999, 25); InstanceVar3 p3 = new InstanceVar3(103, "OnePlus", 34999, 15); System.out.println("--- Inventory ---"); p1.display(); p2.display(); p3.display(); System.out.println("\n--- Restocking ---"); p1.restock(5); p2.restock(10); System.out.println("\n--- Updated Inventory ---"); p1.display(); p2.display(); p3.display(); } }
public class InstanceVar4 { // Memory lifecycle demonstration String name; int value; InstanceVar4(String name, int value) { this.name = name; this.value = value; System.out.println("Object CREATED: " + name + " (Heap memory allocated)"); } // finalize called when GC destroys object (demonstration only) protected void finalize() { System.out.println("Object DESTROYED: " + name + " (Heap memory released)"); } public static void main(String[] args) { System.out.println("--- Creating objects ---"); InstanceVar4 obj1 = new InstanceVar4("Object1", 100); InstanceVar4 obj2 = new InstanceVar4("Object2", 200); System.out.println("\n--- Using objects ---"); System.out.println(obj1.name + " value: " + obj1.value); System.out.println(obj2.name + " value: " + obj2.value); System.out.println("\n--- Objects still in memory ---"); System.out.println("obj1 exists: " + (obj1 != null)); System.out.println("obj2 exists: " + (obj2 != null)); // obj2 reference null kar do - GC eligible obj2 = null; System.out.println("\nobj2 reference set to null"); System.out.println("obj2 is now GC eligible"); // obj1 abhi bhi valid System.out.println("obj1 still valid: " + obj1.name); } }
new keyword se Heap mein memory milti hai. Reference null karne par object GC (Garbage Collector) ke liye eligible ho jaata hai β automatically memory free ho jaati hai.public class InstanceVar5 { // Instance variable ki deep scope demonstration int counter = 0; // instance variable - har object ka alag void increment() { counter++; // instance var modify kar rahe hain } void incrementBy(int amount) { counter += amount; } void display(String label) { System.out.println(label + " counter = " + counter); } public static void main(String[] args) { // 3 alag objects - 3 alag counters InstanceVar5 c1 = new InstanceVar5(); InstanceVar5 c2 = new InstanceVar5(); InstanceVar5 c3 = new InstanceVar5(); System.out.println("--- Initial ---"); c1.display("c1"); // 0 c2.display("c2"); // 0 c3.display("c3"); // 0 c1.increment(); c1.increment(); c1.increment(); c2.increment(); c3.incrementBy(10); System.out.println("\n--- After operations ---"); c1.display("c1"); // 3 c2.display("c2"); // 1 c3.display("c3"); // 10 // PROOF: teeno alag hain! } }
Deep Explanation:
class Student { static int totalStudents = 0; β STATIC VARIABLE String name; β instance variable }
5 Important Rules:
Rule 1: static keyword ke saath declare hota hai Rule 2: METHOD AREA mein store - SIRF EK COPY poori class ke liye Rule 3: JVM AUTOMATICALLY default value deta hai Rule 4: .class file load β memory milti hai (object bana bhi na ho!) Rule 5: ClassName.variableName se access karo (best practice)
Instance vs Static β Key Difference:
INSTANCE: STATIC: ββββββββββββ ββββββββββββββββββββββββ β obj1 β β METHOD AREA β β name=Raj β β totalCount = 3 β ββββββββββββ ββββββββββββββββββββββββ ββββββββββββ β β β β obj2 β shared by all objects! β name=Ali β ββββββββββββ ββββββββββββ β obj3 β β name=Sam β ββββββββββββ
Kab use karein:
β Counter - kitne objects bane (totalStudents, totalAccounts) β Constants - PI, MAX_SIZE (static final ke saath) β Shared config - company name, app version β Utility values - sabko same value chahiye
public class StaticVar1 { // STATIC variable - sirf ek copy, sab share karte hain static int objectCount = 0; // kitne objects bane // INSTANCE variable - har object ka alag String name; int id; StaticVar1(String name) { objectCount++; // static - shared counter badha this.id = objectCount; // is object ka id this.name = name; System.out.println("Object created: " + name + " (ID: " + id + ")"); } public static void main(String[] args) { System.out.println("Initial count: " + StaticVar1.objectCount); // 0 StaticVar1 s1 = new StaticVar1("Rahul"); System.out.println("Count now: " + StaticVar1.objectCount); // 1 StaticVar1 s2 = new StaticVar1("Priya"); System.out.println("Count now: " + StaticVar1.objectCount); // 2 StaticVar1 s3 = new StaticVar1("Amit"); System.out.println("Count now: " + StaticVar1.objectCount); // 3 System.out.println("\nTotal objects created: " + StaticVar1.objectCount); System.out.println("s1.id = " + s1.id); // 1 - alag System.out.println("s2.id = " + s2.id); // 2 - alag System.out.println("s3.id = " + s3.id); // 3 - alag } }
objectCount static hai isliye teeno objects isko share karte hain. Har naya object bante waqt ek hi counter badha β yahi static ka power hai!public class StaticVar2 { // Static variable - object ke bina bhi access ho sakta hai! static String companyName = "TechCorp India"; static String version = "2.0"; static int employeeCount = 0; // Instance variables String empName; int empId; String department; StaticVar2(String empName, String department) { employeeCount++; this.empId = employeeCount; this.empName = empName; this.department = department; } void displayInfo() { System.out.println("Company: " + companyName); // static access System.out.println("Employee: " + empName); // instance access System.out.println("EmpID: " + empId); System.out.println("Department: " + department); System.out.println("Total Emp: " + employeeCount); System.out.println("---"); } public static void main(String[] args) { // Static variable - object ke bina access! System.out.println("Company: " + StaticVar2.companyName); System.out.println("Version: " + StaticVar2.version); System.out.println("Emp Count: " + StaticVar2.employeeCount); System.out.println("\n--- Creating Employees ---"); StaticVar2 e1 = new StaticVar2("Rahul", "IT"); StaticVar2 e2 = new StaticVar2("Priya", "HR"); StaticVar2 e3 = new StaticVar2("Amit", "Finance"); System.out.println("\n--- Employee Details ---"); e1.displayInfo(); e2.displayInfo(); e3.displayInfo(); // Static variable change karo - SABKO dikhega! System.out.println("Changing company name..."); StaticVar2.companyName = "TechCorp Global"; System.out.println("e1 sees: " + e1.companyName); // changed! System.out.println("e2 sees: " + e2.companyName); // changed! System.out.println("e3 sees: " + e3.companyName); // changed! } }
companyName static hai β ek jagah badla, teeno objects ko naya naam dikha! Isliye static variables shared hain. Instance variables alag hain β empName ek ka badla toh doosron ka nahi badla.public class StaticVar3 { // static final = CONSTANT (kabhi nahi badlega) static final double PI = 3.14159; static final int MAX_STUDENTS = 60; static final String SCHOOL_NAME = "Java High School"; // static variable static int totalStudents = 0; // instance variables String studentName; int rollNo; double[] marks; StaticVar3(String name, double[] marks) { totalStudents++; this.rollNo = totalStudents; this.studentName = name; this.marks = marks; } double getAverage() { double sum = 0; for (double m : marks) sum += m; return sum / marks.length; } void display() { System.out.printf("Roll:%d | %-10s | Avg:%.2f%n", rollNo, studentName, getAverage()); } public static void main(String[] args) { // Constants - object ke bina access System.out.println("School: " + StaticVar3.SCHOOL_NAME); System.out.println("Max capacity: " + StaticVar3.MAX_STUDENTS); System.out.println("PI value: " + StaticVar3.PI); // PI = 3.14; // β ERROR! final variable change nahi kar sakte StaticVar3 s1 = new StaticVar3("Rahul", new double[]{85, 90, 78, 92, 88}); StaticVar3 s2 = new StaticVar3("Priya", new double[]{95, 88, 92, 96, 90}); StaticVar3 s3 = new StaticVar3("Amit", new double[]{70, 65, 72, 68, 75}); System.out.println("\n--- Student Report ---"); System.out.println("School: " + StaticVar3.SCHOOL_NAME); System.out.println("Total Students: " + StaticVar3.totalStudents + "/" + StaticVar3.MAX_STUDENTS); System.out.println(); s1.display(); s2.display(); s3.display(); } }
static final = Constant. PI, MAX_STUDENTS kabhi nahi badlenge β change karne ki koshish karo toh compile error. Naming convention mein CAPS_WITH_UNDERSCORE use karte hain.public class StaticVar4 { // Static variable - class load hone par memory milti hai static int staticVar = 0; // Instance variable - object create hone par memory milti hai int instanceVar = 0; StaticVar4() { staticVar++; instanceVar++; } public static void main(String[] args) { // Static variable - OBJECT KE BINA bhi accessible! System.out.println("staticVar (no object): " + StaticVar4.staticVar); // 0 // instance var - object chahiye // System.out.println(instanceVar); // β ERROR in static context! StaticVar4 obj1 = new StaticVar4(); System.out.println("\nAfter obj1:"); System.out.println("staticVar = " + StaticVar4.staticVar); // 1 (shared) System.out.println("obj1.instanceVar = " + obj1.instanceVar); // 1 (obj1 ka) StaticVar4 obj2 = new StaticVar4(); System.out.println("\nAfter obj2:"); System.out.println("staticVar = " + StaticVar4.staticVar); // 2 (shared!) System.out.println("obj1.instanceVar = " + obj1.instanceVar); // 1 (unchanged) System.out.println("obj2.instanceVar = " + obj2.instanceVar); // 1 (obj2 ka) StaticVar4 obj3 = new StaticVar4(); System.out.println("\nAfter obj3:"); System.out.println("staticVar = " + StaticVar4.staticVar); // 3 (shared!) System.out.println("obj1.instanceVar = " + obj1.instanceVar); // 1 System.out.println("obj2.instanceVar = " + obj2.instanceVar); // 1 System.out.println("obj3.instanceVar = " + obj3.instanceVar); // 1 } }
staticVar 3 tak gaya kyunki 3 objects bane β shared counter. instanceVar hamesha 1 raha kyunki har object ka apna copy hai jo sirf ek baar ++ hua constructor mein.public class StaticVar5 { // Complete comparison - teeno ek saath static String className = "Java Batch 2024"; // static String studentName; // instance // marks local rahega method mein StaticVar5(String name) { this.studentName = name; } void calculateResult(int math, int science, int english) { // LOCAL VARIABLES - sirf is method mein int total = math + science + english; // local double average = total / 3.0; // local String result = (average >= 35) ? "PASS" : "FAIL"; // local System.out.println("\n=== Result Card ==="); System.out.println("Class: " + className); // static System.out.println("Student: " + studentName); // instance System.out.println("Math: " + math); // local (parameter) System.out.println("Science: " + science); // local (parameter) System.out.println("English: " + english); // local (parameter) System.out.println("Total: " + total); // local System.out.printf ("Average: %.2f%n", average); // local System.out.println("Result: " + result); // local // method khatam β total, average, result destroy! } public static void main(String[] args) { StaticVar5 s1 = new StaticVar5("Rahul"); StaticVar5 s2 = new StaticVar5("Priya"); s1.calculateResult(85, 90, 88); s2.calculateResult(72, 68, 75); // Static - dono ke baad bhi accessible System.out.println("\nClass name: " + StaticVar5.className); // Instance - object se accessible System.out.println("s1 name: " + s1.studentName); System.out.println("s2 name: " + s2.studentName); // Local - accessible NAHI // System.out.println(total); // β ERROR! } }
| Property | LOCAL | INSTANCE | STATIC |
|---|---|---|---|
| Declare karo | Method/Block ke andar | Class andar, method bahar | Class andar, static keyword |
| Memory | STACK | HEAP | METHOD AREA |
| Default value | β NAHI β ERROR aayega | β JVM deta hai (0, null etc) | β JVM deta hai (0, null etc) |
| Copy | Method ka apna | Har object ka ALAG copy | SIRF EK copy β sab share karte |
| Lifetime | Method khatam hone tak | Object destroy tak | Class load se unload tak |
| Access | Sirf us block mein | obj.var |
ClassName.var |
| Kab use karein | Temporary calculation | Object ki properties | Shared data / Counter / Constant |
| Mistake | Wrong β | Right β |
|---|---|---|
| Local without init | int x; print(x) | int x=0; print(x) |
| Static in non-static | static void m(){ instanceVar++; } | Use object reference |
| Instance without object | ClassName.instanceVar | obj.instanceVar |
| Static change affect | Think static change = only one object | Static change = ALL objects see it |
| final variable change | PI = 3; (after static final) | Cannot change final! |
StaticVar1 hai toh file StaticVar1.java hogi!