Java Reference
In-Depth Information
The scope of a variable is the region of a program in which the variable can be
accessed.
The scope of a local variable extends from the point of its declaration to the end of
the block that encloses it.
It sometimes happens that the same variable name is used in two methods. Consider
the variables r in the following example:
public class RectangleTester
{
public static double area(Rectangle rect)
{
double r = rect.getWidth() * rect.getHeight();
return r;
}
public static void main(String[] args)
{
Rectangle r = new Rectangle(5, 10, 20, 30);
double a = area(r);
System.out.println(r);
}
}
These variables are independent from each other, or, in other words, their scopes
are disjoint. You can have local variables with the same name r in different
methods, just as you can have different motels with the same name ȒBates Motelȓ
in different cities.
The scope of a local variable cannot contain the definition of another variable
with the same name.
In Java, the scope of a local variable can never contain the definition of local
variable with the same name. For example, the following is an error:
Rectangle r = new Rectangle(5, 10, 20, 30);
if (x >= 0)
{
double r = Math.sqrt(x);
// ErrorȌcan't declare another variable called r here
Search WWH ::




Custom Search