Page 143 - computer science (868) class 11
P. 143
7.2 SCOPE OF VARIABLES
In Java, variables are only accessible inside the part of the program where they are created. This is called the scope of
a variable. It defines the visibility and accessibility of a variable. There are two places in a program where the variables
can be created. They are created directly under a class as data members or inside a method as local variables.
Now, if a variable is created under a class, the data members can be accessed from anywhere in the class whereas if
it is created as a local variable, then it can only be accessed within the method it is created and will have no existence
outside the method. If a local variable is used outside the method it is created, the program will produce an error.
Let us take the following example:
import java.util.*;
class scope_of_variable
{
int length, breadth, area;
void input()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter length and breadth");
length=sc.nextInt();
breadth=sc.nextInt();
}
void calculate()
{
int perimeter;
area=length*breadth;
perimeter=2*(length+breadth);
}
void display()
{
System.out.println("Area " +area);
System.out.println("Perimeter " +perimeter);
}
public static void main()
{
scope_of_variable ob = new scope_of_variable();
ob.input();
ob.calculate();
ob.display();
}
}
In the above program, the variable “perimeter” is a local variable that is declared under the method calculate().
However, it is used under the method display() where it has no existence, thus the program returns an error.
So, we can do either of the two following options to avoid the error.
We can declare the variable perimeter as a data member of the method display().
OR
We can print the variable perimeter under the method calculate().
141
Statements and Scope 141

