Java: How to get random number with N digits

By: Slav Kurochkin

In my current project I need to generate SSN which contains 9 digits, here is how to do it:

 public static String generateRandom(int length) {
        Random random = new Random();
        char[] digits = new char[length];
        digits[0] = (char) (random.nextInt(9) + '1');
        for (int i = 1; i < length; i++) {
            digits[i] = (char) (random.nextInt(10) + '0');
        }
        return new String(digits);
    }

And then just call method with number of digits you wish to get:

generateRandom(9)
View Comments

Leave a Comment

Use markdown or basic HTML and be nice.