Table of contents
1.
Introduction
2.
java.util.Random Class
2.1.
Example 
2.2.
Java
3.
Math.random() Method
3.1.
Example 
3.2.
Java
4.
ThreadLocalRandom Class
4.1.
Example 
4.2.
Java
5.
Frequently Asked Questions
5.1.
Can we set a custom seed value for random number generation in Java? 
5.2.
Is there any difference in the quality of random numbers generated by different methods?
5.3.
When should we use ThreadLocalRandom over the Random class? 
6.
Conclusion
Last Updated: Jun 30, 2024
Easy

Java Random Number

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, generating random numbers is a basic program which we use in many scenarios. Whether you're creating a game, a simulation, or any other application that requires unpredictable values, Java provides several ways to generate random numbers. 

Java Random Number

In this article, we'll discuss the 3 different methods Java offers for generating random numbers & learn how to use them effectively in your code. We'll cover the java.util.Random class, the Math.random() method, & the ThreadLocalRandom class. 

java.util.Random Class

The java.util.Random class is one of the most commonly used classes for generating random numbers in Java. It provides a wide range of methods to generate random values of different data types, such as integers, doubles, booleans, & more. To use the Random class, you first need to create an instance of it. 

Here's an example:

import java.util.Random;
Random random = new Random();


Once you have an instance of the Random class, you can call various methods to generate random numbers. For example, to generate a random integer, you can use the nextInt() method:

int randomInt = random.nextInt();


This will give you a random integer between Integer.MIN_VALUE & Integer.MAX_VALUE. If you want to generate a random integer within a specific range, you can pass the upper bound as an argument to nextInt():

int randomInt = random.nextInt(100); // Generates a random integer between 0 (inclusive) & 100 (exclusive)


Similarly, you can use other methods like nextDouble(), nextLong(), nextBoolean(), etc., to generate random values of different data types.

Example 

  • Java

Java

import java.util.Random;

public class RandomExample {
public static void main(String[] args) {
Random random = new Random();

// Generating random integers
int randomInt = random.nextInt();
int randomIntRange = random.nextInt(100); // Range: 0 (inclusive) to 100 (exclusive)

// Generating random doubles
double randomDouble = random.nextDouble();

// Generating random booleans
boolean randomBoolean = random.nextBoolean();

System.out.println("Random Integer: " + randomInt);
System.out.println("Random Integer (Range): " + randomIntRange);
System.out.println("Random Double: " + randomDouble);
System.out.println("Random Boolean: " + randomBoolean);
}
}
You can also try this code with Online Java Compiler
Run Code


Output

Random Integer: 1198383132
Random Integer (Range): 41
Random Double: 0.045453200212297706
Random Boolean: false

Math.random() Method

Another way to generate random numbers in Java is by using the Math.random() method. This method is a static method of the Math class & returns a double value between 0.0 (inclusive) & 1.0 (exclusive). 

For example : 

double randomDouble = Math.random();


Since Math.random() returns a double value, you can multiply it by a desired range & cast it to an integer if needed. For example, to generate a random integer between 0 (inclusive) & 100 (exclusive), you can do the following:

int randomInt = (int) (Math.random() * 100);


One thing to keep in mind is that the Math.random() method uses a fixed seed value, which means that the sequence of random numbers generated will be the same every time you run the program. If you need more control over the seed value or want to generate different sequences of random numbers, you should use the Random class instead.

Example 

  • Java

Java

public class MathRandomExample {
public static void main(String[] args) {
// Generating random doubles
double randomDouble = Math.random();

// Generating random integers within a range
int randomIntRange = (int) (Math.random() * 100); // Range: 0 (inclusive) to 100 (exclusive)

System.out.println("Random Double: " + randomDouble);
System.out.println("Random Integer (Range): " + randomIntRange);
}
}
You can also try this code with Online Java Compiler
Run Code


Output

Random Double: 0.30783928138115846
Random Integer (Range): 38

ThreadLocalRandom Class

The ThreadLocalRandom class is a specialized random number generator introduced in Java 7. It is designed to provide random numbers in a thread-safe manner, making it suitable for use in multi-threaded environments. ThreadLocalRandom is similar to the Random class but offers better performance & scalability when used concurrently by multiple threads.

To use ThreadLocalRandom, you don't need to create an instance of it. Instead, you can directly call its static methods.

For example : 

int randomInt = ThreadLocalRandom.current().nextInt();

 

The current() method returns the ThreadLocalRandom instance associated with the current thread, & then you can call methods like nextInt(), nextDouble(), etc., similar to the Random class.

ThreadLocalRandom also provides methods to generate random numbers within a specific range. For example, to generate a random integer between 1 (inclusive) & 100 (inclusive), you can use the following code:

int randomInt = ThreadLocalRandom.current().nextInt(1, 101);

 

Note that the upper bound is exclusive, so we pass 101 to include 100 in the range.

Using ThreadLocalRandom is recommended when you have multiple threads generating random numbers concurrently, as it eliminates contention & provides better performance compared to using a shared instance of the Random class.

Example 

  • Java

Java

import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomExample {
public static void main(String[] args) {
// Generating random integers
int randomInt = ThreadLocalRandom.current().nextInt();
int randomIntRange = ThreadLocalRandom.current().nextInt(1, 101); // Range: 1 (inclusive) to 101 (exclusive)

// Generating random doubles
double randomDouble = ThreadLocalRandom.current().nextDouble();

// Generating random booleans
boolean randomBoolean = ThreadLocalRandom.current().nextBoolean();

System.out.println("Random Integer: " + randomInt);
System.out.println("Random Integer (Range): " + randomIntRange);
System.out.println("Random Double: " + randomDouble);
System.out.println("Random Boolean: " + randomBoolean);
}
}
You can also try this code with Online Java Compiler
Run Code


Output

Random Integer: 1727623638
Random Integer (Range): 68
Random Double: 0.8512023341504024
Random Boolean: true

Frequently Asked Questions

Can we set a custom seed value for random number generation in Java? 

Yes, you can set a custom seed value using the setSeed() method of the Random class or by passing the seed value to the constructor.

Is there any difference in the quality of random numbers generated by different methods?

All three methods (Random class, Math.random(), & ThreadLocalRandom) use the same underlying algorithm & provide pseudorandom numbers of similar quality.

When should we use ThreadLocalRandom over the Random class? 

ThreadLocalRandom is preferred in multi-threaded environments where multiple threads need to generate random numbers concurrently, as it provides better performance & thread safety compared to using a shared instance of the Random class.

Conclusion

In this article, we learned about three different ways to generate random numbers in Java: using the java.util.Random class, the Math.random() method, & the ThreadLocalRandom class. We discussed the usage & characteristics of each technique with the help of proper code examples to show their implementation. Random number generation is a fundamental concept in programming & is widely used in various scenarios such as simulations, games, & more.

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass