In Java, we cannot declare a variable in the same scope with the other variable which has the same name:
int someInteger = 3;
...
int someInteger = 13;
Syntax error, doesn't compile. However, if we put it inside a loop:
for (int i = 0; i < 10; i++) {
int someInteger = 3;
}
Generates no error, works very well. We are basicly declaring the same variable. What is the reason? What is the logic that I don't know/understand behind this?
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.
It's not a problem to define a variable within a loop. In fact, it's good practice, since identifiers should be confined to the smallest possible scope. What's bad is to assign a variable within a loop if you could just as well assign it once before the loop runs.
If a variable is declared inside a loop, JavaScript will allocate fresh memory for it in each iteration, even if older allocations will still consume memory. While this might be acceptable for variables of scalar data types, it may allocate a lot of memory for SCFile variables, or huge arrays or objects.
This is excellent practice. By creating variables inside loops, you ensure their scope is restricted to inside the loop. It cannot be referenced nor called outside of the loop.
Think of this way, after each loop, the scope is "destroyed", and the variable is gone. In the next loop, a new scope is created, and the variable can be declared again in that scope.
You can also do this, for the similar reason
{
int someInteger = 3;
}
{
int someInteger = 13;
}
By the way, Java does not allow local variable shadowing, which might be inconvenient
int x = 3;
{
int x = 13; // error!
}
Consumer<Integer> consumer = (x)->print(x); // ERROR!
// lambda parameter is treated like local variable
Runnable r = ()->{ int x; ... } // ERROR
// lambda body is treated like local block
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