Java
Beware of Variable Scope
Important aspect for variable handling
Overview
- Local Variables -- in scope from declaration to end of block.
- Instance Variables -- in scope from declaration until object garbage collected.
- Class Variables (static) -- in scope from declaration until program ends.
Watch out for out-of-scope errors
Some questions may seem very complex, but then it turns out that you just need to catch an out-of-scope error where a variable is not accessible outside an if statement.
public void eatIfHungry(boolean hungry) {
if (hungry) {
int bitesOfCheese = 1;
{
boolean teenyBit = true;
System.out.println(bitesOfCheese);
}
}
System.out.println(teenyBit); // DOES NOT COMPILE
}Jujutsu Kaisen
Scope is like the domain expansion in Jujutsu Kaisen. Each variable has its own expansion.