Java – Random Long, Float, Integer and Double

1. Generate an Unbounded Long

Let’s start with generating a Long:

@Test
public void givenUsingPlainJava_whenGeneratingRandomLongUnbounded_thenCorrect() {
    long generatedLong = new Random().nextLong();
}

2. Generate a Long Within a Range

2.1. Random Long With Plain Java

Next – let’s look at creating a random bounded Long – that is, a Long value within a given range or interval:

@Test
public void givenUsingPlainJava_whenGeneratingRandomLongBounded_thenCorrect() {
    long leftLimit = 1L;
    long rightLimit = 10L;
    long generatedLong = leftLimit + (long) (Math.random() * (rightLimit - leftLimit));
}

2.2. Random Long With Apache Commons Math

Let’s take a look at generating the random Long with a cleaner API and Commons Math:

@Test
public void givenUsingApacheCommons_whenGeneratingRandomLongBounded_thenCorrect() {
    long leftLimit = 10L;
    long rightLimit = 100L;
    long generatedLong = new RandomDataGenerator().nextLong(leftLimit, rightLimit);
}

3. Generate an Unbounded Integer

Let’s move right on to generating a random Integer with no bounds:

@Test
public void givenUsingPlainJava_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
    int generatedInteger = new Random().nextInt();
}

As you can see, it’s pretty close to generating a long.

4. Generate an Integer Within a Range

4.1. Random Integer With Plain Java

Next – a random integer within a given range:

@Test
public void givenUsingPlainJava_whenGeneratingRandomIntegerBounded_thenCorrect() {
    int leftLimit = 1;
    int rightLimit = 10;
    int generatedInteger = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit));
}

4.2. Random Integer With Commons Math

And the same with Common Math:

@Test
public void givenUsingApache_whenGeneratingRandomIntegerBounded_thenCorrect() {
    int leftLimit = 1;
    int rightLimit = 10;
    int generatedInteger = new RandomDataGenerator().nextInt(leftLimit, rightLimit);
}

5. Generate an Unbounded Float

Now, let’s go over generating random floats – first unbounded:

@Test
public void givenUsingPlainJava_whenGeneratingRandomFloatUnbouned_thenCorrect() {
    float generatedFloat = new Random().nextFloat();
}

6. Generate a Float Within a Range

6.1. Random Float With Plain Java

And a bounded random float:

@Test
public void givenUsingPlainJava_whenGeneratingRandomFloatBouned_thenCorrect() {
    float leftLimit = 1F;
    float rightLimit = 10F;
    float generatedFloat = leftLimit + new Random().nextFloat() * (rightLimit - leftLimit);
}

6.2. Random Float With Commons Math

Now – a bounded random float with Commons Math:

@Test
public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() {
    float leftLimit = 1F;
    float rightLimit = 10F;
    float randomFloat = new RandomDataGenerator().getRandomGenerator().nextFloat();
    float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit);
}

7. Generate an Unbounded Double

7.1. Random Unbounded Double With Plain Java

Finally – we’re going to generate random double values – first, with the Java Math API:

@Test
public void givenUsingPlainJava_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
    double generatedDouble = Math.random();
}

7.2. Random Unbounded Double With Commons Math

As well as a random double value with the Apache Commons Math library:

@Test
public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
    double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble();
}

8. Generate a Double Within a Range

8.1. Random Bounded Double With Plain Java

In this example, let’s take a look at a random double generated within an interval – with Java:

@Test
public void givenUsingPlainJava_whenGeneratingRandomDoubleBounded_thenCorrect() {
    double leftLimit = 1D;
    double rightLimit = 10D;
    double generatedDouble = leftLimit + new Random().nextDouble() * (rightLimit - leftLimit);
}

8.2. Random Bounded Double With Commons Math

And lastly – a random double within an interval, using the Apache Commons Math library:

@Test
public void givenUsingApache_whenGeneratingRandomDoubleBounded_thenCorrect() {
    double leftLimit = 1D;
    double rightLimit = 100D;
    double generatedDouble = new RandomDataGenerator().nextUniform(leftLimit, rightLimit);
}

And there you have it – quick and to the point examples of how to generate both unbounded and bounded values for the most common numerical primitives in Java.

9. Conclusion

This tutorial illustrated how we could generate random numbers either bound or unbound, using different techniques and libraries.

As always, the implementation of all of these examples and snippets can be found in the GitHub project. This is a Maven-based project so it should be easy to import and run.

Related posts:

Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
HTTP Authentification and CGI/Servlet
Java Program to Implement Hash Tables Chaining with Binary Trees
Java Program to Implement Ternary Heap
Java Program to Find Location of a Point Placed in Three Dimensions Using K-D Trees
Concatenating Strings In Java
Một số nguyên tắc, định luật trong lập trình
Getting Started with Stream Processing with Spring Cloud Data Flow
A Guide to JUnit 5 Extensions
Generating Random Dates in Java
Send email with SMTPS (eg. Google GMail)
Luồng Daemon (Daemon Thread) trong Java
Xây dựng ứng dụng Client-Server với Socket trong Java
Java Program to do a Depth First Search/Traversal on a graph non-recursively
Java Program for Topological Sorting in Graphs
Java Program to Implement the Alexander Bogomolny’s UnOrdered Permutation Algorithm for Elements Fro...
How to Return 404 with Spring WebFlux
Introduction to Spring Method Security
Spring MVC and the @ModelAttribute Annotation
Java Program to Implement Floyd-Warshall Algorithm
Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph
Spring WebFlux Filters
Java Convenience Factory Methods for Collections
Java Program to Solve a Matching Problem for a Given Specific Case
Java Program to Emulate N Dice Roller
Java Program to Perform Stooge Sort
Spring Boot - Rest Controller Unit Test
Iterating over Enum Values in Java
How to Get All Dates Between Two Dates?
Java 8 – Powerful Comparison with Lambdas
Get the workstation name or IP