The Wayback Machine - https://web.archive.org/web/20240923103256/https://www.geeksforgeeks.org/java-util-random-class-java/
Open In App

Java.util.Random class in Java

Last Updated : 07 May, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Random class is used to generate pseudo-random numbers in java. An instance of this class is thread-safe. The instance of this class is however cryptographically insecure. This class provides various method calls to generate different random data types such as float, double, int.

Constructors:

  • Random(): Creates a new random number generator
  • Random(long seed): Creates a new random number generator using a single long seed

Declaration:

public class Random
               extends Object
               implements Serializable

Methods:

  1. java.util.Random.doubles(): Returns an effectively unlimited stream of pseudo random double values, each between zero (inclusive) and one (exclusive)
    Syntax:

    public DoubleStream doubles()
    Returns:
    a stream of pseudorandom double values
  2. java.util.Random.ints(): Returns an effectively unlimited stream of pseudo random int values
    Syntax:

    public IntStream ints()
    Returns:
    a stream of pseudorandom int values
  3. java.util.Random.longs(): Returns an effectively unlimited stream of pseudo random long values
    Syntax:

    public LongStream longs()
    Returns:
    a stream of pseudorandom long values
  4. next(int bits): java.util.Random.next(int bits) Generates the next pseudo random number
    Syntax:

    protected int next(int bits)
    Parameters:
    bits - random bits
    Returns:
    the next pseudo random value from this 
    random number generator's sequence
  5. java.util.Random.nextBoolean(): Returns the next pseudo random, uniformly distributed boolean value from this random number generator’s sequence
    Syntax:

    public boolean nextBoolean()
    Returns:
    the next pseudorandom, uniformly distributed boolean value 
    from this random number generator's sequence
  6. java.util.Random.nextBytes(byte[] bytes) :Generates random bytes and places them into a user-supplied byte array
    Syntax:

    public void nextBytes(byte[] bytes)
    Parameters:
    bytes - the byte array to fill with random bytes
    Throws:
    NullPointerException - if the byte array is null
  7. java.util.Random.nextDouble(): Returns the next pseudo random, uniformly distributed double value between 0.0 and 1.0 from this random number generator’s sequence
    Syntax:

    public double nextDouble()
    Returns:
    the next pseudo random, uniformly distributed double 
    value between 0.0 and 1.0 from this 
    random number generator's sequence
  8. java.util.Random.nextFloat(): Returns the next pseudo random, uniformly distributed float value between 0.0 and 1.0 from this random number generator’s sequence
    Syntax:

    public float nextFloat()
    Returns:
    the next pseudorandom, uniformly distributed float value 
    between 0.0 and 1.0 from this 
    random number generator's sequence
  9. java.util.Random.nextGaussian(): Returns the next pseudo random, Gaussian (“normally”) distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator’s sequence
    Syntax:

    public double nextGaussian()
    Returns:
    the next pseudorandom, Gaussian ("normally") distributed double
    value with mean 0.0 and standard deviation 1.0 from this 
    random number generator's sequence
  10. java.util.Random.nextInt(): Returns the next pseudorandom, uniformly distributed int value from this random number generator’s sequence
    Syntax:

    public int nextInt()
    Returns:
    the next pseudorandom, uniformly distributed int value from 
    this random number generator's sequence
  11. java.util.Random.nextInt(int bound): Returns a pseudo random, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator’s sequence
    Syntax:

    public int nextInt(int bound)
    Parameters:
    bound - the upper bound (exclusive). Must be positive.
    Returns:
    the next pseudorandom, uniformly distributed int value 
    between zero (inclusive) and bound 
    (exclusive) from this random number generator's sequence
    Throws:
    IllegalArgumentException - if bound is not positive
  12. java.util.Random.nextLong(): Returns the next pseudorandom, uniformly distributed long value from this random number generator’s sequence
    Syntax:

    public long nextLong()
    Returns:
    the next pseudorandom, uniformly distributed long value
    from this random number 
    generator's sequence
  13. java.util.Random.setSeed(long seed): Sets the seed of this random number generator using a single long seed
    Syntax:

    public void setSeed(long seed)
    Parameters:
    seed - the initial seed

Methods inherited from class java.lang.Object

  • clone
  • equals
  • finalize
  • getClass
  • hashCode
  • notify
  • notifyAll
  • toString
  • wait

Java program to demonstrate usage of Random class




// Java program to demonstrate
// method calls of Random class
import java.util.Random;
  
public class Test
{
    public static void main(String[] args)
    {
        Random random = new Random();
        System.out.println(random.nextInt(10));
        System.out.println(random.nextBoolean());
        System.out.println(random.nextDouble());
        System.out.println(random.nextFloat());
        System.out.println(random.nextGaussian());
        byte[] bytes = new byte[10];
        random.nextBytes(bytes);
        System.out.printf("[");
        for(int i = 0; i< bytes.length; i++)
        {
            System.out.printf("%d ", bytes[i]);
        }
        System.out.printf("]\n");
          
          System.out.println(random.nextLong());  
      System.out.println(random.nextInt());
       
      long seed = 95;
      random.setSeed(seed);
        
      // Note: Running any of the code lines below
      // will keep the program running as each of the 
      // methods below produce an unlimited random 
      // values of the corresponding type
  
      /* System.out.println("Sum of all the elements in the IntStream returned = " + 
        random.ints().count());
      System.out.println("Count of all the elements in the DoubleStream returned = " + 
        random.doubles().count());
      System.out.println("Count of all the elements in the LongStream returned = " + 
        random.longs().count());
       
      */
     
  }
}     


Output:

4
true
0.19674934340402916
0.7372021
1.4877581394085997
[-44 75 68 89 81 -72 -1 -66 -64 117 ]
158739962004803677
-1344764816

Reference:



Similar Reads

Java.util.Random.nextInt() in Java
Generating random numbers themselves have a good utility value and having them achieved by the usage of function can prove to be very useful. Java in its language has dedicated an entire library to Random numbers seeing its importance in day-day programming. nextInt() is discussed in this article. java.util.Random.nextInt() : The nextInt() is used
4 min read
Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?Solution
5 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read
Java.util.concurrent.Phaser class in Java with Examples
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts
7 min read
Java.util.concurrent.RecursiveTask class in Java with Examples
RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method of RecursiveTask. RecursiveTask class is mostly use
2 min read
Java.util.BitSet class in Java with Examples | Set 1
BitSet is a class defined in the java.util package. It creates an array of bits represented by boolean values. Constructors: BitSet class Constructors / \ BitSet() BitSet(int no_Of_Bits)BitSet() : A no-argument constructor to create an empty BitSet object. BitSet(int no_Of_Bits): A one-constructor with an integer argument to create an instance of t
2 min read
Java.util.BitSet class methods in Java with Examples | Set 2
Methods discussed in this post: BitSet class methods. / / | | \ \ set() xor() clone() clear() length() cardinality() We strongly recommend to refer below set 1 as a prerequisite of this. BitSet class in Java | Set 1 set() : java.util.BitSet.set() method is a sets the bit at the specified index to the specified value. Syntax:public void set(int bitp
4 min read
Java.util.zip.DeflaterInputStream class in Java
Implements an input stream filter for compressing data in the "deflate" compression format. Constructor and Description DeflaterInputStream(InputStream in) : Creates a new input stream with a default compressor and buffer size. DeflaterInputStream(InputStream in, Deflater defl) : Creates a new input stream with the specified compressor and a defaul
3 min read
Java.util.zip.InflaterOutputStream class in Java
This class implements an output stream filter for uncompressing data stored in the "deflate" compression format. Constructors InflaterOutputStream(OutputStream out) : Creates a new output stream with a default decompressor and buffer size. InflaterOutputStream(OutputStream out, Inflater infl) : Creates a new output stream with the specified decompr
3 min read
Java.util.zip.InflaterInputStream class in Java
This class implements a stream filter for uncompressing data in the "deflate" compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream. Constructors InflaterInputStream(InputStream in) : Creates a new input stream with a default decompressor and buffer size. InflaterInputStream(InputStream in, Inflat
3 min read
Java.util.zip.ZipOutputStream class in Java
This class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructor : ZipOutputStream(OutputStream out) : Creates a new ZIP output stream. ZipOutputStream(OutputStream out, Charset charset) : Creates a new ZIP output stream. Methods: void close() : Closes
3 min read
Java.util.jar.JarEntry class in Java
This class is used to represent a JAR file entry. Constructors : JarEntry(JarEntry je) : Creates a new JarEntry with fields taken from the specified JarEntry object. JarEntry(String name) : Creates a new JarEntry for the specified JAR file entry name. JarEntry(ZipEntry ze) : Creates a new JarEntry with fields taken from the specified ZipEntry objec
2 min read
Java.util.zip.GZIPInputStream class in Java
This class implements a stream filter for reading compressed data in the GZIP file format. Constructors GZIPInputStream(InputStream in) : Creates a new input stream with a default buffer size. GZIPInputStream(InputStream in, int size) : Creates a new input stream with the specified buffer size. Methods : void close() : Closes this input stream and
2 min read
Java.util.zip.ZipEntry class in Java
This class is used to represent a ZIP file entry. Constructors ZipEntry(String name) : Creates a new zip entry with the specified name. ZipEntry(ZipEntry e) : Creates a new zip entry with fields taken from the specified zip entry. Methods: Object clone() : Returns a copy of this entry. Syntax :public Object clone() Overrides: clone in class Object
4 min read
Java.util.jar.JarInputStream class in Java
The JarInputStream class is used to read the contents of a JAR file from any input stream. It extends the class java.util.zip.ZipInputStream with support for reading an optional Manifest entry. The Manifest can be used to store meta-information about the JAR file and its entries. Constructors JarInputStream(InputStream in) : Creates a new JarInputS
3 min read
Java.util.zip.ZipInputStream class in Java
This class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructors: ZipInputStream(InputStream in) : Creates a new ZIP input stream. ZipInputStream(InputStream in, Charset charset) : Creates a new ZIP input stream Methods : int available() : Returns 0 af
3 min read
Java.util.PriorityQueue class in Java
It is a priority queue based on priority heap. Elements in this class are in natural order or depends on the Constructor we used at this the time of construction. It doesn't permit null pointers. It doesn't allow inserting a non-comparable object, if it relies on natural ordering. Constructors: PriorityQueue(): Creates a PriorityQueue with the defa
6 min read
Java.util.Locale Class in Java | Set 1
As the name suggests util.Locale Class is used to perform locale tasks and provides locale information for the user. Declaration : public final class Locale extends Object implements Cloneable, Serializable Constructors : Locale(String L): Creates Locale from the given language code.Locale(String L, String C): Creates Locale from the given language
4 min read
Java.util.Locale Class in Java | Set 2
Java.util.Locale Class in Java | Set 1 More methods: getDisplayVariant() : java.util.Locale.getDisplayVariant() displays variant of the Locale Syntax : public final String getDisplayVariant() Parameters : ---- Return : ----------- getDisplayVariant(Locale in) : java.util.Locale.Locale in(Locale in) returns the variant of "in" locale. Syntax : publi
3 min read
Java.util.TimerTask class in Java
TimerTask is an abstract class defined in java.util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden. The run method is implicitly invoked when a timer object schedules
3 min read
Java.util.Timer Class in Java
Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions. Each timer object is associated with a background thread that is responsible for the execution of all the tasks of a timer
6 min read
Java.util.ArrayDeque Class in Java | Set 1
java.util.ArrayDeque class describes an implementation of a resizable array structure which implements the Deque interface. Array deques has not immutable and can grow as necessary. They are not thread-safe and hence concurrent access by multiple threads is not supported unless explicitly synchronized. Null elements are invalid in this structure. M
5 min read
Java.util.ArrayDeque Class in Java | Set 2
Java.util.ArrayDeque Class in Java | Set 1 More Methods of util.ArrayDeque Class : 16. offer(Element e) : java.util.ArrayDeque.offer(Element e) : inserts element at the end of deque. Syntax : public boolean offer(Element e) Parameters : e - element to add Return : true, if element is added else; false 17. offerFirst(Element e) : java.util.ArrayDequ
5 min read
Java.util.Dictionary Class in Java
The java.util.Dictionary class in Java is an abstract class that represents a collection of key-value pairs, where keys are unique and are used to access the values. It was part of the Java Collections Framework introduced in Java 1.2 but has been largely replaced by the java.util.Map interface since Java 1.2. The Dictionary class is an abstract cl
7 min read
Java.util.Observable class in Java
java.util.Observable is used to create subclasses that other parts of the program can observe. When an object of such subclass undergoes a change, observing classes are notified. The update( ) method is called when an observer is notified of a change. Note: Observing class must implement the Observer interface, which defines the update( ) method. A
8 min read
Java.util.UUID class in Java
A class that represents an immutable universally unique identifier (UUID). A UUID represents a 128-bit value. There exist different variants of these global identifiers. The methods of this class are for manipulating the Leach-Salz variant, although the constructors allow the creation of any variant of UUID (described below). There are four differe
7 min read
Java.util.Objects class in Java
Java 7 has come up with a new class Objects that have 9 static utility methods for operating on objects. These utilities include null-safe methods for computing the hash code of an object, returning a string for an object, and comparing two objects. Using Objects class methods, one can smartly handle NullPointerException and can also show customize
7 min read
Random vs Secure Random numbers in Java
Prerequisite: Generating Random numbers in Javajava.security.SecureRandom class: This class provides a cryptographically strong random number generator (RNG). A cryptographically strong random number minimally complies with the statistical random number generator tests specified in FIPS 140-2, Security Requirements for Cryptographic Modules, sectio
3 min read
Java.util.TimeZone Class | Set 1
TimeZone class is used to represents a time zone offset, and also figures out daylight savings.What is a Time Zone and Time Offset?"Time Zone" is used to describe the current time for different areas of the world. It refers to one of the specific regions out of the 24 total regions in the world that are divided up by longitude. Within each one of t
7 min read
Article Tags :
Practice Tags :