Random Class in Java

 

Let us learn what is a Random class in Java programming with its explanation, example, constructors, methods, implementation and output.

What is Random Class?

The Random class is a predefined class available in java.util package. This class generates a stream of pseudo-random numbers within a specified range of numbers.

The Random class in Java is basically used to generate random numbers like integer, floating point numbers, double, boolean.

One important point to note is that this class uses a 48-bit seed, which is modified using a linear congruential formula.

A new random number generator is created by using new Random() method which initializes the generator to a value based on the current time.

If the random number is created by using new Random(long seed) method, the method seeds the random number generator with a specific initial value.

Declaration of Random Class

   

Constructors of Random Class

SR. NO.CONSTRUCTORDESCRIPTION
1.Random()This constructor creates a new random number generator seed.
2.Random(long l)This constructor creates a new random number generator using a single long seed.

Methods of Random Class

SR. NO.METHODDESCRIPTION
1.boolean nextInt()This method returns the next random number of the type integer.
2.boolean nextInt(int n)This method returns the next random number of the type integer within a particular range specified by method parameter n.
3.boolean nextDouble()This method returns the next random number of the type double.
4.boolean nextFloat()This method returns the next random number of the type float.
5.boolean nextLong()This method returns the next random number of the type long.
6.void setSeed(long seed)This method creates a seed of random number generator using a single long seed.
7.void nextBytes(byte[] bytes)This method creates random bytes and places them into a user-supplied byte array.
8.boolean nextBoolean()This method returns the next random boolean value.

Implementation of Random Class in Java

Output

   

If you have any doubts about the implementation of the Random class in Java programming, let us know about it in the comment section. Find more on UPEN.

Collection Frameworks
StringTokenizer Class
Vector Class
Stack Class

Let's Discuss