Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-declaring variables inside loops in Java

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?

like image 968
Haggra Avatar asked Jun 16 '15 02:06

Haggra


People also ask

Can we declare variables inside for loop in Java?

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.

Can a variable be declared inside a loop?

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.

What happens if we declare variable in loop?

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.

Is it better to declare a variable inside or outside a for loop?

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.


1 Answers

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
like image 77
ZhongYu Avatar answered Sep 18 '22 18:09

ZhongYu