Saturday, September 29, 2018

Scope and Life Time of a Variable



Whenever we declare any variable, it is declared within a block (enclosed by curly braces). That particular block is known as scope or life time of a variable.

Let’s describe it with example:

class Sc
{
public void take (int a, int b)
{
int x=a+b;
}

public void show ()
{
System.out.print(x);
}
public static void main(String args[])
{
 Sc ob=new SC();
ob.take(2,3);
ob.show();
}
}

The above program will show compile time error as variable ‘x’ is not accessible within function public void show () as the variable is declared within the function public void take (). Scope and life time of the variable is confined within that function. The correct program would be as follows:

class Sc
{
int x;
public void take (int a, int b)
{
 x=a+b;
}

public void show ()
{
System.out.print(x);
}
public static void main(String args[])
{
 Sc ob=new SC();
ob.take(2,3);
ob.show();
}
}


Loop, if body etc also defines block so variables declared within that block will not be accessible outside.

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner