Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it allowed to declare a variable in a for loop?

Tags:

java

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

like image 705
Roe Avatar asked Nov 27 '18 10:11

Roe


People also ask

Why declare a variable in a for loop?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.

What are the reasons for declaring variables in a program?

Variables are used to store information to be referenced and manipulated in a computer program. They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information.

Can you put a for loop in a variable?

Yes, you can use it but it's quite confusing. The most important thing is the scope of local variable inside the loop.


2 Answers

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.

like image 139
Eran Avatar answered Oct 13 '22 01:10

Eran


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
like image 37
Ashish Patil Avatar answered Oct 13 '22 01:10

Ashish Patil