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 trialmichael lee
5,179 PointsRandom randomGenerator = new Random()
what does this line of code do? I am very confused
2 Answers
Lauren Moineau
9,483 PointsOn that line of code, you are creating a new Random object (you can also say "creating a new instance of the class Random") and giving it the name of randomGenerator. You could have called it random or anything of your liking.
To create it, you use the new keyword and call the Random class constructor Random().
We need to create an instance of the Random class in order to call the methods of that class. Here, we want to use the nextInt() method.
As shown in the video, we can then call the method on that newly created Random object : randomGenerator.nextInt()
Hope that helps :)
Kevin Haube
12,265 PointsThis is called "instantiating". Random()
is a class, and for you to be able to access some or all methods, you have to create an instance of that Class. Calling a method from the Random class is done through this instance we've created named randomGenerator
!