Android Build a Simple Android App with Java Basic Android Programming Choosing a Random Fact

michael lee
michael lee
5,178 Points

Random randomGenerator = new Random()

what does this line of code do? I am very confused

2 Answers

On 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 :)

This 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!