How to Generate Random Integers with a Range in Java

0 min read 103 words

Java comes with many different ways to generate random integers, even if you need to specify a lower and upper bound to constrain your required value for.

Option 1 – ThreadLocalRandom

Specify the min and max values:

import java.util.concurrent.ThreadLocalRandom;

int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

Option 2 – Random

Between `` (inclusive) and the specified value (exclusive):

import java.util.Random;

Random rn = new Random();
int range = maximum - minimum + 1;
int randomNum =  rn.nextInt(range) + minimum;

Option 3 – Multiple values

import java.util.Random;

Random r = new Random();
int[] fiveRandomNumbers = r.ints(5, 0, 11).toArray();
int randomNumber = r.ints(1, 0, 11).findFirst().getAsInt();
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags