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
1 | public class Random extends Object implements Serializable |
Constructors of Random Class
SR. NO. | CONSTRUCTOR | DESCRIPTION |
---|---|---|
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. | METHOD | DESCRIPTION |
---|---|---|
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import java.util.*; public final class demo { public static final void main(String args[]) { int count = 0; System.out.println("Random Number Generator Program\n"); Random num = new Random(); for(count = 0; count < 10; count++) { int randomInt = num.nextInt(100); System.out.println("\nNumber:\t" + randomInt); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 | Random Number Generator Program Number: 2 Number: 17 Number: 97 Number: 65 Number: 12 Number: 90 Number: 34 Number: 45 Number: 87 Number: 7 |
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 |