How to Pick a Random Number in Java

Random numbers have a wide range of programming uses such as in games, encrypting data etc. Java has multiple classes for generating random numbers. Deciding which one to use depends a lot on the program requirements. Here are some of the Random generator classes and their primary purpose,

  • java.util.Random – This is the simplest implementation of pseudorandom random numbers. This is suitable for simple usage scenarios such as selecting a random game move. This class is thread safe but its performance may be an issue in multithreaded programs. This class is not cryptographically secure.
  • java.util.concurrent.ThreadLocalRandom – This is a derived class of java.util.Random and is designed for use in multithreaded programs. This class is not cryptographically secure. Use this class if you are writing a multithreaded program with random numbers generated across threads.
  • java.security.SecureRandom – This is also a derived class of java.util.Random and is designed to generate cryptographically strong random numbers. Use this class in your encryption methods.  However note that this method is much slower than other methods.

The following Java source code contains examples of using the above classes to generate random numbers in a range. Pick the function appropriate to your program as indicated above.

How to Pick a Random Number in Java

import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

// Various methods to generate random numbers in Java
public class RandomMethods {
    public static void main(String[] args) {
        System.out.println(getSimpleRandomNumber(10)); // 1 to 10
        System.out.println(getThreadSafeRandomNumber(5)); // 1 to 5
        System.out.println(getSimpleRandomNumber(1000)); // 1 to 1000
    }
    
    // Returns integer between 1 and maxValue both inclusive
    // Use this for simple uses such as a game move
    public static int getSimpleRandomNumber(int maxValue) {
        Random r = new Random();
        return r.nextInt(maxValue)+1;
    }
    
    // Returns integer between 1 and maxValue both inclusive
    // Use this in multithreaded programs
    public static int getThreadSafeRandomNumber(int maxValue) {
        ThreadLocalRandom r = ThreadLocalRandom.current();
        return r.nextInt(maxValue)+1;
    }
    
    // Returns integer between 1 and maxValue both inclusive
    // Use this in encryption methods. This is slower than other methods.
    public static int getRandomNumberForEncryption(int maxValue) {
        SecureRandom r = new SecureRandom();
        return r.nextInt(maxValue);
    }
}

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply