O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.5. Variable Scope

The scope of a variable is the part of the program over which the variable name can be referenced—in other words, where you can use the variable in the program. Every variable that I have declared so far in program examples has been defined within the context of a method, the method main(). Variables that are declared within a method are called local variables, as they are only accessible within the confines of the method in which they are declared. However, they are not necessarily accessible everywhere in the code for the method in which they are declared. Look at the next code fragment, which shows variables defined within nested blocks:

{
  int n = 1;                                     // Declare and define n
  // Reference to n is OK here
// Reference to m here is an error because m does not exist yet

  {
    // Reference to n here is OK too
    // Reference to m here is still an error

    int m = 2;                                   // Declare and define m

    // Reference to m and n are OK here - they both exist
  }      // m dies at this point

  // Reference to m here is now an error
  // Reference to n is still OK though
}        // n dies at this point so you can't refer to it in following statements

A variable does not exist before its declaration; you can refer to it only after it has been declared. It continues to exist until the end of the block in which it is defined, and that includes any blocks nested within the block containing its declaration. The variable n is created as the first statement in the outer block. It continues to exist within the inner ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required