Random Class in Java Simply Explained

Posted by Marta on March 28, 2021 Viewed 3861 times

Card image cap

In Java, you can generate random numbers using the Random class . The random class could be seen as a number generator.

There are many scenarios where this functionality is useful. For instance, you might want to generate an array and populate it with numbers. Or select a random cell within a matrix. In any of these cases you will use Random class to generate a random number.

In this tutorial, you will learn what is the Random class in java and how to use it. Additionally I have included some Java code examples, which you can reuse in your own code. Let’s dive in!

What is Random Class in Java?

The Random class is a java class that will allow you to generator random numbers in your program. Let’s say for instance that you will like to program a Bingo game. You could use the Random class to generate the random numbers.

This class acts as a generator providing random numbers when you call it. Using the Random class, you can generate collections of numbers, as well as generating numbers one by one.

This class helps you to generate different type of numbers, including integer, long, double and float. See the Java Documentation for further details.

How do you use Random class?

Now that you understand what the Random class is, how can you use it in your java program?. You can use this class in three simple steps: import the class, instantiate it, and then call one of its methods.

There are different methods depending on the type of number you need: a float number, an integer number, etc, and the amount of numbers you need. Let’s start with the simplest example, generating an integer number.

import java.util.Random; // 1. Import 

public class Test {

    public static void main(String[] args){
        Random random = new Random(); // 2. Instantiate
        System.out.println(random.nextInt()); // 3. Generate number

    }
}

Output:

563309126

As well as creating single numbers, you can also create a collection of integers using the .ints(collectionSize) method. For instance, let’s say you want to generate 5 integer numbers at once:

import java.util.Random;

public class Test {

    public static void main(String[] args){
        Random random = new Random();
        random.ints(5).forEach( num -> System.out.println(num));

    }
}

Output:

-1615640330
-1970971454
635764506
-825177622
-11176987

Generate Number Between 1 and 10

However, maybe the above numbers are too random. In many occasions, you will need to generate a random number within a given range. For example, you might need to generate random numbers between 1 and 10.

Creating numbers within a range can be easily achieved by passing some extra parameters to the previous methods: .nextInt() and .ints().

Let’s see an example to illustrate this. Imagine you would like to create a single number between 1 and 10. You will need to call .nextInt() method passing an extra parameter to indicate the limit. See the example below:

import java.util.Random;

public class Test {

    public static void main(String[] args){
        Random random = new Random(); 
        System.out.println(random.nextInt(9)+1);

    }
}

Output:

8

It should be noted that the .nextInt() method generates numbers with origin zero. Therefore, if you want the origin to be one you will need to add one to the generated number.

Or in case you want to generate several numbers within a range at once, see below how you could achieve that using Java:

import java.util.Random;

public class Test {

    public static void main(String[] args){
        Random random = new Random();
        random.ints(5,1,10)
                .forEach(num -> System.out.println(num));
    }
}

Output:

8
9
2
3
3

The code above will generate five numbers between 1 and 10. The output above is the result of calling .ints() passing three parameters:

  • First parameter indicates the number of numbers to generate.
  • Second parameter represents the origin of the random number, in our example 1.
  • Last parameter is the upper bound of the random number, in this case 10.

More Random Class Java Examples

Let’s see a few more examples where the random class is useful to generate numbers.

Generate 10 random prices between 10 and 20

import java.util.Random;

public class Test {

    public static void main(String[] args){
        Random random = new Random();
        random.doubles(5, 10.00d,20.00d)
                .forEach(num -> System.out.println(num));

    }

The previous code snippet will generate five random numbers between 10.00 and 20.00 and print them. Alternatively, instead of printing them, you could save them on a java collection, such as a list, and use the numbers later on. See below this in action:

import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

public class Test {

    public static void main(String[] args){

        Random random = new Random();
        List<Double> prices = random.doubles(5, 10.00d,20.00d)
                                    .boxed()
                                    .collect(Collectors.toList());

    }
}

Conclusion

To summarise, in this article you learned what is the Random class in java. Additionally we have seen how to use the random class in java to generate random numbers in your programs. And an example of how to generate numbers between 1 and 10 in java.

I hope you enjoy this article, and thank you so much for reading and supporting this blog!

Happy Coding!

More Interesting Articles

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java