[Java] How does Java generate random numbers?

foreword

When we learn the basics of Java, we know that random numbers can be generated, which can add a little bit of fun to our boring learning. This article introduces Java random numbers.

1. Introduction to the Random class

Use the Random tool class in Java to generate random numbers. This class exists under the java.util package and exists in JDK1.0 version. The word Random itself means random, random, and arbitrary. Random is an ordinary class, so when using it, you need to create a Random object and call the methods it provides.

public class Random implements java.io.Serializable {
    
    }

The Random class provides many methods, as shown in the figure below:
insert image description here

Second, the Random class generates random numbers

1. Generate random numbers

In Java, you can use the java.util.Random class to generate random numbers. The Random class provides several methods to generate different kinds of random numbers, such as nextInt(), nextDouble(), and so on.
Here we demonstrate how to generate a random integer between 0 and 9:

import java.util.Random;

public class RandomTest {
    
    
    public static void main(String[] args) {
    
    
        // 创建Random实例
        Random random = new Random();
        // 生成0到9之间的随机数
        int randomNum = random.nextInt(10); 
        System.out.println(randomNum);
    }
}

In the above sample code, a Random object is first created, and then a random integer between 0 and 9 is generated using the nextInt() method, and the result is printed to the console.

2. nextInt() method

The nextInt(int bound) method is an instance method of the Random class that generates a random integer between 0 (inclusive) and the specified value (exclusive).
We previously used the nextInt(int bound) method to generate a random number between 0-9:

Random random = new Random();
int randomNum = random.nextInt(10);
System.out.println(randomNum);

The code uses the default constructor of the Random class to create a random number generator object, and then calls the nextInt(int bound) method to generate a random integer between 0 (including 0) and 10 (not including 10) (referred to multiple times and bold), and finally store the result in the randomNum variable and print it to the console.

The implementation principle of this method is to generate random numbers according to the internal state of the random number generator. If the specified bound parameter is a positive number, the random number generated is an integer between 0 and bound. If bound is negative or 0, an IllegalArgumentException will be thrown. It should be noted that the generated random number is a pseudo-random number, which is actually a deterministic function, but its performance looks random.

For the Random.nextInt(int bound) method, special attention should be paid to the value range of the bound parameter. If the generated random number is not between 0 and bound, it may have a negative impact on some applications, for example, it may cause loopholes in cryptography applications. Therefore, when using this method, it is necessary to carefully check the value range of the bound parameter and restrict it appropriately.
Then in addition to the nextInt() method, there are nextLong(), nextBoolean(), nextFloat(), nextDouble(), etc.

3. Usage scenarios

The Java random number generator can be used in many scenarios. For example, in game development, monsters, maps, props, etc. can be randomly generated; if passwords are involved, random numbers can be generated during the encryption process, such as when generating keys Salt values ​​with random lengths; tests and drills can also be performed: random number generators can be used to generate test data, observation data, etc.;

In short, random numbers are widely used, and any scene that needs to simulate randomness can use the random number generator provided by Java to generate random numbers.

Most of us have choice difficulties, such as not knowing what to have for lunch? Very headache! Then let God decide! We use Java random numbers to randomly draw or determine lunch.

import java.util.Random;

public class RandomLunch {
    
    
    public static void main(String[] args) {
    
    
        String[] foods = {
    
    "汉堡", "炸鸡", "披萨", "烤肉", "牛肉面", "米线", "酸菜鱼", "煲仔饭", "火锅", "小笼包"}; //可以选择的午餐品种
        Random random = new Random();
        int index = random.nextInt(foods.length); // 生成0到可选菜品数量之间的一个随机整数
        String lunch = foods[index]; // 根据随机数选定菜品
        System.out.println("午饭吃" + lunch);
    }
}

In the above code, an array is first defined to store the lunch varieties that can be selected. Then use the java.util.Random class to create a random number generator object, and use the nextInt(int bound) method to generate a random number between 0 and the number of optional dishes. Finally, use this random number to select a dish from the dishes array, store it in the string variable lunch, and output the lunch selection result.

In actual development, similar codes can be integrated into a system that provides a menu selection function, so that friends in the office can quickly decide on lunch.

4. Official Tips

Instances of java.util.Random are thread-safe. However, concurrent use of the same java.util.Random instance across threads may experience contention, resulting in degraded performance. Consider using java.util.concurrent.ThreadLocalRandom in multithreaded designs.
Instances of java.util.Random are not cryptographically secure. Consider using java.security.SecureRandom to obtain a cryptographically secure pseudo-random number generator for use in security-sensitive applications.

Summarize

There are still many usage scenarios of Java random numbers, so we need to master them. This article briefly introduces the Random number class that Java generates random numbers.

Guess you like

Origin blog.csdn.net/u011397981/article/details/132353833