Question: Explain the purpose and usage of the Random class in Java. Provide an example of using the Random class to generate a random number between 1 and 10.
Answer: The Random class in Java is used to generate pseudo-random numbers. Its purpose is to provide a way to produce random numbers that can be used for various purposes, such as generating random positions in a game, randomizing data for testing, and more.
To use the Random class, you first need to create an instance of it:
import java.util.Random;
Random random = new Random();
Once you have created an instance of the Random class, you can use its methods to generate random numbers. One commonly used method is nextInt()
, which generates a random integer. To generate a random number between 1 and 10, you can use the following code:
int randomNumber = random.nextInt(10) + 1;
In this example, nextInt(10)
will generate a random integer between 0 (inclusive) and 10 (exclusive). Adding 1 to the result shifts the range to be between 1 and 10.
Explanation:
Random
class from the java.util
package to have access to its functionality.Random
class using Random random = new Random();
.int randomNumber = random.nextInt(10) + 1;
.nextInt(10)
method produces a random integer between 0 (inclusive) and 10 (exclusive). Adding 1 to the result adjusts the range to be between 1 and 10.This is how the Random class can be used to generate random numbers within a specified range in Java.