5

I'm a student currently learning java at school (Beginner) and I was wondering about something.
I have a basic knowledge of coding from other languages and I don't understand a particular thing in Java.
If I were to declare a variable (let's use an int as a example) inside a loop wouldn't that mean that I'm declaring the same variable over and over?

This is what I mean:

for (int i = 0; i < 3; i ++) {
    int x = 5;
}

Isn't it the same thing as this? (This one is incorrect)

int x = 5;
int x = 5;

If not, Why? Both of them are / declare the same variable twice, though I know that in loops the variable is local and can't be used outside of the loop (I don't think thats the issue though).
I also know that you can't declare the same variable twice so I don't understand how the first example is legal.

Thanks so much :D

This Question has be solved, Thanks to everyone that helped :D

Wolfaloo
  • 94
  • 1
  • 13
Roe
  • 59
  • 2

8 Answers8

10
for (int i = 0; i < 3; i ++) {
    int x = 5;
}

is actually equivalent to:

{
    int x = 5;
}
{
    int x = 5;
}
{
    int x = 5;
}

Each x variable is declared in a separate scope.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • So its like having the same rule that apply to loops that you cant use variables that are declared inside the loop outside of the loop? so its basically doing the same thing for each one of these brackets? – Roe Nov 27 '18 at 10:44
  • @Roe each variable declared within the loop's body exists only within the scope of the current iteration of the loop. – Eran Nov 27 '18 at 10:46
3

scope is in one iteration, after end of loop, scope doesn't exist.

simple example:

for (int i = 0; i < 4; i++) {
            int x = 0;
            System.out.println(x);
            x++;
        }


output:
0
0
0
0
Ashish Patil
  • 4,428
  • 1
  • 15
  • 36
0

In each iteration of your loop, a variable x of type int is "created" and assigned the value 5.
As soon as the iteration finishes, this variable is "destroyed" and by the next iteration the cycle starts again.
So there are never 2 variables by the same name in the same scope.

forpas
  • 160,666
  • 10
  • 38
  • 76
0

Lets take 1st expression

for (int i = 0; i < 3; i ++) {
        int x = 5;
 }

Here scope of variable x is within the loop block

So each time a new loop starts scope is already released.

So there is no error

If you change the same code to like this

for (int i = 0; i < 3; i ++) {
        int x = 5;
        int x = 5;
 }

Now there will be an error as x is already in scope and you are again trying to define.

This is allowed

for (int i = 0; i < 3; i ++) {
    int x = 5;
    x = 5;
}

as you are resigning the variable

MyTwoCents
  • 7,284
  • 3
  • 24
  • 52
  • I understood what you said except for this part: "So each time a new loop starts scope is already released. So there is no error" – Roe Nov 27 '18 at 10:46
0

the variable x has life time that begin at when you declare it and ends at the closing block for the for-loop.

in other word x is born when you enter new iteration and dies when iteration ends (or dies at the end of block that contains it)

Ali Faris
  • 17,754
  • 10
  • 45
  • 70
0

It is generally good practice to make the variable avayable to the smallest context possible: if you only need it inside the loop declaring it inside it is considered good practice.

For the loop declaration case, your value gets reassigned basically.

This might proove interesting to read and add further informations on the matter: Declaring variables inside or outside of a loop

This is also a legal thing to do

for (int i= 0; i < 1000000000; i++) { 
    int j = i & i+1 ;
}

These are legal because at the end of the loop the declared variable "ceases to exists" in order to be reformed the next execution

Wolfaloo
  • 94
  • 1
  • 13
0

Well, when you declare int x = 5; inside the loop, you're declaring it in a local scope (which starts from its { to }) so the variable x will be destroyed when it gets out of its scope which means for the next loop iteration, it's a new x so that's why you can do that and since it's destroyed when it gets out of scope it can't be used/seen outside the scope.

Hengly
  • 121
  • 1
  • 5
0

Just to clarify the concept of allowing variable declaration in a loop, I've declared the same variable again in the loop, and got error "A local variable or function named 'x' is already defined in this scope"(I wrote this code in C#, but you should get similar message in Java): same variable in a loop

If I declare the variable in a different scope outside the loop, there will be no error as the scope is different:

        for (int i = 0; i < 3; i++)
        {
            int x = 5;                
        }

        {
            int x = 5;
        }

If we couldn't declare variables in loop, we had to write the following code:

        {
            int x = 5;
            // Do something with x=5
        }
        {
            int x = 5;
            // Do something with x=5
        }
        {
            int x = 5;
            // Do something with x=5
        }

But with loop, we can just write the following instead of writing 3 scopes:

        for (int i = 0; i < 3; i++)
        {
            int x = 5;
            // Do something three times with x=5
        }