Possible Duplicate:
How to generate a random String in Java
I am wanting to generate a random string of 20 characters without using apache classes. I don't really care about whether is alphanumeric or not. Also, I am going to convert it to an array of bytes later FYI.
Thanks,
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 .
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.
Here you go. Just specify the chars you want to allow on the first line.
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray(); StringBuilder sb = new StringBuilder(20); Random random = new Random(); for (int i = 0; i < 20; i++) { char c = chars[random.nextInt(chars.length)]; sb.append(c); } String output = sb.toString(); System.out.println(output);
If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use
java.security.SecureRandom
instead. Values produced byjava.util.Random
andjava.util.concurrent.ThreadLocalRandom
are mathematically predictable.
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