Java में Scope और Lifetime
In this page:
Class Scope / Fields
Class level पर declared एक field उस class में हर method के लिए accessible है और containing object जितनी देर मौजूद है उतनी देर persist करता है, एक local variable के विपरीत जो एक method तक सीमित है।
उदाहरण: Class Scope / Fields
class Counter {
int count = 0; // accessible to every method in this class
void increment() {
count++;
}
}
public class Main {
public static void main(String[] args) {
Counter c = new Counter();
c.increment();
System.out.println(c.count);
}
}
Login to try C/C++/Java/PHP code in the editor
Method Scope / Parameters
किसी method के अंदर declared एक parameter या local variable सिर्फ तब तक मौजूद है जब तक वह method execute हो रहा हो — एक बार method return हो जाए, उस variable की memory reclaim किए जाने के योग्य है।
उदाहरण: Method Scope / Parameters
public class Main {
static void method() {
int local = 5; // only exists while method runs
System.out.println(local);
}
public static void main(String[] args) {
method();
// local is not visible here
}
}
Login to try C/C++/Java/PHP code in the editor
Block Scope
एक block scope (curly braces की एक pair के बीच का code, जैसे एक if या loop के अंदर) एक variable की visibility सिर्फ उस block तक सीमित करता है — यह block शुरू होने से पहले या इसके खत्म होने के बाद मौजूद नहीं है।
उदाहरण: Block Scope
public class Main {
public static void main(String[] args) {
if (true) {
int x = 10; // confined to this block
System.out.println(x);
}
// x is not visible here
}
}
Login to try C/C++/Java/PHP code in the editor
Variable Shadowing
Variable shadowing तब होता है जब एक local variable या parameter का नाम एक class field जैसा हो, उस scope में temporarily field को hide करते हुए — field को सीधे access करने के लिए फिर this.fieldName चाहिए।
उदाहरण: Variable Shadowing
class Box {
int size = 10;
void setSize(int size) {
this.size = size; // this.size disambiguates from the parameter
}
}
public class Main {
public static void main(String[] args) {
Box b = new Box();
b.setSize(20);
System.out.println(b.size);
}
}
Login to try C/C++/Java/PHP code in the editor
Garbage Collection & Lifespans
Java का garbage collector objects के लिए memory अपने आप reclaim करता है एक बार कुछ भी उन्हें reference न करे; आप C में जैसे करते वैसे manually memory free नहीं करते, लेकिन एक object की expected lifespan समझना अब भी performance के लिए मायने रखता है।
उदाहरण: Garbage Collection & Lifespans
public class Main {
public static void main(String[] args) {
Object obj = new Object();
obj = null; // no more references: eligible for garbage collection
System.out.println("Object dereferenced");
}
}
Login to try C/C++/Java/PHP code in the editor
- एक variable को इसके block के बाहर उपयोग करना, जो एक compile error है।
- यह मान लेना कि एक local variable method calls के बीच अपनी value रखता है।
- उसी method में एक parameter जैसा ही नाम वाला एक local variable declare करना, जो एक compile error है।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: