您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes
Introduction
Content
Apply
Reflect
Extend
previous.gif
 (3087 bytes)
next.gif
 (2959 bytes)

 
 
Content Index
Content Page # 22

Local variable

A local variable is one that can only be referred to inside a single method, or part of a method. For example some local variables are local to a particular method, others are local to only part of a method (such as in a compound loop statement).

An example of a local variable is the loop variable 'i' in this for loop:

for( int i = 0; i < 5; i++)
{
  total = total + i;
  g.drawString( total, x, y);
  y = y + 20;
 }
Since the variable 'i' is declared as part of this for loop, it cannot be referred to outside the loop. So for example, if the loop were followed by a statement attempting to put the value of 'i' on screen:
for( int i = 0; i < 5; i++)
{
  total = total + i;
  g.drawString( "total = " + total, x, y);
  y = y + 20;
}

g.drawString( "i = " + i, x, y);

the following compilation error would occur:
The error says 'undefined variable i' since the compiler does not know what variable you mean.

The part of a class where a variable can be referred to is called the scope of the variable. An instance or class variable (see later this unit) has a scope comprising every method of a class. A local variable may have a scope of a whole method, or may, as in the loop above, have a scope of just one compound statement.

The full listing of our Scope class (without the offending line) is given below:

// Scope.java

// <APPLET code="Scope.class" width=275 height=200></APPLET>

import java.applet.Applet;
import java.awt.*;

public class Scope extends Applet
{
  // instance variable
  double average;

public void paint (Graphics g)
{
    int x = 20;
    int y = 20;

    int total = 0;

for( int i = 0; i < 5; i++)
{
     total = total + i;
     g.drawString( "total = " 
                + total, x, y)
     y = y + 20;
     }
     g.drawString("Program terminating 
                     ", x, y);
    }
  }
There are 5 variables in this program:
  • average
  • x
  • y
  • total
The variable average has a scope of all methods, since it is an instance variable.

The variables x and y and total have a scope of all the statements that occur after them in the paint() method. 

Variable i only has scope within the loop statement

The issue is scope is not covered in great detail here, however, be aware that an error relating to an undefined variable is often one of either scope or a misspelling of the variable identifier.

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg