Variable Scope

 

 

What is the scope of a variable?
The scope of a variable is the part of the program over which the variable name can be referenced. (from Ivor Horton's Beginning Java 2, JDK 5 Edition by Ivor Horton)

1. Scope of a parameter ( the value passed into a method) - only in the body of the method it is passed to.
2. Scope of a local variable - only within the block of code where it was declared.
3. Scope of a local variable in a for loop - only in the for loop.
* if you want the variable to be accessible after the loop then declare it before the for loop
4. Scope of a method or field of a class - anywhere in the class - it has class scope

Scope Tutorial 1

Example 2