Is there any way to generate 8 characters long random and unique String in Java?
String id = getRandomString();
and then id
will be for example wf41Av5g
The uniqueness property depends on the scope in which you use it. Java can certainly generate random strings, although if you want a universally unique identifier you can use UUID
class.
String unique = UUID.randomUUID().toString();
If the uniqueness is important, you can't simply randomly generate strings. There is no way to avoid a collision. Even UUIDs can collide, although it is quite unlikely.
You could keep a record of the strings you've used, and when you generate a new random string, check the record to see if it's a duplicate, and if so, discard it and try again.
However, what i would suggest is that you don't generate random numbers. Instead, keep a counter, and encrypt its output to produce random-looking numbers. These are guaranteed never to collide if you do this properly. See an earlier answer of mine, or one by Rossum
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