A local variable's scope is restricted to the block or method in which it is declared. It can be accessed only in the block/method in which it is declared, from the point of declaration till the end of the block/method.
A local variable comes into existence when the code of the block/method containing the declaration is executed and the declaration is encountered during execution. The variable exists only till the flow of control reaches to the end of the block/method containing it.
One important scope rule in Java that a local variable in some inner block can not hide the variable of the same name in the outer block. This is allowed in C++ and the reference to outer block variables is resolved using scope resolution operator but it is not allowed in Java.
Example: The following program will not compile.
class ScopeDemo{
public static void main(String args[]){
int i=5;
{
int i=10;
System.out.println(i);
}
}
}
On compiling this program you will see following error messages:
i is already defined in main(java.lang.String[])
The reason is that i in the inner block hides i of the outer block which is not allowed in Java.
The following program will compile successfully though local variable i has multiple declarations. The reason is that both the blocks in which i is declared are at the same level.
class ScopeDemo1{
public static void main(String args[]){
for(int i=0;i<5;i++){
System.out.println(i);
}
for(int i=0;i<7;i++){
System.out.println(i);
}
}
}
A local variable comes into existence when the code of the block/method containing the declaration is executed and the declaration is encountered during execution. The variable exists only till the flow of control reaches to the end of the block/method containing it.
One important scope rule in Java that a local variable in some inner block can not hide the variable of the same name in the outer block. This is allowed in C++ and the reference to outer block variables is resolved using scope resolution operator but it is not allowed in Java.
Example: The following program will not compile.
class ScopeDemo{
public static void main(String args[]){
int i=5;
{
int i=10;
System.out.println(i);
}
}
}
On compiling this program you will see following error messages:
i is already defined in main(java.lang.String[])
The reason is that i in the inner block hides i of the outer block which is not allowed in Java.
The following program will compile successfully though local variable i has multiple declarations. The reason is that both the blocks in which i is declared are at the same level.
class ScopeDemo1{
public static void main(String args[]){
for(int i=0;i<5;i++){
System.out.println(i);
}
for(int i=0;i<7;i++){
System.out.println(i);
}
}
}