Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random String in Java [duplicate]

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.

like image 513
chandra wibowo Avatar asked May 19 '10 08:05

chandra wibowo


People also ask

How do you generate a random text string in Java?

Using randomUUID() java. util. UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.

How do you generate random strings?

Using the random index number, we have generated the random character from the string alphabet. We then used the StringBuilder class to append all the characters together. If we want to change the random string into lower case, we can use the toLowerCase() method of the String .


1 Answers

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.

like image 137
Jon Skeet Avatar answered Oct 01 '22 13:10

Jon Skeet