Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of variable declared in for loop

Tags:

java

scope

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

like image 219
Prashant Shilimkar Avatar asked Sep 06 '25 02:09

Prashant Shilimkar


1 Answers

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.

like image 92
Suresh Atta Avatar answered Sep 07 '25 21:09

Suresh Atta