Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Math processing
Expertise: Beginner
May 5, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Random Integer Generation

How do I write a Java program that generates random numbers within limits, such as 1 to 100, or 1 to 1000?

The java.util package includes a Random class which will generate a sequence of pseudo-random numbers. Pseudo-random number sequences appear to have a random distribution, but have a definite order. Given the same seed, a pseudo-random number generator will always produce the same sequence of numbers. Therefore, you should initialize the Random class with as random a seed as possible. Using the current time as a seed is often sufficient.

However, when a pseudo-random number sequence is exhausted, it wraps around and starts again from the beginning. Consequently, for long-lived applications that generate many random numbers over time, you will want to periodically reseed your random generator.

The Random class does not provide a generic means of generating random integers within a specific range. Rather, it generates a uniformly distributed set of values between 0 and some upper bound. For doubles and floats it generates a value between 0 and 1. You can use this to generate arbitrary ranges of random integers. The following example program provides a random integer generating class that takes care of converting a random double into a random integer within a specific range. It also takes care of reseeding the random number generator after the sequence has been in use for a long time.

import java.util.*;

public final class RandomIntGenerator {
  public static final int DEFAULT_MIN_RANGE = 1;
  public static final int DEFAULT_MAX_RANGE = 100;

  int _minRange, _maxRange, _range;
  long _numCalls;
  Random _random;

  public RandomIntGenerator() {

  public RandomIntGenerator(int minRange, int maxRange) {
    _random   = new Random(System.currentTimeMillis());
    setRange(minRange, maxRange);
    _numCalls = 0;

  public void setRange(int minRange, int maxRange) {
    _minRange = minRange;
    _maxRange = maxRange;
    _range    = maxRange - minRange + 1;

  public int nextInt() {
    double d;
    d = ((double)_range)*_random.nextDouble();
    if(++_numCalls == Integer.MAX_VALUE) {
      // The pseudo-random number sequence is sufficiently
      // exhausted that it is time to switch to a new seed.
      _numCalls = 0;

    return (_minRange + (int)d);

  public static final void main(String[] args) {
    RandomIntGenerator randomInt;

    randomInt = new RandomIntGenerator();

    for(int i = RandomIntGenerator.DEFAULT_MIN_RANGE;
        i <= RandomIntGenerator.DEFAULT_MAX_RANGE; ++i)

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date