← Back to Core Java Course | Chapter 13: Advanced Topics & Reference | Lesson 7 of 10

Java Scope & Lifetime

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

java
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);
	}
}

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

java
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
	}
}

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

java
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
	}
}

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

java
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);
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.