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) Improving Our Code Adding More Colors

Ragesh Kanagaraj
Ragesh Kanagaraj
3,637 Points

Random class object get created everytime the user clicks the button. Is it a good practice ?

In one of the QUIZ questions , creating objects withing a method will cause the obj to get created when ever that method is called there by crashing the application.

But in the above code shown in the video, object of Random class is created within a method facts(). When ever the user clicks the button that method will get called and the object get created everytime. Wont this crash the app ? or is it a good practice to do so ?

1 Answer

Hello,

While it is true that everytime the method is called, a new object will be created, it is also true that each time the method ends the object will no longer be used and so will, typically, be garbage collected freeing up the memory. So by creating it in the method where we need it, we're actually helping to limit the scope of our variables and also lower the memory needed by our application.

Ragesh Kanagaraj
Ragesh Kanagaraj
3,637 Points

So is it advisable to create object withing the methods ?

Honestly, it really depends on what you're trying to optimize as to which method is the best. For example, if you're having to draw something using an onDraw method, you're not going to want to be garbage collecting as often, holding the objects used there with a bigger scope would likely be a better situation to do. However, if you're only using the object once in a great while, you might want to reduce the memory that you are using overall and thus define it with a smaller scope(aka in the method) so that it can get garbage collected when you are done.