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

More related topics,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete