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 trialDylan Carter
4,780 PointsVariables 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.
1 Answer
Grigorij Schleifer
10,365 PointsHi Dylan,
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?
Dylan Carter
4,780 Pointsit does besides instance variables, what are those?
Grigorij Schleifer
10,365 PointsInstance variables a declared inside (not inside a method or a loop) the class and are visible for that class and the instances of that class. So the are called instance variables.
Dylan Carter
4,780 Pointsoh so the same thing as the member variables?
Grigorij Schleifer
10,365 PointsGrigorij Schleifer
10,365 PointsYep !
Member variables in a classβthese are called fields. This are non-local variables