Java Random Class: Usage & Examples
The Random class in Java is used to generate pseudo-random numbers. Random numbers can be generated using an instance object of the Random class, with commonly used methods including:
- retrieve the next boolean value
- Generate the next integer.
- return the next long value
- generate a random floating point number
- return the next pseudorandom, uniformly distributed double value
- Generate the next random bytes and store them in the specified byte array.
Here is a simple example demonstrating how to use the Random class to generate random integers.
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
Random random = new Random();
int randomInt = random.nextInt(100); // 生成一个0到99之间的随机整数
System.out.println("Random integer: " + randomInt);
}
}
It is important to note that random numbers generated by the Random class are pseudo-random, meaning they are generated based on a seed value. If the same seed value is used, the generated random number sequence will be the same. You can set the seed value using the setSeed(long seed) method.