Welcome to the Treehouse Community
Looking to learn something new?
Dylan Carter4,780 Points
Variables inside of loops scope?
any variable declared inside a loop on has scope for that loop, and not the method, correct?
could not find a simple answer to this googling.
Grigorij Schleifer10,363 Points
If you need a variable to be only available for a particular task then better not to declare it as global (same as outside of the loop/method). But the variable is only visible inside the scope of the mothod/loop.
So If the variable that controls a loop is not needed outside of the loop, it's best to declare the variable in the initialization expression (Java Docs) of that loop. Declaring variables inside a loop limits their life span and reduces errors.
Another point is that creating a local variable may reduce memory usage. When you exit a method or a loop, the local variables inside disappear. Only instance variables maintain their value over method/loop calls and use more memory recouces.
Does it make sense?