Java Scope & Lifetime
In this page:
Class Scope / Fields
A field declared at the class level is accessible to every method in that class and persists for as long as the containing object exists, unlike a local variable confined to one method.
Example: 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
A parameter or local variable declared inside a method only exists while that method is executing — once the method returns, that variable's memory is eligible for reclaiming.
Example: 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
A block scope (the code between a pair of curly braces, like inside an if or loop) confines a variable's visibility to just that block — it doesn't exist before the block starts or after it ends.
Example: 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 happens when a local variable or parameter has the same name as a class field, temporarily hiding the field within that scope — accessing the field directly then requires this.fieldName.
Example: 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's garbage collector automatically reclaims memory for objects once nothing references them anymore; you don't manually free memory the way you would in C, but understanding an object's expected lifespan still matters for performance.
Example: 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
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: