How to generate a random String in Java [duplicate]

Generating a random string of characters is easy – just use java.util.Random and a string containing all the characters you want to be available, e.g.

public static String generateString(Random rng, String characters, int length)
{
    char[] text = new char[length];
    for (int i = 0; i < length; i++)
    {
        text[i] = characters.charAt(rng.nextInt(characters.length()));
    }
    return new String(text);
}

Now, for uniqueness you’ll need to store the generated strings somewhere. How you do that will really depend on the rest of your application.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)