OCJP

Scope of the Variables in Java

Scope of the variables is like from where value of any variable can be accessed. Scope of any variable is depends on how and where the variable is declared.

Variables declared in any class may have visibility like private,public,protected or default.

ex.

class VariableScope
{
private int prv;
protected int prc;
public int pub;
int def ;// Default Variable
}

In above example prv is Private variable which can be accessed with in Member Functions of the Class. No Other Class (Not Event Child Class) can access private variable. (Inner Class can access). In same example prc is protected variable that can be accessed from the member functions of the same class and also from Child Classes of the class in Inheritance. When variable is declared as public (pub variable in our example) can be accessed from any class with object of VariableScope class object. Default variables are the variable where any visibility mode is not specified. In can be accessed from the package where the container class exists. Even Child Class in other package can not access the default variables.

PrivateProtectedDefaultPublic
With in Same classSame class + Child ClassesClasses within Same Pacakge Any Where Access

Other Scope of Variable is Local Variables those are declared within a function or any block { and }. They can be accessed only from the block where they are declared.

ex.

void showData(){
int x=20;
//X can be used within this function
}

void showData(int x){
//Here x is Parameter and it can be accssed from this function only.
}

void loopBlockTest(){

for(int i=1;i<=10;i++){
//variable i can be used in this for loop only
}
}

There is also static variables in Java those can be accessed by class name. And value of static variable is shared for all the objects of the same class.

class Data{

int x;
static int y;

public static void main(String []a){
Data D1= new Data();
Data D2= new Data();

D1.x=10;
D1.y=10;
D2.x=20;
D2.y=20; //Value for D1 is also will be 20

System.out.println("Static :"+ Data.y); //can be accessed using class name
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *


× How can I help you?