Loading lessons...
Java Scope
Java Scope
Scope is where a variable can be seen and used. Variables declared inside a block are only available inside that block.
Block scope
A variable declared inside a block of curly braces exists only there:
public static void main(String[] args) {
int x = 100; // x can only be used in main
{
int y = 50; // y can only be used in this inner block
}
}
Method parameters
Parameters are local to their method. They exist only while the method runs.
Why scope matters
- Different blocks can reuse the same variable name.
- Variables only live while needed, saving memory.
- Keeps your code organized and predictable.
Naming to avoid confusion
Because of block scope, code like this works:
{
int x = 100;
}
{
int x = 200; // fine, this is a different block
}
TL;DR
- Variables only work inside the block where they are declared.
- Curly braces define a block.
- Same names are fine in different blocks.