Java Random Class Tutorial and Example

HQ Ā» Java Tutorial Ā» java.util Ā» Random
Java Random Class Tutorial and Example 2018-02-28T03:41:34+00:00


The Random class of java.util package contains methods in handling Random numbers as the class name implies.Ā An instance of this class is used to generate a stream of pseudorandom numbers. A 48-bit seed has been used on this class, and these seed is modified usingĀ a linear congruential formula.

A particular scenario wherein if two instances of Random class are created using the same value on it’s seed,Ā and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. This is a must have property of this class and in order to guarantee as such, particular algorithms are specified for Random class. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.

Random Class Syntax

public class Random
extends Object
implements Serializable

Random Class Compatibility Version

Random Class is available since Java 1.0

Basic Usage of Random

The Random class as part of the java.util package is one of the classes of the java api that is fundamentally a must to learn as it is one of the foundation classes of Java. Being available since Java 1.0, this class has widely usage in the language.

Below is how you instantiate a new Random object.

There are two overloaded constructor of Random class. The first one is the one we showed above and the other which accepts a seed method argument.

Random Method Usage Examples

Modifier and Type Method and Description
DoubleStream doubles()
Returns an effectively unlimited stream of pseudorandom double values, each between zero (inclusive) and one (exclusive).

Contact Info


Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.