Generating Random Numbers in a Range in Java

1. Overview

In this tutorial, we’ll explore different ways of generating random numbers within a range.

2. Generating Random Numbers in a Range

2.1. Math.random

Math.random gives a random double value that is greater than or equal to 0.0 and less than 1.0.

Let’s use the Math.random method to generate a random number in a given range [min, max):

public int getRandomNumber(int min, int max) {
    return (int) ((Math.random() * (max - min)) + min);
}

Why does that work? Let’s look at what happens when Math.random returns 0.0, which is the lowest possible output:

0.0 * (max - min) + min => min

So, the lowest number we can get is min.

Since 1.0 is the exclusive upper bound of Math.random, this is what we get:

1.0 * (max - min) + min => max - min + min => max

Therefore, the exclusive upper bound of our method’s return is max.

In the next section, we’ll see this same pattern repeated with Random#nextInt.

2.2. java.util.Random.nextInt

We can also use an instance of java.util.Random to do the same.

Let’s make use of the java.util.Random.nextInt method to get a random number:

public int getRandomNumberUsingNextInt(int min, int max) {
    Random random = new Random();
    return random.nextInt(max - min) + min;
}

The min parameter (the origin) is inclusive, whereas the upper bound max is exclusive.

2.3. java.util.Random.ints

The java.util.Random.ints method returns an IntStream of random integers.

So, we can utilize the java.util.Random.ints method and return a random number:

public int getRandomNumberUsingInts(int min, int max) {
    Random random = new Random();
    return random.ints(min, max)
      .findFirst()
      .getAsInt();
}

Here as well, the specified origin min is inclusive, and max is exclusive.

3. Conclusion

In this article, we saw alternative ways of generating random numbers within a range.

Code snippets, as always, can be found over on GitHub.

Related posts:

Java Program to Perform Finite State Automaton based Search
Java Program to Find the Nearest Neighbor Using K-D Tree Search
Hướng dẫn Java Design Pattern – Chain of Responsibility
Java Program to Describe the Representation of Graph using Incidence Matrix
Guide to the Synchronized Keyword in Java
Fixing 401s with CORS Preflights and Spring Security
Giới thiệu về Stream API trong Java 8
Java Program to Find the Median of two Sorted Arrays using Binary Search Approach
Error Handling for REST with Spring
HttpClient 4 – Send Custom Cookie
Spring Boot - Servlet Filter
Spring NoSuchBeanDefinitionException
Login For a Spring Web App – Error Handling and Localization
Jackson JSON Views
Java Program to Implement Karatsuba Multiplication Algorithm
Java Program to Implement Heap’s Algorithm for Permutation of N Numbers
Java Program to Implement Min Hash
Removing Elements from Java Collections
Convert Character Array to String in Java
4 tính chất của lập trình hướng đối tượng trong Java
Recommended Package Structure of a Spring Boot Project
Ép kiểu trong Java (Type casting)
Java Program to Implement Hash Tables with Quadratic Probing
Limiting Query Results with JPA and Spring Data JPA
Java Program to Implement Triply Linked List
Java Program to Perform Complex Number Multiplication
Guide to UUID in Java
Build a REST API with Spring and Java Config
Servlet 3 Async Support with Spring MVC and Spring Security
Introduction to Netflix Archaius with Spring Cloud
Spring Boot Integration Testing with Embedded MongoDB
Tạo ứng dụng Java RESTful Client với thư viện Retrofit