Random Number Generator in Java

Filed Under: Java
Random Number Generation Java

Today we will look at how to generate a random number in Java. Sometimes we need to generate random numbers in Java programs, for example, a dice game or to generate a random key id for encryption, etc.

Random Number Generator in Java

random number generator java

There are many ways to generate a random number in java.

  1. java.util.Random class can be used to create random numbers. It provides several methods to generate random integer, long, double etc.
  2. We can also use Math.random() to generate a double. This method internally uses Java Random class.
  3. java.util.concurrent.ThreadLocalRandom class should be used to generate random number in multithreaded environment. This class is part of Java Concurrent package and introduced in Java 1.7. This class has methods similar to Java Random class.
  4. java.security.SecureRandom can be used to generate random number with strong security. This class provides a cryptographically strong random number generator. However, it’s slow in processing. So depending on your application requirements, you should decide whether to use it or not.

Java Random Number Generator

Let’s look at some examples to generate a random number in java. Later on, we will also look at ThreadLocalRandom and SecureRandom example program.

Generate Random integer


Random random = new Random();

int rand = random.nextInt();

Yes, it’s that simple to generate random int in java. When we create the Random instance, it generates a long seed value that is used in all the nextXXX method calls. We can set this seed value in the program, however, it’s not required in most of the cases.


//set the long seed value using Random constructor
Random random = new Random(123456789);

//set long seed value using setter method
Random random1 = new Random();
random1.setSeed(1234567890);

Java Random number between 1 and 10

Sometimes we have to generate a random number between a range, for example in a dice game possible values can be between 1 to 6 only. Below is the code showing how to generate a random number between 1 and 10 inclusive.


Random random = new Random();
int rand = 0;
while (true){
    rand = random.nextInt(11);
    if(rand !=0) break;
}
System.out.println(rand);

Note that the argument in the nextInt(int x) is excluded, so we have to provide argument as 11. Also, 0 is included in the generated random number, so we have to keep calling nextInt method until we get a value between 1 and 10. You can extend the above code to generate the random number within any given range.

Generate Random double

We can use Math.random() or Random class nextDouble method to generate random double number in java.


Random random = new Random();

double d = random.nextDouble();

double d1 = Math.random();

Generate Random float


Random random = new Random();

float f = random.nextFloat();

Generate Random long


Random random = new Random();

long l = random.nextLong();

Generate Random boolean


Random random = new Random();

boolean flag = random.nextBoolean();

Generate Random byte array

We can also generate random bytes and place them into a user-supplied byte array using Random class. The number of random bytes produced is equal to the length of the byte array.


Random random = new Random();

byte[] randomByteArray = new byte[5];

random.nextBytes(randomByteArray);

System.out.println(Arrays.toString(randomByteArray)); // sample output [-70, -57, 74, 99, -78]

ThreadLocalRandom Example to generate random number in multithreaded environment

Here is a simple example showing ThreadLocalRandom usage in a multithreaded environment.


package com.journaldev.randomnumber;

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

public class ThreadLocalRandomExample {

	public static void main(String[] args) {
		Runnable runnable = new MyRunnable();

		for (int i = 0; i < 5; i++) {
			Thread t = new Thread(runnable);
			t.setName("MyRunnable-Thread-" + i);
			t.start();
		}
	}

}

class MyRunnable implements Runnable {

	@Override
	public void run() {
		String threadName = Thread.currentThread().getName();
		System.out.println(threadName + "::" + ThreadLocalRandom.current().nextInt());
	}

}

Below is a sample output of my execution of the above program.


MyRunnable-Thread-0::-1744088963
MyRunnable-Thread-3::139405798
MyRunnable-Thread-1::1403710182
MyRunnable-Thread-2::-1222080205
MyRunnable-Thread-4::-185825276

Note that we can’t set seed value for ThreadLocalRandom instance, it will throw UnsupportedOperationException.

ThreadLocalRandom example

ThreadLocalRandom class also has some extra utility methods to generate a random number within a range. For example, to generate a random number between 1 and 10, we can do it like below.


ThreadLocalRandom random = ThreadLocalRandom.current();
		
int rand = random.nextInt(1, 11);

ThreadLocalRandom also has similar methods for long and double.

SecureRandom Example

You can use SecureRandom class to generate more secure random numbers using any of the listed providers. A quick SecureRandom example code is given below. However, I have never used this class before.


Random random = new SecureRandom();

int rand = random.nextInt();

System.out.println(rand);

That’s all about how to generate a random number in java program.

You can download the example code from our GitHub Repository.

Comments

  1. Chaman Bharti says:

    Good article on Random number generation. I think you should add some example that how to create random number without using java class I mean beginner level program.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages