I am generating a number of random Strings, with a specified length, using for loops and a StringBuilder, but I am getting Strings that are shorter than the specified length. My question is, why are some Strings being generated with the correct length, and some are not?
public class PasswordGen {
public static void main(final String[] args) {
final String[] chars = characters.split("");
final List<String> characterList = Arrays.asList(chars);
final Random rng = new SecureRandom();
Collections.shuffle(characterList, rng);
final int passwordsToGenerate = 16;
final int length = 31;
for (int i = 0; i < passwordsToGenerate; i++) {
final StringBuilder builder = new StringBuilder();
for (int j = 0; j < length; j++) {
final int index = rng.nextInt(characterList.size());
builder.append(characterList.get(index));
}
final String password = builder.toString();
System.out.println(password);
if (password.length() < 31) {
System.out.println("^ is not 31 characters in length: " + password.length());
}
}
}
public static final String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
}
The output:
LMUYN7bHKX13Rx1dwEkbHI8KjUONbDN
hnwMBD2LPHyuoYffGy7eC5STAg8heB
^ is not 31 characters in length: 30
EbburpyvZqc71mPadP8rYc6cJ8K9wl
^ is not 31 characters in length: 30
nLb58OzfnERsPm1SdR1nKBuOilhXzG
^ is not 31 characters in length: 30
c44M4Pk1kDIBMVqL0o5NybPA5t8zI3D
I3ttG7TvO8pKOp9yb5mGzJtnkTNVLH9
K1md1ORt2W3s8iR3RpMf2yNHjMrH8N
^ is not 31 characters in length: 30
G8daUMVLoMqpYqSrAUzSdI5IJCM7GSM
KMfaLvfCaudpRACpuOlA1gO3rqmhBs
^ is not 31 characters in length: 30
Y20V5RcKUiS8Ny9NpARmTMac29y8Z
^ is not 31 characters in length: 29
Rse101oxhOMXRdpchp4X3Uzm00Gzsc
^ is not 31 characters in length: 30
oQxaYE9qx1cEJP8KvTGdwo1IJhNH41O
y6E2WrKEAl2zWV6BCkH1JaWvz3aBxvs
QFautBHKlgDPlJhmge7n6Kf79G6mfu
^ is not 31 characters in length: 30
l2OBC9sFsZOfB481HXLsIiIwnmcOpdB
A4CTQj9Xc7grxtYYFzDRLelf3YQOTWV
I tried adding a Thread.sleep()
block inside both the inner for loop, before and after getting the next index, before and after appending the character to the builder, before and after setting the password variable, and before and after the the inner loop, to see if it was somehow related to threading. There was no visible difference in the results.
I am using Windows 7 Professional 64-bit, and have tested with JDK 7u67 and 8u11, both 32-bit and 64-bit with the same results.