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

Android Build a Simple Android App Improving Our Code Adding More Colors

Creating an object over and over again

In the lectures all code lines where object was created were moved outside of the method. Why do you create object of String over and over again inside of the method? Why did you not declare it as a global variable? For example, here fact is created everytime when we call getColor() method:

public String getColor() { String fact = ""; Random randomGenerator = new Random(); int randomNumber = randomGenerator.nextInt(mColors.length); fact = mColors[randomNumber]; return fact; }

1 Answer

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hi Beksultan,

the "fact" String variable is a lokal variable. If you put this variable outside the method it will become a class variable and it will be created when you create this class, or the object of this class.

The good part of the lokal variable is, that it is only visible for the method and not for the outside world.

Does it make sense?

Grigorij