Generating Pseudo Random Numbers With Java 17

Dsforgood
2 min readMar 6, 2022
pseudo random number

Hello Readers and Developers we welcome you all to this article on Generating Pseudo Random Numbers with Java 17. There are many updates to the API for generating random numbers in the latest Java 17 release. With Java 17 API update, new interface types have been introduced, as well as methods to easily list, find and instantiate generator factories. Also a new set of random number generator implementations is now available.

In this article we will generate random numbers with old and new APIs with full code and explanation. So without further delay let us start by understanding the old API first.

Pseudo Random Number Generation With Old API

In old API we use Random class to generate pseudo random numbers. Random class belongs to java.util package. Below is the complete code for it,

In the above code we can see that the Random class object is created and then the nextInt() method is invoked to get the random number in the specified range. The constructor sets the seed of the random number generator to a value that is very likely distinct from any other invocation. Below is the output of this example,

All instances of Random class are thread safe but concurrent usage may result in poor performance. To handle this ThreadLocalRandom class is used. Also the cryptographically secure SecureRandom class is available in the old API.

Now Let us take a look at the new API,

Pseudo Random Number Generator API In Java 17

The new API provides an improved overall design with new interface types and generator implementations. With the old API, switching between Different generators was difficult. In the new API support for stream based processing is added. The new API also removes duplicate code in classes.

The new root interface RandomGenerator provides a uniform API for all existing and new random number generators.

A factory class for generating multiple random number generators of a specific algorithm was added in the new API.

Now below is the code for generating pseudo random numbers with new API,

In the above code we are using RandomGenerator to create pseudo random numbers. Here we are passing the name of the random number generator as parameter.

Below is the output for this random number generation code.

As they don’t have to be thread-safe, the new generator implementations perform faster compared to Random (old API).

Conclusion

In this article we have seen the generation of pseudo random numbers by using the old API and java 17 API. Java 17 added new interface types as well as new generator implementations. We hope you understood these features. Wishing you all the best in coding.

Thank you for reading this article. Take care and See you in the next article.

--

--

Dsforgood

We are a bunch of data science enthusiasts simplifying concepts and ideas in technology for common readers. We believe in using data science for good!