Understanding scope
In programming, scope defines where a variable is/is not usable within a program. This is often referred to as the visibility of the variable. In other words, where in the code is the variable “visible”. Java uses block scope. In order to explain Java’s scope, we must first understand what a block is.
What is a block?
Curly braces delimit a block of code. In other words, a block starts with the opening curly brace, {
, and ends with the closing curly brace, }
. Note that the braces face each other, as in { }
. A variable is visible and available for use, from where it is declared in the block, to the closing }
of that block. Figure 4.1 presents a code example to help explain:
Figure 4.1 – Block scope in Java
In the preceding figure, we declare an int
variable, x
, on line 5 and initialize it to 1
. The current block of code is the group of Java statements surrounded by { }
. Therefore, the x
variable’...