Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,363 Points

Yep !

Member variables in a class—these are called fields. This are non-local variables

1 Answer

Grigorij Schleifer
Grigorij Schleifer
10,363 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,363 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?