Mayank Madhav
Mayank Madhav

Reputation: 499

how does declaring of variables in a loop statement work in java

public class Test1{
    public static void main(String[] args){
        int x = 3;
        do {
            int y = 1;
            System.out.print(y++ + " ");
            x--;
        } while(x >= 0);
    }
}

In above code, local variable y is in scope for the block of do while statement. This is valid for all the iterations of the loop. So why does java not throw an error "Variable Y is already defined" for subsequent iterations after the first one, as we are redeclaring the same variable in each iteration?

Upvotes: 3

Views: 97

Answers (4)

Suresh
Suresh

Reputation: 1601

On every loop iteration, you are freshly declaring the variable y and instantiating it with value 1. Loop doesn't bother the status of the variable y down the line as the variable y is getting declared every time at the starting of the loop. So it just ignores the previous status and starts afresh as y=1 on every loop iteration.

Upvotes: 0

QBrute
QBrute

Reputation: 4535

If you unroll your loop, your code looks basically like this:

{
    int y=1; 
    System.out.print(y++ + " ");
}
{
    int y=1; 
    System.out.print(y++ + " ");
}
{
    int y=1; 
    System.out.print(y++ + " ");
}
{
    int y=1; 
    System.out.print(y++ + " ");
}

Each y has its own scope, i.e. they only exist inside their enclosing braces. So four different variables are created and 1 1 1 1 should be printed.

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

So why does java not throw an error "Variable Y is already defined" for subsequent iterations after the first one, as we are redeclaring the same variable in each iteration?

The variable y die once the iteration end and a new y gets declared in next iteration.

So if you iterate 3 times, each time a new y gets declared and 3 times died.

       do {
            int y = 1; // created
            System.out.print(y++ + " ");
            x--;
           // going to die here as the scope of the block ending here
      } while(x >= 0);

Upvotes: 1

Kayaman
Kayaman

Reputation: 73558

The variable x is in scope for all iterations of the loop, the variable y is in scope for each iteration of the loop separately.

When execution goes outside of the { } braces, y goes out of scope (and vanishes). So when while(x >= 0) is evaluated, y is not in scope. You can test that by trying to use y in the condition, you'll see an error telling you there's no y variable declared.

Upvotes: 1

Related Questions