4.5 Local Variables and Scope 

Previous Index Next 


Local variables are declared in the body of methods. They are declared exactly the same way as attributes except that the only FieldModifier allowed is final.

Local variables are effected by scope in a similar way to C++. Basically a variable is only visible within the block of code that the variable was declared. A block of code is defined by a set of braces. As soon as a local variable goes out of scope it is destroyed.

For instance:

public void myMethod()     // declare simple method called myMethod
 {
  int y =0;                // declare integer y initializes to 0
  if ( y == 0)             // true since y is initialized to 0
     {
      int x = 5;           // declare integer x initialized to 5
      x = x * y;           // set x  equal to x times y
     }
  x = 0;                   // THIS IS ILLEGAL. x is out of scope so it cannot be accessed here !
  y = 0;                   // this is legal. y is still in scope
 }