Variable Scope

Source: Kevin Taylor About.com

Java has three kinds of variables: local (automatic), instance, and class. Local variables are declared within a method body. Both instance and class variables are declared inside a class body but outside of any method bodies. Instance and class variables look similar, except class variables are prepended with the static modifier.

General Form
Let's take a look at the general form for declaring each kind of variable in a Java class. The following class is not real Java code; it is only pseudocode:

   class someClass {

      // Instance Variable
      visibility_modifier variable_type instanceVariableName;

      // Class Variable
      visibility_modifier static variable_type classVariableName;

      returnType someMethod() {

         // Local Variable
         variable_type localVariableName;
      }
   }

Variable Scope
Each of the three kinds of variables has a different scope. A variable's scope defines how long that variable lives in the program's memory and when it expires. Once a variable goes out of scope, its memory space is marked for garbage collection by the JVM and the variable may no longer be referenced.

Notice that both instanceVariableName and classVariableName are declared within someClass but outside of any of its methods (only one method exists in this example). localVariableName, on the other hand, is declared within someMethod. Local variables must be declared within methods. This includes being declared within code blocks nested inside of a method--within an if, while, or for block, for instance. A variable is local to the code block within which it is declared. Being declared within a method body makes a variable local to that method. Being declared within an if block makes the variable local to that if block, for example. This means that the variable cannot be used outside of the curly braces within which it was declared. In fact, it can only be used from the line it is declared on until the code block ends.