- To meet temparary requirements of the programer some times we have to
create variables inside method or block or constructor such type of variables
are called as local variables
- Local variables also known as stack variables or automatic variables or temparary
variables
- Local variables will be stored inside a stack
- The local variables will be created while executing the block in which we
declared it & destroyed once the block completed .Hence, The scope of local variable is
exactly same as the block in which we declared it.
Ex:-
class Test
{
public static void main(String[] args)
{
int i=0;
for(int j=0;j<3;j++)
{
i=i+j;
}
System.out.println(i+"-------------"+j);
}
}
Here we will get compile time error
like this: Can't find symbol , Symbol:varible J, Location: class Test
- For the local variables JVM won't provide any default values
compulsary we should perform initialization explicitly , before using that varible
Ex:- Class Test{
public static void main(String args[])
{
int x;
System.out.println("Hello");
}
}
O/P: Hello
Let's see another example
class Test2{
public static void main(String args[])
{
int x;
System.out.println(x);
}
}
In this class Test2 example we will get compile time error why because we are not initialized variable x
we should initialize before we using it.
Note:-
- It is not recommended to perform initialization of local variables
inside logical blocks because there is no garantee execution of
these blocks at run time
- It's Highly recommended to perform initialization for the local variables at the
time of declaration, at least with default values
- The only applicable modifier for the local variables is "final" if we are
using any other modifier we will get compile time error
0 comments:
Post a Comment