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 (2014) Coding the Fun Facts Properties of Arrays

Obinna Eruchalu
PLUS
Obinna Eruchalu
Courses Plus Student 534 Points

Is there any benefit to instantiating these vars/objects every time the button is clicked (as opposed to before)?

We create a new instance of the String Array and Random number generator every time we click the button. Is there any benefit to doing it this way, than to create both when the app is launched (within the onCreate function)?

1 Answer

Vivien Kuo
Vivien Kuo
4,541 Points

You can make both the string array and random number generator a member variable and generate a new number everytime the button is pressed. However, since these two objects are only used when the button is pressed, there is little benefit to doing this. It's the difference between leaving resources to hold an object for as long as the activity is running, or using the resources to instantiate a new object and destroying it each time the button is pressed. Most phones have more than the capacity to do either or, and it is mostly up to you to decide on which implementation you want. Personally, I think it makes the program easier to read when the objects are instantiated each time because the code is not used outside of the onclick method.