Language 3 of 10 · Topic 0.3

Variable Scoping, final Constants & Local Variable Inference (var)

1Concept

Java enforces block scoping {}. The final keyword makes variables immutable (constants), methods un-overridable, and classes un-inheritable. Java 10+ introduced var for local variable type inference, where the compiler infers the static type from the right-hand initializer.

2Architecture Diagram

var list = new ArrayList<String>(); // Statically compiled as ArrayList<String>!
final int MAX_RETRIES = 3;         // Cannot be reassigned once initialized.

3Code Example

Stage 0 Language Foundations
import java.util.List;

public class ScopeDemo {
    private static final String SYSTEM_NAME = "Enterprise-Auth"; // Class-level constant

    public static void main(String[] args) {
        final var timeoutSeconds = 30; // Inferred as int, immutable
        var activeNodes = List.of("node-east-1", "node-east-2", "node-west-1"); // Inferred as List<String>

        System.out.println("System: " + SYSTEM_NAME);
        System.out.println("Timeout: " + timeoutSeconds + "s");
        System.out.println("Nodes count: " + activeNodes.size());

        for (var node : activeNodes) {
            System.out.println(" - Active: " + node);
        }
    }
}

4Expected Output

System: Enterprise-Auth
Timeout: 30s
Nodes count: 3
 - Active: node-east-1
 - Active: node-east-2
 - Active: node-west-1

5Key Takeaways

  • var is only allowed for local variables with initializers (not for fields or parameters).
  • final on an object reference prevents reassigning the reference, but the object's contents can still mutate.
  • Static final variables are stored in the Metaspace/Class data area.