Let me explain doubt.
I have a int i = 9
inside main method. Now i have for loop inside same main method.Look the following example
class Test {
public static void main(String... args) throws Exception{
int i =39;
for (int i = 0; i < 10; i++) { // error:i already defined
}
}
}
For above example it is showing compile time error that i is already defined.From this error i think that scope of i declared in for condition is also outside loop.
Now see following example
class Test {
public static void main(String... args) throws Exception{
for (int i = 0; i < 10; i++) {
}
System.out.println(i); // error: cannot find symbol i
}
}
In above example it is showing error outside for loop that cannot find symbol i.
If it is not finding i declared in for loop condition.Then why it is showing i is already defined in first example
As per definition of Block
A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.
So
{ //block started
} //block ended
What ever the variables declared inside the block ,the scope restricted to that block.
A thumb rule will be scope of variable is with in {}
.
public static void main(String... args) throws Exception{
int i =39;
for (int i = 0; i < 10; i++) {
System.out.println(i); // which i ??
}
}
In the above case the compiler confuses which i it's looking for since the i
already defined and it have a scope to access in loop also.
There is already i
defined in main
method scope
public static void main(String... args) throws Exception{
for (int i = 0; i < 10; i++) {
}
System.out.println(i); // the scope ended already with in {}
}
In above case the i
scope already ended in for {}
,and outside not available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With