The Scope of a Variable
In this lesson, we explore the portions of a program where we can use our variables.
We'll cover the following
What is a variable’s scope?
When we declare a variable, the portion of the program where we can use that variable is called its scope. This portion extends from the declaration itself to the closing brace that encloses the declaration. That is, the closing brace ends the compound statement or method that contains the variable’s declaration.
Example
For example, the figure given below contains the main
method that appeared in the previous lesson. The scope of starCounter
begins at its declaration and extends to the end of the outer while
loop. Thus, starCounter
is available for use anywhere within this portion of the program. It would be undefined after the closing brace of the outer while
loop, for example. Both rowCounter
and sideLength
have a scope that begins at their respective declaration and extends to the end of
the main method.
Get hands-on with 1400+ tech skills courses.