Tino APCS

Lifetime, Initialization, and Scope of Variables

Three categories of Java variables have been explained thus far in these lessons.

  • Instance variables
  • Local variables
  • Parameters

Variable lifetime

The lifetime of a variable defines the portion of runtime during which the variable exists.

  • When an object is constructed, all its instance variables are created. As long as any part of the program can access the object, it stays alive.
  • A local variable is created when the program executes the statement that defines it. It stays alive until the block that encloses the variable definition is exited.
  • When a method is called, its parameters are created. They stay alive until the method returns to the caller.

Variable initialization

The type of the variable determines its initial state.

  • Instance variables are automatically initialized with a default value (0 for numbers, false for boolean, null for objects).
  • Parameters are initialized with copies of the arguments.
  • Local variables are not initialized by default so an initial value must be supplied. The compiler will generate an error if an attempt is made to use a local variable that may not have been initialized.

Scope

Scope refers to the area of a program in which an identifier is valid and has meaning.

  • Instance variables are usually declared private and have class scope. Class scope begins at the opening left brace ({) of the class definition and terminates at the closing brace (}). Class scope enables methods to directly access all of its instance variables.
  • The scope of a local variable extends from the point of its definition to the end of the enclosing block.
  • The scope of a parameter is the entire body of its method.

An example of the scope of a variable is given in Code Sample 4-2. The class ScopeTest is created with three methods:

Code Sample 4-2

The results show the following about the scope of the variable test:

  • Within the scope of main, the value of test is 10, the value assigned within the main method.
  • Within the scope of printLocalTest, the value of test is 20, the value assigned within the printLocalTest method
  • Within the scope of printClassTest, the value of test is 30, the private value assigned within ScopeTest, because there is no value given to test within the printClassTest method
  • Within the scope of printParamTest, the value of test is 40, the value sent to the printParamTest method

Dark Mode

Outline