Course contentsShow
← Java
Lesson 191 of 2,8704. Control Flow StructuresFree lesson

Declaring Variables Before Control Structures

Variables declared outside a control structure are accessible inside it and remain in scope afterward.

Declaring Variables Before Control Structures

You'll learn why declaring variables outside control structures extends their usefulness beyond a single block.

The Core Idea

When you declare a variable before a control structure (like an if, while, or for loop), that variable remains accessible both inside the control structure and after it completes. This is different from declaring a variable inside a block, where it disappears once that block ends.

Think of it like setting up equipment before starting a task: if you prepare your tools in the main workspace, you can use them during the task and still have them afterward. If you only unpack them inside a temporary work area, they vanish when you leave that area.

Why This Matters

Variables declared outside control structures let you:

  • Capture results: Store values computed inside a loop or conditional for use later
  • Track state across iterations: Maintain counters or accumulators that survive beyond one loop cycle
  • Use values after branching: Access data determined by an if-else after the entire conditional completes

Simple Example

int result;  // Declared BEFORE the if

if (temperature > 30) {
    result = 100;  // Accessible inside
} else {
    result = 50;
}

System.out.println(result);  // Still accessible AFTER

If result were declared inside the if block, it wouldn't exist when you tried to print it afterward.

When to Declare Early

Declare variables before a control structure whenever you need to:

  • Use the value after the control structure ends
  • Initialize once but modify within loops or conditionals
  • Share a variable across multiple branches

Key Takeaway: Variables declared before a control structure remain in scope inside it and afterward, making them available wherever you need them in the surrounding block.