Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.Start your free trial
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,365 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?