import java.security.SecureRandom;
/**
* Utility class for generating random numbers.
*/
public class RandomNumberGenerator {
// Thread-safe, cryptographically strong pseudo-random number generator.
// Reusing a single instance avoids overhead and entropy exhaustion.
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
// Inclusive lower and upper bounds for an 8-digit positive integer.
private static final int LOWER_BOUND = 10_000_000;
private static final int UPPER_BOUND = 99_999_999;
public static void main(String[] args) {
// Generate and display a single 8-digit random integer
int randomNumber = generate8DigitNumber();
System.out.println("Generated 8-digit number: " + randomNumber);
// Optional: Generate a padded String representation (useful if zero-padding is needed)
String randomString = generate8DigitString();
System.out.println("Generated 8-digit string: " + randomString);
}
/**
* Generates a random 8-digit positive integer between 10,000,000 and 99,999,999 (inclusive).
*
* @return a random 8-digit integer
*/
public static int generate8DigitNumber() {
// SECURE_RANDOM.nextInt(bound) returns a value from 0 (inclusive) up to bound (exclusive).
// Range size = (99,999,999 - 10,000,000 + 1) = 90,000,000.
// Adding LOWER_BOUND shifts the range from [0, 89,999,999] to [10,000,000, 99,999,999].
int range = UPPER_BOUND - LOWER_BOUND + 1;
return LOWER_BOUND + SECURE_RANDOM.nextInt(range);
}
/**
* Generates a random 8-digit string, allowing leading zeros (range 00000000 to 99999999).
* Useful for verification codes, OTPs, or IDs where fixed width is required.
*
* @return an 8-character numeric string
*/
public static String generate8DigitString() {
// Generates an integer from 0 to 99,999,999 and formats it with leading zeros
int number = SECURE_RANDOM.nextInt(100_000_000);
return String.format("%08d", number);
}
}
/*
run:
Generated 8-digit number: 55084333
Generated 8-digit string: 95472301
*/