Scope of variables

In Java variables can be either global or local. Global variables are declared immediately after the main class and are visible throughout the program. Local variables are declared within a method (or subclass) and are only visible within that block of the program.

As an example consider this applet. The code calculates the area of a rectangle and displays the rectangle and the area. It illustrates some of the issues with using local variables:

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

public class areaRect extends Applet {

public void paint(Graphics g) {

int area;
area=areaRectangle(30,40);
g.drawString("Area of rectangle is "+area, 50, 50);
g.drawRect (10,10,30,40);

}
private int areaRectangle(int side1, int side2) {

int area
area= side1*side2;
return area;

}

}

In this example a variable area is declared in each of the methods. Note, though, that area is only visible within the method it is declared in, so there are in fact two different variables in this program called area. This can be confusing to anyone working with the code and also means that the result of the calculation needs to be passed back to the paint method.

This code can be simplified if area is declared globally:

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

public class areaRect extends Applet {

int area;
public void paint(Graphics g) {

areaRectangle(30,40);
g.drawString("Area of rectangle is "+area, 50, 50);
g.drawRect (10,10,30,40);

}
private void areaRectangle(int side1, int side2) {

area= side1*side2;

}

}

So the general rule is to make all variables global, unless there is a reason not to, and avoid confusion by using different names for local variables.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License