How to generate large random numbers in Java?

Java 8Object Oriented ProgrammingProgramming

For large random numbers, use BigInteger type in Java. At first, create a Random object −

Random randNum = new Random();

Now, declare a byte array and generate random bytes −

byte[] b = new byte[max];
randNum.nextBytes(b);

Now, generate a large random number with BigInteger type −

BigInteger bigInt = new BigInteger(b);

Example

 Live Demo

import java.math.BigInteger;
import java.util.Random;
public class Demo {
   public static void main(String... a) {
      int max = 10;
      Random randNum = new Random();
      byte[] b = new byte[max];
      randNum.nextBytes(b);
      // BigInteger type
      BigInteger bigInt = new BigInteger(b);
      System.out.println("Very large random number = "+bigInt);
   }
}

Output

Very large random number = 283258678185163472552410
raja
Published on 24-Apr-2019 10:39:14
Advertisements