Java: Generating a random number of a certain length

To generate a random number with, for example 5 digits, you can do:

int n = 10000 + new Random().nextInt(90000);
// 10000 ≤ n ≤ 99999

Since the upper bound given to nextInt is exclusive, the maximum is indeed 99999.

Generalized version

// Generates a random int with n digits
public static int generateRandomDigits(int n) {
    int m = (int) Math.pow(10, n - 1);
    return m + new Random().nextInt(9 * m);

Warning: The above method breaks for n > 9, since 109 is the largest power of 10 that an int can store.

More than 9 digits

You can adapt the above method to work with long. This would get you up to 18 digits.

Alternatively you can work with strings. See this article: Generating a random String (password, booking reference, etc). The resulting string can be converted to a BigDecimal if needed.


Be the first to comment!