+91 81900 98289

Java Scope

A local variable exists only inside the block where it was declared. A variable declared inside an if cannot be used after that if. A parameter exists only for that method call.

A field is declared in the class, outside the methods. Every method of the object can read it. Prefer local variables unless several methods must share the value.

Example

inner exists only inside the if. The print runs while that block is active, so both names are visible there.

public class Scope { public static void main(String[] args) { int outer = 1; if (outer == 1) { int inner = 5; System.out.println(outer + inner); } } }
If two names collide, the local variable hides the field. That is a frequent bug. Use this.field when you mean the field, or pick a local name that does not match.