Create random String in Java example shows how to create random string of a specified length in Java. The example also shows how to create random alphanumeric string, random numeric string or random alphabetic string in Java.
How to create a random string of the specified length in Java?
There are several ways in which you can create a random string in Java as given below.
1) Using the Random and String classes
We can create a random string of specified length using the java.util.Random class as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package com.javacodeexamples.stringexamples; import java.util.Random; public class JavaRandomStringExample { //we want random alphanumeric string of 20 characters static final int OUTPUT_STRING_LENGTH = 20; public static void main(String[] args) { //string containing allowed characters, modify according to your needs String strAllowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; //initialize Random Random random = new Random(); System.out.println("Random alphanumeric string of 20 characters"); for(int i=0; i<10; i++){ System.out.println( getNextRandomString(strAllowedCharacters, random) ); } } private static String getNextRandomString(String strAllowedCharacters, Random random) { StringBuilder sbRandomString = new StringBuilder(OUTPUT_STRING_LENGTH); for(int i = 0 ; i < OUTPUT_STRING_LENGTH; i++){ //get random integer between 0 and string length int randomInt = random.nextInt(strAllowedCharacters.length()); //get char from randomInt index from string and append in StringBuilder sbRandomString.append( strAllowedCharacters.charAt(randomInt) ); } return sbRandomString.toString(); } } |
Output
1 2 3 4 5 6 7 8 9 10 11 |
Random alphanumeric string of 20 characters E3KL6DdWSETWhhjCPFmE 9u0C7BfaTV9v4XgsdQuQ IeZ4qPFFq0Pt0AOTrRxD 5Q0r9y1ZepILbMnC4ZfZ hYmE4ZQc1gCqADOVtu4K 4pesUvWAHZyx8VVa9Ys8 lL5EN5MwiLrlcy2oPan8 8JzJPbdGCdCYBXsNlU96 RaYInByoSEQWXigf06IY pJwnjqzm36agsELTmoYW |
We kept all the allowed characters in a String for later reference and took one random character from it and appended it to the StringBuilder object. When we had required string length, we converted StringBuilder to String and returned it.
You can change the String containing allowed characters according to your needs. You can also change the string required length to generate a random string of specified characters.
Note: Please note that the above solution uses java.util.Random class. If you want a secure solution change the Radom with SecureRandom class.
If you are using Java 1.4 or earlier version, use the StringBuffer class instead of the StringBuilder class.
2) Using the SecureRandom and BigInteger classes
The BigInteger class can be used to generate random strings by using below given constructor.
1 |
public BigInteger(int bits, Random random) |
This constructor creates randomly generated non-negative BigInteger in the range of 0 to 2^bits – 1. Here is the example program to generate random string using BigInteger and SecureRandom classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package com.javacodeexamples.stringexamples; import java.math.BigInteger; import java.security.SecureRandom; public class JavaRandomStringExample { public static void main(String[] args) { RandomStringGenerator generator = new RandomStringGenerator(); for(int i=0; i<10; i++){ System.out.println( generator.getNextRandomString() ); } } } class RandomStringGenerator{ //initialize secure random static final SecureRandom secureRandom = new SecureRandom(); //get next random string public String getNextRandomString(){ //create 130 bits random BigInteger BigInteger bInt = new BigInteger(130, secureRandom); //return string representation of BigInteger in 32 radix return bInt.toString(32); } } |
Output
1 2 3 4 5 6 7 8 9 10 |
u9g34acj9nrhst3idudie85tu8 rqrs1ln4hitiha1qej567d48od mhpfo7i3ai1u1rc8hdrbre6skb npp3875q5lccdvpqd16lmdacve pbln6eq11pi1fi2vhr2rph43q4 7stbvfds9ta0r420ovvnmv6vbg 7ck457r1i7t9gac13sotgtfhb9 sai0tmedh6a23dte36icjh3jaf har1ueuasmsp8ntdu8pela6h3g trvvv1jid38s2uu85p9vjt2800 |
3) Using the UUID class
Java provides UUID (Universally unique identifier) class which can be used to generate random string. Use randomUUID
method of the UUID class to generate random 128-bit string.
1 |
public static UUID randomUUID() |
This method generates level 4 (i.e. pseudo randomly generated) UUID.
What is version 4 UUID?
Version 4 UUID is based on random numbers. Algorithm of version 4 UUID keeps version number and other 2 bits reserved. Every other bits are set by random numbers. Below given is the format of version 4 UUID.
1 |
xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx |
Where x could be any hexadecimal digit. Y is any one of 8, 9, a or b.
Here is the example program to generate random level 4 UUID.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.javacodeexamples.stringexamples; import java.util.UUID; public class JavaRandomStringExample { public static void main(String[] args) { for(int i=0; i<10; i++){ String strRandomString = UUID.randomUUID().toString(); System.out.println( strRandomString ); } } } |
Output
1 2 3 4 5 6 7 8 9 10 |
f31c7c67-ac20-4aa5-86e9-4e4c17786a1c 4859dde6-242b-4b82-9718-7e20e0c83e09 8985942d-e91a-433d-9a38-74934f9d4ea5 7ea562aa-c3af-4dfc-a3aa-5e1c3c7e2235 47ce22ac-1e5c-45c3-b970-c8e21da8b0c8 2d81b531-43c0-45a4-964a-a9c027c50ed2 845f2649-eebc-4698-b5f5-17cdde2db845 1ab76e31-40a0-418d-84bf-9cc7f5e1a9a3 209e6356-d25f-4ff3-a0ed-7786c8988378 0106ec74-cfe8-43d1-bd1b-c0087dea4eb6 |
If you don’t want “-” in the final strings, you can change the line which generates the UUID as given below.
1 |
String strRandomString = UUID.randomUUID().toString().replaceAll("-", ""); |
4) Using Apache Commons
If you are using the Apache Commons library, you can use the RandomStringUtils class from Apache Commons lang to generate random string of specified length.
a) Generate random alphanumeric string of specified length
Use randomAlphanumeric
method of RandomStringUtils class to generate random alphanumeric string.
1 |
public static String randomAlphanumeric(int stringLength) |
This method generates a random alphanumeric string of specified length.
1 2 3 |
for(int i=0; i<5; i++){ System.out.println( RandomStringUtils.randomAlphanumeric(20) ); } |
Output
1 2 3 4 5 |
0ZQGfZe3EfXDudmwnrCE tVlRNida5uyOXhteKDCj QNQnEXHQvxvnPvNmkICi xW9eI3gSAMEGbZW7skC3 CarCzPpydJQxq0Tavet1 |
b) Generate a random alphabetic string of specified length
Use randomAlphabetic
method of RandomStringUtils class to generate random alphabetic string.
1 |
public static String randomAlphabetic(int stringLength) |
This method generates a random alphabetic string of specified length.
1 2 3 |
for(int i=0; i<5; i++){ System.out.println( RandomStringUtils.randomAlphabetic(20) ); } |
Output
1 2 3 4 5 |
qnRmReJHofAIhYSqpgVS KiYODEYgIHzcpoHEdQZW scLhKRnbYNuHtRLXuFDd PjYjVddNakkpRHfWZDFD vYXUPwEKmlRVtlCfuebs |
c) Generate a random alphanumeric string of specified length
Use randomNumeric
method of RandomStringUtils class to generate random numeric string.
1 |
public static String randomNumeric (int stringLength) |
This method generates a random numeric string of specified length.
1 2 3 |
for(int i=0; i<5; i++){ System.out.println( RandomStringUtils.randomNumeric (20) ); } |
Output
1 2 3 4 5 |
92470231898520600726 80218440767826078030 54668187709794707054 15214762655349726874 68178303212080981526 |
Note: Please note that the RandomStringUtils class uses java.util.Random to produce random sequences. Use the SecureRandom class along with random
method of the RandomStringUtils class to generate secure randoms as given below.
1 |
public static String random(int stringLength, start, end, boolean letters, boolean numbers, char[] source, Random random) |
Where,
count – number of characters
start – start index position in the source char[]
end – end index position in the source char[]
letters – true if letters are allowed
numbers – true if numbers are allowed
char[] – char array to choose random letters from
random – the source of random sequence
Example program
1 2 3 4 5 6 7 8 9 |
SecureRandom secureRandom = new SecureRandom(); for(int i=0; i<5; i++){ String strRandomString = RandomStringUtils.random(20, 0, 0, true, true, null, secureRandom); System.out.println( strRandomString ); } |
Output
1 2 3 4 5 |
AKQbzrqYlcTwvnonpgCs Uj5Y7X3YXYEOhlX28iF6 YtMcsz857E0bnVTunWkS SmxSr9qa2FFXdgNhZJX9 AtkyegR7HIlahgfDsbKs |
This example is a part of the Java String tutorial.
Please let me know your views in the comments section below.