RandomStringGenerator to generate alphanumeric strings

I use this:

static char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'q', 'w', 'e', 'r', 't', 'z', 'u', 'i', 'o', 'p', 'a', 's',
        'd', 'f', 'g', 'h', 'j', 'k', 'l', 'y', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Z', 'U', 'I', 'O', 'P', 'A',
        'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Y', 'X', 'C', 'V', 'B', 'N', 'M' };

private static String randomString(int length) {
    StringBuilder stringBuilder = new StringBuilder();

    for (int i = 0; i < length; i++) {
        stringBuilder.append(chars[new Random().nextInt(chars.length)]);
    }
    return stringBuilder.toString();
}

or

private static String randomString(int length) {
    StringBuilder stringBuilder = new StringBuilder();

    for (int i = 0; i < length; i++) {
        switch (new Random().nextInt(3)) {
            case 0:
                stringBuilder.append((char) (new Random().nextInt(9) + 48));
                break;
            case 1:
                stringBuilder.append((char) (new Random().nextInt(25) + 65));
                break;
            case 2:
                stringBuilder.append((char) (new Random().nextInt(25) + 97));
                break;
            default:
                break;
        }
    }
    return stringBuilder.toString();
}

Yes, using the following code:

import static org.apache.commons.text.CharacterPredicates.DIGITS;
import static org.apache.commons.text.CharacterPredicates.LETTERS;

// ...

RandomStringGenerator generator = new RandomStringGenerator.Builder()
        .withinRange('0', 'z')
        .filteredBy(LETTERS, DIGITS)
        .build();

RandomStringGenerator generator = new RandomStringGenerator.Builder()
    .selectFrom("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray())
    .build();

I kind of prefer this way rather than generating character codes and filtering out ones I don't want. And implicitly assuming that '0'..'z' includes all the codes I want, including capital letters (based on the ascii code chart).

In addition, depending on the application (eg password generation), you might want to use a CSPRNG (secure PRNG) seeded by a true-randomness source:

.usingRandom(new SecureRandom()::nextInt)

The default SecureRandom seed is from a true-randomness source of OS hardware device entropy.

Tags:

Java