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

michael lee
michael lee
5,175 Points

Random randomGenerator = new Random()

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

1 Answer

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