How to generate random numbers in Java

Key takeaways:

  • java.util.Random generates random values in various formats.

  • Math.random() produces a random double in the interval from 0 (inclusive) to 1 (exclusive). Ideal for straightforward random number generation and scaling to other ranges.

  • ThreadLocalRandom provides thread-safe random number generation for integers, doubles, and booleans. It is best suited for multithreaded applications requiring efficient randomization.

  • random.ints() provides an infinite stream of random integers within a specified range, allowing flexible and powerful random number generation in Java streams.

  • SecureRandom produces cryptographically secure random numbers. It is essential for applications needing high-level security, such as encryption and secure token generation.

  • Each method caters to different needs, ranging from basic randomization to cryptographic security, allowing developers to select the appropriate tool for their specific use cases.

Random number generation

A random number is an arbitrary number that does not follow any specific pattern. John von Neumann introduced the first method in 1946 for pseudo-random numberPseudo-random numbers are developed by a mathematical formula or an algorithm in which a series of numbers is produced from an initial seed value. The algorithms are deterministic, so if the ‘seed’ value is used again, the sequence of random numbers will be similar each time. generation known as middle-square method.

Random number generation can help us in gaming, such as controlling dice rolls OTPOne-time password codes, and in cryptography for generating secure keys and encryption. Java provides several built-in ways to create random numbers, and Java random numbers can be of various types, such as integers and doubles of the specified range. In this Answer, we’ll explore five different methods for Java random number generators.

  • Using the java.util.Random class
  • Using the Math.random() method
  • Using the ThreadLocalRandom class
  • Using the Random.ints() method
  • Using the SecureRandom class

Method 1: Using the java.util.Random class

To use the Random class to generate random numbers, follow the steps below:

  1. Import the java.util.Random class.
  2. Make the instance of the Random class, i.e., Random rand = new Random().
  3. Ue some of the following Random class methods on rand object:
    • nextInt(upperbound): This generates random integers in the range 0 to upperbound-1.
    • nextFloat(): This generates a float between 0.0 and 1.0.
    • nextDouble(): This generates a double between 0.0 and 1.0.
import java.util.Random;
class GenerateRandom {
public static void main( String args[] ) {
// Instance of the random class
Random rand = new Random();
// Setting the upper bound to generate the
// random numbers in specific range
int upperbound = 25;
// Generating random numbers from 0 - 24
// using nextInt()
int int_random = rand.nextInt(upperbound);
// Generating random numbers using nextDouble
// in 0.0 and 1.0 range
double double_random = rand.nextDouble();
// Generating random numbers using nextFloat
// in 0.0 and 1.0 range
float float_random = rand.nextFloat();
// Printing the generated random numbers
System.out.println("Random integer value from 0 to " + (upperbound-1) + " : " + int_random);
System.out.println("Random float value between 0.0 and 1.0 : " + float_random);
System.out.println("Random double value between 0.0 and 1.0 : " + double_random);
}
}

This class also allows us to generate long and boolean-type random numbers using the nextLong() and nextBoolean() methods, respectively.

Method 2: Using the Math.random() method

The Java Math.random() method generates a random double-precision floating-point number between 0. 0 (inclusive) and 1.0 (exclusive).

class GenerateRandom {
public static void main( String args[] ) {
// Generate random number
System.out.println("Random number: " + Math.random());
}
}

For generating random numbers within a range using the Math.random(), follow the steps below:

  1. Declare the minimum value of the range.
  2. Declare the maximum value of the range.
  3. Use the formula Math.floor(Math.random() * (max - min + 1) + min) to generate values, with the min and the max value inclusive.

Note: This method can only be used if we need an integer or float of a specified random number range.

class GenerateRandom {
public static void main( String args[] ) {
int min = 50; // Minimum value of range
int max = 100; // Maximum value of range
// Print the min and max
System.out.println("Random value in int from "+ min + " to " + max + ":");
// Generate random int value from min to max
int random_int = (int)Math.floor(Math.random() * (max - min + 1) + min);
// Printing the generated random numbers
System.out.println(random_int);
}
}

Method 3: Using the ThreadLocalRandom class

ThreadLocalRandom class in Java provides the mechanism to generate pseudorandom numbers in a safe thread model by providing each thread with its random number generator so that there is no conflict between the threads in the multithreaded environment. Additionally, this class uses an internally generated seed value that cannot be modified.

To use the ThreadLocalRandom class, follow the steps below:

  1. Import the java.util.concurrent.ThreadLocalRandom class.
  2. Use some of the following ThreadLocalRandom class methods:
    • To generate a random integer, use ThreadLocalRandom.current().nextInt().
    • To generate a random double-precision floating-point number, use ThreadLocalRandom.current().nextDouble().
    • To generate a random boolean value, use ThreadLocalRandom.current().nextBoolean().
import java.util.concurrent.ThreadLocalRandom;
class GenerateRandom {
public static void main( String args[] ) {
// Generate Java random integers
int int_random = ThreadLocalRandom.current().nextInt();
// Print Java random integers
System.out.println("Random Integers: " + int_random);
// Generate Java random doubles
double double_rand = ThreadLocalRandom.current().nextDouble();
// Print random doubles
System.out.println("Random Doubles: " + double_rand);
// Generate Java random boolean
boolean boolean_rand = ThreadLocalRandom.current().nextBoolean();
// Print Java random boolean
System.out.println("Random Booleans: " + boolean_rand);
}
}

Method 4: Using the random.ints() method

The ints is an instance method of the Random class that is used to generate a stream of random integers in Java 8. There are four different variants of this method, namely:

  • ints(long streamSize): Generates a stream of pseudorandom random integers with the specified number of elements.

  • ints(): Produces an infinite stream of random integers without any specific bounds or limits.

  • ints(long streamSize, int randomNumberOrigin, int randomNumberBound): Generates a stream of pseudorandom integers with the specified number of elements. The value of each random integer is between a lower bound randomNumberOrigin (included) and an upper bound randomNumberBound (excluded).

  • ints(int randomNumberOrigin, int randomNumberBound): Generates an infinite stream of pseudorandom integers that adhere to the provided lower bound (included) and upper bound (excluded).

import java.util.Random;
public class Main{
public static void main(String[] args) {
//create an object of the Random class
Random random=new Random();
// stream size
long streamSize = 10;
// using ints generate stream of random ints
System.out.println("Random stream:");
random.ints(streamSize).forEach(System.out::println);
System.out.println("Range bound random stream:");
random.ints(streamSize, 5, 11).forEach(System.out::println);
}
}

Method 5: Using the SecureRandom class

The Random class has a higher chance of repeating numbers during random number generation. But, the SecureRandom class mitigates the issue by allowing us to generate random numbers that are cryptographically strong using the following steps:

  1. Import SecureRandom using java.security.SecureRandom.
  2. Make the instance of the SecureRandom class using new SecureRandom().
  3. Use some of the following SecureRandom class methods on rand object:
    • nextInt(): This generates the next pseudorandom int value from the sequence of numbers maintained by the SecureRandom object.
    • nextInt(upperbound): This generates random numbers in the range 0 to upperbound-1.
    • nextFloat(): This generates a float between 0.0 and 1.0.
    • nextDouble(): This generates a double between 0.0 and 1.0.

Note: An article in the Nature magazine explains that for a pseudorandom number generator to be cryptographically secure, it must display two characteristics:

  • Pass statistical randomness tests: The numbers they generate need to look random and unpredictable.

  • Stay secure under attack: If a part of the initial or running state of the program becomes available due to an attack, a malicious actor should not be able to guess the other values based on the available information.

If a random number generator meets the above conditions, it would generate random sequences that have a high entropy, zero correlation, and no repetition of subsequences.

import java.security.SecureRandom;
class GenerateRandom {
public static void main( String args[] ) {
// Instance of the SecureRandom class
SecureRandom rand = new SecureRandom();
// Setting the upper bound to generate
// the random numbers between the specific range
int upperbound = 1000;
// Generating Java random numbers from 0 - 999
// using nextInt()
int int_random1 = rand.nextInt(upperbound);
int int_random2 = rand.nextInt(upperbound);
// Generating Java random numbers using nextDouble
// in 0.0 and 1.0 range
double double_random = rand.nextDouble();
// Generating Java random numbers using nextFloat
// in 0.0 and 1.0 range
float float_random = rand.nextFloat();
// Printing the generated Java random numbers
System.out.println("Random integer value from 0 to " + (upperbound - 1) + " : " + int_random1);
System.out.println("Random integer value from 0 to " + (upperbound - 1) + " : " + int_random2);
System.out.println("Random float value between 0.0 and 1.0 : " + float_random);
System.out.println("Random double value between 0.0 and 1.0 : " + double_random);
}
}

Selecting a suitable random number generation method

Each method meets different needs, from general randomization to high-security applications, allowing developers to choose the most suitable method based on their requirements. Choosing the right method for generating random numbers is key to ensure robustness in your applications, as Donald Knuth once said:

Note: Random numbers should not be generated with a method chosen at random.

Quiz!

1

Which class is preferred for generating random numbers in cryptographic applications?

A)

java.util.Random

B)

SecureRandom

C)

ThreadLocalRandom

D)

None of the above

Question 1 of 30 attempted

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to generate random number between 1 to 10 in Java

class GenerateRandom {
    public static void main( String args[] ) {
      int min = 1; // Minimum value of range
      int max = 10; // Maximum value of range
      // Print the min and max  
      System.out.println("Random value in int from "+ min + " to " + max + ":");
      // Generate random int value from min to max
      int random_int = (int)Math.floor(Math.random() * (max - min + 1) + min);
      // Printing the generated random numbers
      System.out.println(random_int);
    }
}

What is Mersenne Twister?

Mersenne Twister is general-purpose pseudorandom number generator. It was developed in 1997 by Makoto and Matsumoto.


What are true random numbers?

Unlike pseudo-random numbers that are generated using deterministic algorithms and whose value depends on the choice of initial seed number, true random numbers are unpredictable because they are generated using a process with no identifiable pattern. They rely on external physical factors to ensure randomness, such as:

  • Thermal noise
  • Radioactive decay
  • Keystroke time intervals

How to generate a 10-digit random number in Java

import java.util.Random;

class GenerateRandom {
    public static void main(String[] args) {
        Random tenrand = new Random();
        String randomNumber = String.format("%010d", tenrand.nextInt(1000000000)); //Generates a random integer between 0 and 999999999 (inclusive), which is up to 10 digits long.
        System.out.println(randomNumber);
    }
}

How to generate random string in JavaScript

The JavaScript Math.random() function can be used to generate a string of randomly selected characters.

Check out our Answer, How to generate a string of randomly chosen characters in JS, to apply Math.random() method to generate random string.


What does RNG stand for?

RNG stands for random number generator.


What are the applications of random numbers?

The following are some of the key applications of random numbers:

  • Cryptography
  • Computer simulation
  • Gaming
  • Algorithm initialization
  • Monte Carlo methods

What is a seed value?

The seed value is a number that is used by the generator to initialize the program state and generate the pseudorandom numbers.


What is random password generator?

A random password generator is a tool or method for generating random passwords. It depends on a random number selector or picker to select random characters to ensure passwords are unpredictable and secure.


What is a linear congruential generator (LCG)?

The linear congruential generator is a method for generating a random number. The LCG logic based on a discontinuous piecewise linear equation. It generates a sequence of randomized numbers using a mathematical equation.

Check out our detailed Answer on Pseudo random numbers using the Linear Congruential Generator.


What is linear feedback shift register (LFSR)?

Linear feedback shift register is a bit generator. It is used to generate pseudorandom numbers by shifting bits and applying XOR operations.


What is a seed selection?

Seed selection is the process by which we decide which seed value to use to initialize a random number generator. Using the same seed allows you to recreate the same random sequence, which is useful for experimentation and running simulations, and also for testing and debugging purposes.


What is random number generation hardware?

Random number generation hardware generates truly random numbers by using some of the following unpredictable physical phenomena:

  • Thermal noise
  • Radioactive decay

What are Monte Carlo methods?

Monte Carlo methods include a variety of computational algorithms that depends on repeated random sampling to derive numerical results.


What are some common UI elements for random number generation in apps?

The following are some of the common UI elements for random number generation in apps:

  • Number picker wheel
  • Dice roller

Copyright ©2024 Educative, Inc. All rights reserved