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:

  1. retrieve the next boolean value
  2. Generate the next integer.
  3. return the next long value
  4. generate a random floating point number
  5. return the next pseudorandom, uniformly distributed double value
  6. 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.

bannerAds