Home and Learn: Games Programming Course

Random Numbers in Java - nextInt

There are a few ways to get a random number in Java. If all you want is a quick random number, then you can use this:

import java.util.Random;

Random rand = new Random();
int randomValue = rand.nextInt(10);

So, you import the Random class from java.util. You create a new Random object. Use nextInt after your random object and type a number between the round brackets of this method. The code above has a value of 10. This gets you a random number between 0 and 9. So, one less than the number you type between the round brackets.

If you want a number between two values, say 1 and 10, then do this:

int maxValue = 11;
int minValue = 1;

int randomValue = rand.nextInt(maxValue - minValue) + 1;

This gets you a number between your minimum value and your maximum value. You add 1 at the end to get rid of the zero. If you actually want a zero, you can miss off the + 1 at the end.

Try it out in a loop:

for (int loopVal = 0; loopVal < 50; loopVal++) {

int randomValue = rand.nextInt(maxValue - minValue) + 1;



Using ThreadLocalRandom to get a Random Number

Another way to get a random number is with ThreadLocalRandom. You need this import first:

import java.util.concurrent.ThreadLocalRandom;

Then you can use nextInt again:

int randomValue = ThreadLocalRandom.current().nextInt(0, 26);

By using ThreadLocalRandom, you can just type your lower number and your higher number between the round brackets, separated by a comma. No need to use max - min + 1, which can be confusing. (The 0, 26 gets you a random number between 0 and 25. So your second number between the round brackets of nextInt should be 1 more than what you need. So, for example, if you wanted a dice throw, the numbers would 1, 7.

Here's a program that uses random numbers to generate a random string of alphanumeric characters. This can be used to generate things like files names or passwords. It also uses the substring and concat methods.

String randomString = "";
int randomCharactersLength = 10;

for (int init = 1; init <= randomCharactersLength; init++) {

int randomValue = ThreadLocalRandom.current().nextInt(0, alphaNumeric.length());
String ranChar = alphaNumeric.substring(randomValue, randomValue + 1);
randomString = randomString.concat(ranChar);


If you want a more sophisticated version of this, here's some source code:

Java Code to get a random string - main method

Java Code to get a random string - Class

The program can be used and adapted as you see fit. If you improve the code, or add features to it, we'd love to hear from you.

In the next lesson, we'll move back to more beginner-friendly java lessons as we take a look at error handling.

<-- Inheritance | Java Error Handling -->

Back to the Java Contents Page

All Home and Learn Courses

Email us: enquiry at homeandlearn.co.uk