[!NOTE] In Java, variables do not live forever. A variable is born when it is declared, and it dies when its surrounding "Block" finishes executing. This is called Scope.
What is a Block?
A block of code refers to all of the code enclosed between curly braces { and }.
Variables are only accessible inside the block they are created in. Furthermore, they are only accessible after the exact line they are declared on.
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
{ // A block artificially begins here!
int x = 100;
// Code here CAN use x
System.out.println(x);
} // The block ends here. The variable 'x' is immediately destroyed in memory!
// Code here CANNOT use x
}
}
Practical Scope: For Loops
A very common practical example of Scope involves for loops.
When you declare your iterator variable int i = 0 inside the parenthesis of a for loop, that variable i is strictly scoped to the loop itself. You cannot access i once the loop finishes computing.
for (int i = 0; i < 5; i++) {
System.out.println(i); // This is perfectly fine.
}
System.out.println(i); // COMPILATION ERROR! 'i' no longer exists!
If you need to know the value of i after the loop finishes (for example, to know exactly what index caused a failure), you must declare i in the block above the loop!
int i = 0; // Raised scope
for (i = 0; i < 5; i++) {
if (i == 3) { break; }
}
System.out.println("The loop broke at index: " + i); // This works beautifully!