Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Scope of variables:

Scope in Java means availability. Scope indicates the lifetime of a


variable in Java. Life time is nothing but the time from the time a
variable is created to the time a variable is lost.
For example
function1()
{
int a=10;//variable is created
}// a is lost
System.outprintln(a);//Error as a is already out of memory or lost
here a cannot be acccesed outside of function1() because its
availability is only inside of function1().it cannot be printed from
out side..
There are three types of variables in Java depending on the scope
They are
1) local variable/ local scope
2) instance variable
3) static variable / class variable

1) local variable:
A variable declared insside a method or a block is called as local
variable.
Local variable can only be accessed inside of a method or block
where it is declared.

When we come out of that method , the variable is not visible


Example program:
class localdemo
{
void function1()
{
int a=10;
System. Out. Println(a);
}
void function2()
{
//System.out.println(a);// Error
}
public static void main(String[] args)
{
localdemo ld= new localdemo();
ld. function1();
ld.function2();
}
}
2. Instance variable: an instance variable is a variable which is
declared directly inside a class and outside of a method.
If you want to access an instance variable then we must create an
instance of the class( object).
After creating the object we can access the instance variable by
using dot operator.
Example program:
class instancedemo
{
void function1()
{
int a=10;
System. Out. Println(a);
}
void function2()
{
int b=20;
System. Out. Println(b);
}
public static void main(String[] args)
{
localdemo ld= new localdemo();
ld.function1();
ld.function2();
}
}
Output:
10
20

3. Static variable/ class variable:


Static variable is declared by using a Keyword static. static
variable can be accessed even without creating the object.
static variable is also called as class variable.
So there is no need to create an object to access the static
variables .
Example program:
class staticdemo
{
static int a=10;
static int b=20;
public static void main(String[] args)
{
System. Out. Println(a);
System. Out. Println(b);
}
}

You might also like