Unit 2 Cycle 2 Day 17: Error: Scope and Variable Access

Unit 2 Advanced (Cycle 2) Day 17 of 28 Advanced

Error: Scope and Variable Access

Section 2.9 — For Loops

Key Concept

Variable scope in for loops means the loop variable declared in the initialization (int i = 0) only exists within the loop. Attempting to use i after the loop results in a compile error. If you need the loop variable's final value after the loop, declare it before the loop: int i; for (i = 0; ...). The AP exam creates error-spotting questions where code tries to access a loop variable outside its scope, or where a variable declared inside a loop body is referenced after the loop ends.

A student writes the following code. Which line causes a compile-time error?

Line 1: for (int i = 0; i < 5; i++) Line 2: { Line 3: int sum = 0; Line 4: sum += i; Line 5: } Line 6: System.out.println(sum);

Which line causes the error?

Answer: (D) Line 6

The variable sum is declared inside the loop (Line 3), so its scope is limited to the loop body (Lines 2-5). Line 6 is outside the loop and cannot access sum. The fix: declare sum before the loop.

Why Not the Others?

(A) The for loop header is syntactically correct.

(B) sum += i is valid inside the loop where both sum and i are in scope.

(C) The closing brace ends the loop body, which is valid.

Common Mistake

Variables declared inside a loop body are recreated each iteration and destroyed when the loop ends. To use a variable after a loop, declare it before the loop.

AP Exam Tip

Scope errors are common AP exam questions. A variable declared inside braces {} cannot be accessed outside those braces.

Review this topic: Section 2.9 — For Loops • Unit 2 Study Guide

More Practice

Related FRQs

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.