A block of code (code block) and variable scope go hand in hand since blocks of code determine variable scope.
What is a Code Block?
In Java, a code block is defined by two curly braces { }. A class is a block of code. A method is a block of code. All loops, if statements, switch statements, try/catch statements, and others are blocks of code defined by { }. Look at the breakdown of this example class.
If you're not yet familiar with if statements and while loops, fear not. We'll be covering them very soon. For now, just try to notice the pattern of the curly braces.
class Main {
// everything inside these two curly braces
// is a member of the class "Main"
public static void main(String[] args){
// everything inside the curly brackets of the
// main() method belongs to the main() method.
// the variable "i" is available throughout
// the main() method
int i = 0;
if (i < 10){
// here the variable `x` is only
// available within this if statement.
int x = 0;
while (i < 10){
int z = i + x;
// here the variable `z` is only available
// within this while loop
System.out.println(z);
x = x + 1;
i = i + 1;
} // end of while statement
} // end of if statement
} // end of main() method
} // end of Main class
What is the Variable Scope?
A variable only exists within the scope it was declared in. The nearest enclosing curly brackets define the scope.
class Main {
// this variable is an instance variable
// it will be available to all methods - its scope is the entire class
int a = 10;
// the parameter "int a" in the method below is available anywhere
// inside the square() method - it is not available outside the square() method
public int square(int a){
// "int total" is within the scope of this method
// it is only available within this method
// but you can see on the line below that you have
// direct access to variable "a"
int total = a * a;
return total;
}
public void scopeExample(){
// method scope
int val = 1;
while (val < 10){
// "b" (below) is inside the scope of this while loop
// "b" will be re-initialized within each loop
int b = val * val;
System.out.println(b);
}
// using "b" outside the while loop is a compilation error
// "b" is out of scope
//System.out.println(b); // this is an error is uncommented
}
}
Summary: What are Code Blocks and Variable Scope?
- A code block is any group of code that is enclosed with
{} - Variable scope is defined by the nearest enclosing
{} - You cannot use variables that are "out of scope"