Random Numbers in Java

Java 8Object Oriented ProgrammingProgramming

The java.util.Random class instance is used to generate a stream of pseudorandom numbers. Following are the methods provided by the Random class to set the seed of the random number, generate the next random number.

Let us learn about some of these methods −

Sr.NoMethod & Description
1protected int next(int bits)
This method generates the next pseudorandom number.
2boolean nextBoolean()
This method returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence.
3void nextBytes(byte[] bytes)
This method generates random bytes and places them into a user-supplied byte array.
4double nextDouble()
This method returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.
5float nextFloat()
This method returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.

Let us see an example to generate random number. The next(int bits) method is used to generate the next pseudorandom number −

Example

import java.util.*;
public class Demo {
   public static void main( String args[] ) {
      // create random object
      Random randomno = new Random();
      // get next next pseudorandom value
      int value = randomno.nextInt();
      // check the value
      System.out.println("Value is: " + value);
   }
}

Output

Value is: 1346755359

Let us see another example to generate next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence. Using the nextDouble() method −

Example

import java.util.*;
public class Demo {
   public static void main( String args[] ) {
      Random randomno = new Random();
      // check next double value
      System.out.println("Next double value: " + randomno.nextDouble());
   }
}

Output

Next double value: 0.17585764114834557
raja
Published on 24-Sep-2019 07:58:59
Advertisements