How to generate a random String in Java

chandra wibowo picture chandra wibowo · May 19, 2010 · Viewed 231k times · Source

I have an object called Student, and it has studentName, studentId, studentAddress, etc. For the studentId, I have to generate random string consist of seven numeric charaters, eg.

studentId = getRandomId();
studentId = "1234567" <-- from the random generator.

And I have to make sure that there is no duplicate id.

Answer

Jon Skeet picture Jon Skeet · May 19, 2010

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.