Last Updated on 13 January 2023   |   Print Email
Generating random strings is a very common need of software applications. For examples, random strings are used for identifiers, tokens, keys, one-time passwords, verification code, etc. So in this article, I’d love to share with you some ways and code examples which you can use to generate random strings in Java, that include alphabetic, alphanumeric, numeric-only, and special characters.
1. Generate Random Strings using Java Core
For simple purposes (no strict security requirement), you can write some code with plain Java code. No external dependencies needed.
The basic logic about generating random string
The following code snippet gives you a basic idea about the logic of generating random strings in Java:
public static String randomStringSimple(int length) {
byte[] byteArray = new byte[length];
Random random = new Random();
random.nextBytes(byteArray);
return new String(byteArray, Charset.forName("UTF-8"));
}
This method generates a random string whose size is specified by the parameter length. You can see, we use the Randomclass’ nextBytes() method that returns a byte array filled with random values. Then we create a String object from the byte array, which results in a random string.Since a byte can have any value from -128 to 127, the generated string can contain non-visible characters. That means this code example cannot be used in practice, rather it gives you the basic idea of how to write code for generating random strings in Java.Also note that the java.util.Random class generates pseudorandom numbers, or fake random.
Generate alphanumeric random string using Java Core
The following code example shows how to generate a random string which contains both alphabetic and numeric characters:
public static String randomAlphanumericString(int length) {
String alphanumericCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuv";
StringBuffer randomString = new StringBuffer(length);
Random random = new Random();
for (int i = 0; i < length; i++) {
int randomIndex = random.nextInt(alphanumericCharacters.length());
char randomChar = alphanumericCharacters.charAt(randomIndex);
randomString.append(randomChar);
}
return randomString.toString();
}
The logic in this code is quite simple. First we define a String object alphanumericCharacters that contains all letters and numbers. Then we generate a random String with each character is randomly chosen from the predefined set. You can see we use the Randomclass’ nextInt() method that returns a random integer number that is not greater than the specified bound.And below is some testing code that generates 3 random strings with different length:
Random String #1: X7OsqoYB8P
Random String #2: pED6RK7HIVTOq0W
Random String #3: fqihhIIHsarlY4UAukXk
Generate random strings include special characters
You can modify the above code example to generate random strings that contain both alphanumeric and special characters. Based on the character codes in ASCII table:You see, the codes from 33 to 126 includes special, alphabetic and numeric characters. So below is the code:
public static String randomAlphanumericString(int length) {
char startChar = 33;
char endChar = 126;
StringBuffer randomString = new StringBuffer(length);
Random random = new Random();
for (int i = 0; i < length; i++) {
int randomIndex = startChar + random.nextInt(endChar - startChar + 1);
randomString.append((char) randomIndex);
}
return randomString.toString();
}
The UUID strings look like serial keys or product keys, right? So you can use UUID to ensure the uniqueness of random strings.
3. Generate Random Strings using Apache Commons Lang
If you don’t want to write code from scratch, you can use a ready-made library such as Apache Commons Lang - a popular library that provides extra methods missing in the standard Java libraries. To use Apache Commons Lang in a Java Maven project, declare the following dependency in the pom.xml file:
Then you can use some randomXXX() methods in the RandomStringUtils class for generate a kind of random string you wish to.Basically, you can use the generic method random(int count, boolean letters, boolean numbers). For example, the following code generates a 10-character random string that includes both letters and numbers:
So, depending on your need, use an appropriate method provided by the RandomStringUtils class. It’s very convenient if your project is already making use of the Apache Commons Lang library.
4. Use Secure and Thread-safe Random Generator
In case more security is required, you should use SecureRandom class instead of Random, which provides a cryptographically strong random number generator. For example:
Random random = new SecureRandom();
And in the random string generation code is used by multiple threads, you should use the ThreadLocalRandom class. For example:
Random random = ThreadLocalRandom.current();
That’s my guide and code examples about generating random strings in Java. I hope you find this article helpful. Thanks for reading.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments