Managing Complexity: Scope
Managing Complexity: Scope
Managing Complexity
Scope
The scope of a variable is defined as the part of the program in which the
variable is valid (where you are allowed to use it). Java has rules to keep
scope as small as possible, because this usually makes programs less
complex.
For for loops, the scope is relatively straightforward: any variable declared
in the initialize part of the for loop is valid only inside the for loop itself.
AP Computer Science
AP Computer Science
Exercise 1. Identifying Scope
For the following exercises, we’ll be working with this program:
Problem 1a.
Draw a box around the scope of the variable a and label the box.
Problem 1b.
Draw a box around the scope of the variable b and label the box.
AP Computer Science
Problem 1c.
Draw a box around the scope of the variable c and label the box.
Problem 1d.
Draw a box around the scope of the variable d and label the box.
Problem 1e.
Draw a box around the scope of the variable e and label the box.
Problem 1f.
What is the output of this program? Write it below.
Each of the following code samples has exactly one scope error. Find the
error and write down why it is an error (what rule of scope it breaks.)
Problem 2a.
AP Computer Science
Problem 2b.
Problem 2c.
AP Computer Science
Problem 2d.
Problem 2e.
Problem 2f.