Detailed explanation of System/Random/SecureRandom of Java random numbers

This series is: Learn Java from scratch, created exclusively for senior Java teachers of Qianfeng Education

Committed to explaining clearly the relevant knowledge points of Java learning for everyone, including rich code cases and explanations. If you feel that it is helpful to everyone, you can [click to follow] and continue to follow up~

At the end of the article, there is a summary of the key points of this article! Regarding technical issues, you are also welcome to communicate with us!

foreword

When we solve practical problems, in addition to often needing to operate on numbers, dates, and times, sometimes we need to set up the system and generate some random numbers.

So how do we meet these needs? Next, we will take you to learn about several other commonly used classes in Java , including System, Random, SecureRandom, etc.


The full text is about [4000] words, no nonsense, just pure dry goods that allow you to learn techniques and understand principles! This article has a wealth of cases and pictures, so that you can better understand and use the technical concepts in the article, and can bring you enough enlightening thinking...

1. System class

1 Introduction

SystemThe class is located in the java.lang package, which represents the running platform of the current Java program, and many attributes and control methods at the system level are placed in this class.

Since the construction method of this class is privateyes, we cannot directly create objects of this class through new. The System class provides some static variables and static methods, allowing us to call these class variables and class methods directly through the System class. In the System class, although there are quite a lot of static variables and methods, for us, we only need to remember some commonly used ones.

1.1 Commonly used static variables

The static variables commonly used in the System class are as follows:

● PrintStream out: standard output stream;

● InputStream in: standard input stream;

● PrintStream err: standard error output stream;

1.2 Commonly used static methods

The commonly used static methods in the System class are as follows:

● currentTimeMillis(): returns the current computer time;

● exit(): Terminate the currently running Java virtual machine;

● gc(): request the system to perform garbage collection to complete the garbage removal in the memory;

● getProperty(): Get the value corresponding to the property named key in the system;

● arraycopy(): perform array copy, that is, copy an array from the specified source array.

Next, we will give you a brief introduction to the basic use of the above static variables and static methods .

2. Use of static variables

First, let's take a look at how to use several commonly used static variables in the System class.

2.1 out

The out static variable belongs to PrintStreamthe type, which is the standard output stream in the System class, and is used to receive the data to be output. The data content in out is usually output to the display, or an output target specified by the user. In fact, out is not unfamiliar to us. It can be said that it is often used in our previous cases, especially the print method in out, which we have been using recently. But we have to make it clear that print is a method of the PrintStream stream, not a method of the System class.

//输出字符串不换行
System.out.print("Hello World");

//输出字符串并换行
System.out.println("Hello World");

2.2 in

The in static variable belongs to InputStreamthe type, which is the standard input stream in the System class, and is used to receive the input data. in usually corresponds to keyboard input, or another input source specified by the user. In the previous case, we also briefly used the in constant, but it was not used as frequently as the out.
Please add a picture description

In the above case, System.in.read()the statement can read a character, and the read() method is InputStreama method owned by the class. The variable c must be of type int instead of char, otherwise the precision may be lost and the compilation may fail. In addition, the above program will not output normally if the input is Chinese characters. If we want to output Chinese characters normally, we need to declare System.in as an instance of InputStreamReader type. for example

InputStreamReader in=new InputStreamReader(System.in,"GB2312")At this time, the complete Unicode code can be read in to display normal Chinese characters.

2.3 err

The err static variable belongs to PrintStreamthe type, which is the standard error output stream in the System class, and is used to receive the data to be output. The data content in err is usually output to the display, or an output target specified by the user. Its usage is the same as System.out, except that it can output error information without providing parameters, and it can also be used to output other information specified by the user, including the value of some variables.

//err的用法
System.err.println();

//输出指定的内容
System.err.println("错误信息");

The above static variables are very simple, just remember their usage.

3. Use of static methods

Next, let me tell you about the usage of several commonly used static methods in the System class .

3.1 currentTimeMillis() method

currentTimeMillis()The method is used to return the timestamp of the current computer. The time format is the time of the current computer and GMT time (Greenwich Mean Time). The number of milliseconds elapsed since 0:00:00 on January 1, 1970. We generally use it to Execution time of the test program. By calling currentTimeMillis()the method, we can get a long integer number, which is the current time expressed in difference. In fact, currentTimeMillis()we have explained the method in detail in the previous article, so I won't go into details here.

long time = System.currentTimeMillis();

3.2 exit() method

The exit() method is used to terminate the currently running Java virtual machine, that is, it can be used to exit the program. This method requires an integer status parameter, 0 means normal exit, non-zero means abnormal exit. We use this method to realize the exit function of the program in the graphical interface programming. The usage of this method is as follows:

public class Demo01 {
    
    
	public static void main(String[] args) {
    
    
		//exit的用法
		try {
    
    
            //睡眠5秒
			Thread.sleep(5000);
			//5秒后正常退出程序
			System.exit(0);
		} catch (InterruptedException e) {
    
    
			e.printStackTrace();
		}
	}
}

3.3 gc() method

The gc() method is used to request the active garbage collection of the system to complete the garbage removal in the memory. But whether the system will immediately recycle these garbage depends on the specific implementation of the garbage collection algorithm in the system and the specific conditions of the system when it is executed. Generally, we will not actively call this method during development, and sometimes calling it may not be effective.

//主动进行垃圾回收
System.gc();

3.4 getProperty() method

getProperty()The method can obtain some corresponding attribute values ​​in the system according to the specified key. The common attribute names and their attributes in the system are shown in the following table:

image.png

public class Demo03 {
    
    

	public static void main(String[] args) {
    
    
		//getProperty的用法
		
		//获取java版本
		String version = System.getProperty("java.version");
		System.out.println("Java版本:"+version);
		
		//获取java安装目录
		String home = System.getProperty("java.home");
		System.out.println("Java目录:"+home);
		
		//系统名称
        String name = System.getProperty("os.name");
        System.out.println("操作系统名称:"+name);
        
        //用户名称
        String user = System.getProperty("user.name");
        System.out.println("当前用户名称:"+user);
	}

}

3.5 arraycopy()

arraycopy()The method is used for array copying. An array can be copied from the specified source array. The copying will start from the specified position and end at the specified position of the target array. arraycopy()The method generally has 5 parameters, where src represents the source array, srcPos represents the starting position copied from the source array, dest represents the target array, destPos represents the starting position of the target array to be copied to, and length represents the number of copies .

public class Demo04 {
    
    

	public static void main(String[] args) {
    
    
		//arraycopy的用法
		
		//源数组
		char[] srcArray = {
    
    'A','B','C','D'};
		//目标数组
        char[] destArray = {
    
    '1','2','3','4','5'};
        
        //进行数组复制
        System.arraycopy(srcArray,1,destArray,1,2);
        
        System.out.println("遍历源数组:");
        for(int i = 0;i < srcArray.length;i++) {
    
    
            System.out.println("源数组中的每个元素:"+srcArray[i]);
        }
        
        System.out.println("遍历目标数组:");
        for(int j = 0;j < destArray.length;j++) {
    
    
            System.out.println("新数组中的每个元素:"+destArray[j]);
        }
	}

}

Two. Random random class

1 Introduction

When we are developing, in addition to operating some fixed numbers, sometimes we also need to operate some uncertain random numbers. Java provides us with two methods of generating random numbers within a specified range:

● Use Random class: Pseudo-random number class, used to create pseudo-random numbers. The so-called pseudo-random number means that as long as we give an initial seed, the sequence of random numbers generated is exactly the same;

● Call the random() method of the Math class: Math.random() is actually calling the Random class inside, which is also a pseudo-random number, but we cannot specify the seed.

The Random class provides us with a relatively rich method of generating random numbers, such as nextInt()、nextLong()、nextFloat()、nextDouble()the etc. method. These methods can generate boolean、int、long、float、bytearrays and double type random numbers, which is better than the random() method. The random() method can only generate double type random numbers between 0 and 1.

Moreover, all the methods provided by the Random class generate random numbers that are uniformly distributed, which means that the probability of generating numbers inside the interval is equal. The Random class is located in the java.util package. This class has the following two commonly used construction methods:

● Random(): By default, the timestamp of the current system is used as the seed number, and the Random object is constructed using the seed number.

● Random(long seed): Create a new random number generator using a single long type parameter.

2. Commonly used API methods

In the Random class, there are some commonly used API methods for us to manipulate random numbers:

method illustrate
boolean nextBoolean() Generate a random boolean value with equal probability of generating true and false values
double nextDouble() Generate a random double value between [0,1.0), including 0 but not including 1.0
int nextlnt() Generate a random int value, which is in the range of int, that is -231~231-1. If you need to generate an int value in the specified interval, you need to perform certain mathematical transformations
int nextlnt(int n) Generates a random int value in [0,n), including 0 and not including n. If you want to generate an int value in the specified interval, you also need to perform certain mathematical transformations
void setSeed(long seed) Resets the number of seeds in the Random object. The Random object after setting the seed number is the same as the Random object created by using the new keyword with the same seed number
long nextLong() Returns a random long integer number
boolean nextBoolean() returns a random boolean value
float nextFloat() returns a random floating point number
double nextDouble() Returns a random double value

3. Basic usage

Next, we use a case to explain to you how to use the above method.

import java.util.Random;

public class Demo07 {
    
    

	public static void main(String[] args) {
    
    
		// 随机类生成随机数
		Random r = new Random();
		
		// 生成[0,1.0]区间的小数
		double d1 = r.nextDouble();
		System.out.println("d1="+d1);
		
		// 生成[0,10.0]区间的小数
		double d2 = r.nextDouble() * 10;
		System.out.println("d2="+d2);
		
		// 生成[0,10]区间的整数
		int i1 = r.nextInt(10);
		System.out.println("i1="+i1);
		
		// 生成[0,25)区间的整数
		int i2 = r.nextInt(30) - 5;
		System.out.println("i2="+i2);
		
		// 生成一个随机长整型值
		long l1 = r.nextLong();
		System.out.println("l1="+l1);
		
		// 生成一个随机布尔型值
		boolean b1 = r.nextBoolean();
		System.out.println("b1="+b1);
		
		// 生成一个随机浮点型值
		float f1 = r.nextFloat();
		System.out.println("f1="+f1);
	}

}

But from the above case, we will find that the random numbers generated each time may be different, and do not reflect the characteristics of pseudo-random numbers. Why is this? In fact, this is because when we create a Random instance, if no seed is given, the default is to use the current timestamp of the system as the seed. So every time you run it, the seed is different, so the sequence of pseudo-random numbers you get is different. If we specify a fixed seed when creating a Random instance, we get a completely deterministic sequence of random numbers.

3. SecureRandom class

1 Introduction

I told you before that Random is a kind of pseudo-random number. At this time, some friends asked, is there a true random number class?

Of course there are!

SecureRandom is a true random number!

From the principle point of view, SecureRandomthe RNG (Random Number Generator, random number generation) algorithm is used internally to generate an unpredictable and secure random number. But at the bottom of the JDK, there are actually many different implementations of SecureRandom. Some use a secure random seed plus a pseudo-random number algorithm to generate secure random numbers, and some use a true random number generator to generate random numbers. In actual use, we can give priority to obtaining a high-strength secure random number generator; if not provided, then use a normal-level secure random number generator. But in either case, we cannot specify a seed.

Because this seed is "entropy" generated by various random events such as CPU thermal noise, bytes read and written to disk, network traffic, etc., it is theoretically impossible for this seed to be repeated. This also ensures the security of SecureRandom, so the final generated random number is a secure true random number.

Especially in cryptography, secure random numbers are very important. If we use insecure pseudo-random numbers, all encryption systems will be broken. Therefore, in order to ensure the security of the system, we try to use SecureRandom to generate secure random numbers.

2. Basic use

SecureRandomIt provides us with random number generation methods nextBoolean()、nextBytes()、nextDouble()、nextFloat()、nextInt()such as , as shown in the following figure:

Next, we will use a case to see how to generate a secure random number.

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;

public class Demo05 {
    
    

	public static void main(String[] args) {
    
    
		//SecureRandom真随机数的用法
		
		SecureRandom sr = null;
        try {
    
    
        	//获取高强度安全随机数生成器实例对象
            sr = SecureRandom.getInstanceStrong(); 
        } catch (NoSuchAlgorithmException e) {
    
    
        	//处理异常,获取普通的安全随机数生成器
            sr = new SecureRandom(); 
        }
        
        //生成16个随机数
        byte[] buffer = new byte[16];
        //用安全随机数填充buffer
        sr.nextBytes(buffer); 
        System.out.println("随机数="+Arrays.toString(buffer));
        
        //生成100以内的随机整数
        int nextInt = sr.nextInt(100);
        System.out.println("随机数="+nextInt);
	}

}

4. Conclusion

So far, we have introduced classes related to system classes, pseudo-random numbers, true random numbers, etc., so that we have introduced some common classes during development. Today's focus is on:

● System: represents the running platform of the current Java program, and many attributes and control methods at the system level are placed in this class;

● Random: generate pseudo-random numbers;

● SecureRandom: Generate secure true random numbers.

Guess you like

Origin blog.csdn.net/GUDUzhongliang/article/details/130677754
Recommended