java tutorial: three ways to generate random numbers in Java

In this tutorial, I will share with you three methods of using Java built-in classes or functions to generate random numbers.

  • Method: java.lang.Math.Random
  • Class: java.util.Random
  • Class: java.util.concurrent.ThreadLocalRandom

java.lang.Math.Random

Calling the Math.Random() function can return a double value with a positive sign. The value is greater than or equal to 0.0 and less than 1.0, that is, the value range is the left-closed and right-open interval of [0.0,1.0). The return value is a pseudo-randomly selected The number is (approximately) evenly distributed in this range.

Such as the following example:

import org.junit.Test;

public class GenerateNumberTest {

    @Test
    public void testMathRandom() {
        // Generating random doubles
        System.out.println("Random doubles: " + Math.random());
        System.out.println("Random doubles: " + Math.random());
    }
}

java.util.Random

The Random class has two construction methods:

  • Random(): Creates a new random number generator.
  • Random(long seed): Creates a new random number generator using a single seed, returns the number from 0 to seed-1 .

The following example:

import org.junit.Test;
import java.util.Random;

public class GenerateNumberTest {

    @Test
    public void testUtilRandom() {
        // create instance of Random class
        Random rand = new Random();

        // Generate random integers in range 0 to 9
        for(int i = 0; i < 10; i++) {
            System.out.println(rand.nextInt(10));
        }

        // Generate Random doubles
        double nextDouble = rand.nextDouble();

        // Print random doubles
        System.out.println("Random Doubles: " + nextDouble);
    }
}

java.util.concurrent.ThreadLocalRandom

A random number generator isolated to the current thread. The ThreadLocalRandom.class is a subclass of the Random.class, which can generate random numbers of integers, doubles, Booleans, etc.


import org.junit.Test;
import java.util.concurrent.ThreadLocalRandom;

public class GenerateNumberTest {

    @Test
    public void testThreadLocalRandom() {
        for(int i = 0;i < 10;i++) {
            int nextInt = ThreadLocalRandom.current().nextInt(10);
            System.out.println(nextInt);
        }

        for(int j = 0;j < 10;j++) {
            double nextDouble = ThreadLocalRandom.current().nextDouble();
            System.out.println(nextDouble);
        }

    }
}

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *