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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With