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
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.
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.
Yes, you can use it but it's quite confusing. The most important thing is the scope of local variable inside the loop.
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.
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
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