How to generate random alphanumeric string of given size in Java
In this section, we will show you how to generate random alphanumeric string of given size in Java.
Example 1: Use SecureRandom
import java.security.SecureRandom;
public class Main {
//Create a String of the characters which can be included in the string
private static final String ALPHA_NUMERIC_STRING =
"ABCDEFGHIJKLMNOPQRSTUVWXY" +
"Zabcdefghijklmnopqrstuvwxyz0123456789";
// Driver code
public static void main(String[] args)
{
String randomAlphaNumericString = generateAlphaNumericString(25);
System.out.println(randomAlphaNumericString);
}
//Method to generate Random AlphaNumeric String
public static String generateAlphaNumericString(int length) {
SecureRandom random = new SecureRandom();
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; i++) {
builder.append(ALPHA_NUMERIC_STRING.
charAt(random.nextInt(ALPHA_NUMERIC_STRING.length())));
}
return builder.toString();
}
}
Console Output:
97Iv8KBcDHntD0nv8rj1964L1
Example 2: Apache Commons Text library
Download Apache Commons Text library:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.10.0</version>
</dependency>
Main.java:
import org.apache.commons.text.CharacterPredicates;
import org.apache.commons.text.RandomStringGenerator;
public class Main {
// Driver code
public static void main(String[] args)
{
String randomAlphaNumericString = generateAlphaNumericString(25);
System.out.println(randomAlphaNumericString);
}
//Method to generate Random AlphaNumeric String
public static String generateAlphaNumericString(int length) {
RandomStringGenerator randomStringGenerator =
new RandomStringGenerator.Builder()
.withinRange('0', 'z')
.filteredBy(CharacterPredicates.LETTERS,
CharacterPredicates.DIGITS)
.build();
return randomStringGenerator.generate(length);
}
}
Console Output:
cJWQyrKznpxXpVJXeVwlI5aVb