Core Java

Generate Random Integers – nextInt Java Example

In this post, we feature a comprehensive article about how to Generate Random Integers, using a nextInt Java Example.

1. Introduction

Java JDK has provided the following utility classes to generate random integers over time: The java.util.Random class from version 1.0, java.util.concurrent.ThreadLocalRandom class from version 1.7, and java.util.SplittableRandom class from version 1.8. These classes provide the nextInt method to generate a random integer and ints method to generate a stream of random integers. Here are the syntax details:

   /**
	 *  
	 * @return the next pseudorandom, uniformly distributed int value from this
	 *         random number generator's sequence.
	 */
	int nextInt();

	/**
	 *  
	 * @param bound the upper bound (exclusive).
	 * @return a pseudorandom, uniformly distributed int value between 0 (inclusive)
	 *         and the specified value (exclusive), drawn from this random number
	 *         generator's sequence.
	 */
	int nextInt(int bound);

	/**
	 * 
	 * @param origin the least value returned
	 * @param bound  the upper bound (exclusive).
	 * @return a pseudorandom int value between the specified origin (inclusive) and
	 *         the specified bound (exclusive).
	 */
	int nextInt(int origin, int bound);

	/**
	 * 
	 * @return an effectively unlimited stream of pseudorandom int values.
	 */
	IntStream ints();

	/**
	 * 
	 * @param randomNumberOrigin the least value returned
	 * @param randomNumberBound  the upper bound (exclusive)
	 * @return an effectively unlimited stream of pseudorandom int values, each
	 *         conforming to the given origin (inclusive) and bound (exclusive).
	 */
	IntStream ints(int randomNumberOrigin, int randomNumberBound);

	/**
	 * 
	 * @param streamSize the number of values to generate
	 * @return a stream producing the given streamSize number of pseudorandom int
	 *         values.
	 */
	IntStream ints(long streamSize);

	/**
	 * 
	 * @param streamSize         the number of values to generate
	 * @param randomNumberOrigin the least value returned
	 * @param randomNumberBound  the upper bound (exclusive)
	 * @return a stream producing the given streamSize number of pseudorandom int
	 *         values, each conforming to the given origin (inclusive) and bound
	 *         (exclusive).
	 */
	IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound);

In this example, I will create a Java application to generate a singular and a set of random integers.

2. Technologies used

The example code in this article was built and run using:

  • Java 1.8.101
  • Eclipse Oxygen

3. nextInt Java Project

In this step, I will create a Java project which contains a Java application to generate random integers.

3.1 Random

The java.util.Random class has provided the nextInt() method since version 1.0. It has added the nextInt(int bound) since version 1.2. Both methods generate a random integer number. It has added the ints method with four signatures to generate a stream of random integers since version 1.8.

In this step, I will create a With_Random class to generate a singular and a stream of random integers.

With_Random.java

package org.jcg.zheng.random;

import java.util.Random;

import org.jcg.zheng.RandomIntegerBase;
import org.jcg.zheng.SignatureType;

public class With_Random extends RandomIntegerBase {

    private Random random = new Random();

    @Override
    protected SignatureType[] getNextIntSignatures() {
        return new SignatureType[] { SignatureType.NONE, SignatureType.HAS_BOUNDARY };
    }

    @Override
    protected SignatureType[] getIntsSignatures() {
        return new SignatureType[] { SignatureType.NONE, SignatureType.HAS_BOUNDARY,
            SignatureType.HAS_BOUNDARY_AND_ORIGIN, SignatureType.HAS_SIZE };
    }

    @Override
    protected int getRandomInteger(SignatureType methodSignatureType) {
        int randomNum = -1;
        switch (methodSignatureType) {
        case NONE:
            randomNum = random.nextInt();
            break;
        case HAS_BOUNDARY:
            randomNum = random.nextInt(boundary);
            break;
        case HAS_BOUNDARY_AND_ORIGIN:
            break;
        case HAS_SIZE:
            break;
        default:
            break;
        }
        return randomNum;
    }

    @Override
    protected int[] getRandomInts(SignatureType methodSignatureType) {
        int[] randomNums = null;

        switch (methodSignatureType) {
        case NONE:
            randomNums = random.ints().limit(streamSize).toArray();
            break;
        case HAS_BOUNDARY:
            randomNums = random.ints(origin, boundary).limit(streamSize).toArray();
            break;
        case HAS_BOUNDARY_AND_ORIGIN:
            randomNums = random.ints(streamSize, origin, boundary).toArray();
            break;
        case HAS_SIZE:
            randomNums = random.ints(streamSize).toArray();
            break;
        default:
            break;
        }
        return randomNums;
    }

}

3.2 ThreadLocalRandom

The Java 7 java.util.concurrent.ThreadLocalRandom class provides the nextInt method to generate a random integer. It has added the ints method since version 1.8.

In this step, I will create a With_ThreadLocalRandom class to generate a singular and a stream of random integers.

With_ThreadLocalRandom.java

package org.jcg.zheng.random;

import java.util.concurrent.ThreadLocalRandom;

import org.jcg.zheng.RandomIntegerBase;
import org.jcg.zheng.SignatureType;

public class With_ThreadLocalRandom extends RandomIntegerBase {

    @Override
    protected int getRandomInteger(SignatureType methodSignatureType) {
        int randomNum = -1;
        switch (methodSignatureType) {
        case NONE:
            randomNum = ThreadLocalRandom.current().nextInt();
            break;
        case HAS_BOUNDARY:
            randomNum = ThreadLocalRandom.current().nextInt(boundary);
            break;
        case HAS_BOUNDARY_AND_ORIGIN:
            randomNum = ThreadLocalRandom.current().nextInt(origin, boundary);
            break;
        case HAS_SIZE:
            break;
        default:
            break;
        }
        return randomNum;
    }

    @Override
    protected int[] getRandomInts(SignatureType methodSignatureType) {
        int[] randomNums = null;

        switch (methodSignatureType) {
        case NONE:
            randomNums = ThreadLocalRandom.current().ints().limit(streamSize).toArray();
            break;
        case HAS_BOUNDARY:
            randomNums = ThreadLocalRandom.current().ints(origin, boundary).limit(streamSize)
                    .toArray();
            break;
        case HAS_BOUNDARY_AND_ORIGIN:
            randomNums = ThreadLocalRandom.current().ints(streamSize, origin, boundary).toArray();
            break;
        case HAS_SIZE:
            randomNums = ThreadLocalRandom.current().ints(streamSize).toArray();
            break;
        default:
            break;
        }
        return randomNums;
    }

    @Override
    protected SignatureType[] getNextIntSignatures() {
        return new SignatureType[] { SignatureType.NONE, SignatureType.HAS_BOUNDARY,
            SignatureType.HAS_BOUNDARY_AND_ORIGIN };
    }

    @Override
    protected SignatureType[] getIntsSignatures() {
        return new SignatureType[] { SignatureType.NONE, SignatureType.HAS_BOUNDARY,
            SignatureType.HAS_BOUNDARY_AND_ORIGIN, SignatureType.HAS_SIZE };
    }

}

3.3 SplittableRandom

The Java 8 java.util.SpilttaleRandom class provides the nextInt and ints methods to return a singular and stream of random integers.

In this step, I will create a With_SplittableRandom class to generate a singular and a stream of random integers.

With_SplittableRandom.java

package org.jcg.zheng.random;

import java.util.SplittableRandom;

import org.jcg.zheng.RandomIntegerBase;
import org.jcg.zheng.SignatureType;

public class With_SplittableRandom extends RandomIntegerBase {

    SplittableRandom random = new SplittableRandom();

    @Override
    protected int getRandomInteger(SignatureType methodSignatureType) {
        int randomNum = -1;
        switch (methodSignatureType) {
        case NONE:
            randomNum = random.nextInt();
            break;
        case HAS_BOUNDARY:
            randomNum = random.nextInt(boundary);
            break;
        case HAS_BOUNDARY_AND_ORIGIN:
            randomNum = random.nextInt(origin, boundary);
            break;
        case HAS_SIZE:
            break;
        default:
            break;
        }
        return randomNum;
    }

    @Override
    protected int[] getRandomInts(SignatureType methodSignatureType) {
        int[] randomNums = null;

        switch (methodSignatureType) {
        case NONE:
            randomNums = random.ints().limit(streamSize).toArray();
            break;
        case HAS_BOUNDARY:
            randomNums = random.ints(origin, boundary).limit(streamSize).toArray();
            break;
        case HAS_BOUNDARY_AND_ORIGIN:
            randomNums = random.ints(streamSize, origin, boundary).toArray();
            break;
        case HAS_SIZE:
            randomNums = random.ints(streamSize).toArray();
            break;
        default:
            break;
        }
        return randomNums;
    }

    @Override
    protected SignatureType[] getNextIntSignatures() {
        return new SignatureType[] { SignatureType.NONE, SignatureType.HAS_BOUNDARY,
            SignatureType.HAS_BOUNDARY_AND_ORIGIN };
    }

    @Override
    protected SignatureType[] getIntsSignatures() {
        return new SignatureType[] { SignatureType.NONE, SignatureType.HAS_BOUNDARY,
            SignatureType.HAS_BOUNDARY_AND_ORIGIN, SignatureType.HAS_SIZE };
    }

}

3.4 SignatureType

In this step, I will create an enum class to define the signature type used in both the nextInt and ints methods.

SignatureType.java

package org.jcg.zheng;

public enum SignatureType {

    NONE, HAS_BOUNDARY, HAS_BOUNDARY_AND_ORIGIN, HAS_SIZE;
}

3.5 RandomIntegerBase

In this step, I will create an abstract class – RandomIntegerBase which will print out a random integer and a stream of random integers.

RandomIntegerBase.java

package org.jcg.zheng;

import java.util.Arrays;

public abstract class RandomIntegerBase {

    protected int boundary = 10;
    protected int origin = 0;
    protected int streamSize = 5;

    protected abstract int getRandomInteger(SignatureType signatureType);

    protected abstract int[] getRandomInts(SignatureType methodSignature);

    protected abstract SignatureType[] getNextIntSignatures();

    protected abstract SignatureType[] getIntsSignatures();

    protected void randomInteger() {
        for (SignatureType methodSignature : getNextIntSignatures()) {
            System.out.println("\n\twith signature: " + methodSignature.name());
            for (int i = origin; i < boundary; i++) {
                System.out.print(getRandomInteger(methodSignature) + "\t");
            }
        }
    }

    protected void randomIntegerArray() {
        for (SignatureType methodSignature : getIntsSignatures()) {
            System.out.println("\n\twith signature: " + methodSignature.name());
            Arrays.stream(getRandomInts(methodSignature))
                    .forEach(r -> System.out.print(r + "\t"));
        }
    }

}

3.6 Random Application

In this step, I will create a Java application which generates a singular and stream of random integers via With_Random, With_ThreadLocalRandom, and With_SplittableRandom

RandomApplication.java

package org.jcg.zheng;

import org.jcg.zheng.random.With_Random;
import org.jcg.zheng.random.With_SplittableRandom;
import org.jcg.zheng.random.With_ThreadLocalRandom;

public class RandomApplication {

    public static void main(String[] args) {

        With_Random randomNextInt = new With_Random();
        System.out.println("\nGenerate a random integer with Random.nextInt ");
        randomNextInt.randomInteger();
        System.out.println("\n\nGenerate a stream of integers with Random.ints ");
        randomNextInt.randomIntegerArray();

        With_SplittableRandom splittableRandom = new With_SplittableRandom();
        System.out.println("\n\nGenerate a random integer with SplittableRandom.nextInt ");
        splittableRandom.randomInteger();
        System.out.println("\n\nGenerate a stream of integers with SplittableRandom.ints ");
        splittableRandom.randomIntegerArray();

        With_ThreadLocalRandom localRandom = new With_ThreadLocalRandom();
        System.out.println("\n\nGenerate a random integer with ThreadLocalRandom.nextInt ");
        localRandom.randomInteger();
        System.out.println("\n\nGenerate a stream of integers with ThreadLocalRandom.ints ");
        localRandom.randomIntegerArray();

    }
}

4. Demo

In this step, I will execute the Java application and capture the output here.

Output

Generate a random integer with Random.nextInt 

	with signature: NONE
179849868	-771773519	1892153862	124664961	-1895403012	141282545	-1493084355	1670606027	1751879145	-768408023	
	with signature: HAS_BOUNDARY
4	3	7	2	1	2	7	0	2	0	

Generate a stream of integers with Random.ints 

	with signature: NONE
-1363796045	-671530137	2126004220	1016481001	1360997539	
	with signature: HAS_BOUNDARY
7	6	2	3	9	
	with signature: HAS_BOUNDARY_AND_ORIGIN
4	8	8	5	3	
	with signature: HAS_SIZE
1831271225	246082158	516693645	885371310	-9188024	

Generate a random integer with SplittableRandom.nextInt 

	with signature: NONE
-897391379	-951196627	737090001	-276183059	1704021189	-849413691	-172179000	-671726879	454421318	-1594567429	
	with signature: HAS_BOUNDARY
6	9	5	7	7	8	1	4	3	0	
	with signature: HAS_BOUNDARY_AND_ORIGIN
1	3	7	9	3	0	9	3	5	4	

Generate a stream of integers with SplittableRandom.ints 

	with signature: NONE
588209218	441521627	1098193051	1197157131	-494320254	
	with signature: HAS_BOUNDARY
2	0	7	1	1	
	with signature: HAS_BOUNDARY_AND_ORIGIN
8	1	7	1	3	
	with signature: HAS_SIZE
-1543455550	-380186012	1606492274	1222040699	-1731352416	

Generate a random integer with ThreadLocalRandom.nextInt 

	with signature: NONE
-30273511	1846483373	-1498368933	-118921871	-885411060	1857994968	-1324473783	-1369182777	-1765721674	-544309699	
	with signature: HAS_BOUNDARY
3	4	1	6	7	1	5	9	4	0	
	with signature: HAS_BOUNDARY_AND_ORIGIN
9	6	0	9	9	7	1	3	5	2	

Generate a stream of integers with ThreadLocalRandom.ints 

	with signature: NONE
-514365201	899029711	-1145536651	73157318	173374212	
	with signature: HAS_BOUNDARY
6	8	1	2	5	
	with signature: HAS_BOUNDARY_AND_ORIGIN
4	1	5	4	0	
	with signature: HAS_SIZE
-1508604967	-514052218	1468970462	-67974228	-1327434922	

5. nextInt Java Example – Summary

In this example, I demonstrated how Java provides three utility classes to generate random numbers over time. The JDK8 java.util.SplittableRandom class is the best class to generate random integers.

6. Download the Source Code

This nextInt Java Example consists of an Eclipse project to generate a random integer and a stream of random integers.

Download
You can download the full source code of this example here: Generate Random Integers – nextInt Java Example

Last updated on Sept. 10, 2019

Mary Zheng

Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button