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

Java Java Data Structures Efficiency! Implement Chooser UI

Dylan Carter
Dylan Carter
4,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 Schleifer
Grigorij Schleifer
10,365 Points

Yep !

Member variables in a classβ€”these are called fields. This are non-local variables

1 Answer

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hi 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
Dylan Carter
4,780 Points

it does besides instance variables, what are those?

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Instance 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
Dylan Carter
4,780 Points

oh so the same thing as the member variables?