Skip to content

How to generate a random alpha-numeric string

To generate a random alpha-numeric string in Java, you can use the Random class to select characters from a combined pool of digits and letters, then append them to a StringBuilder. Here's an example of how you might do this:


java
import java.util.Random;

// Set the length of the string
int length = 10;

// Create a StringBuilder to store the string
StringBuilder sb = new StringBuilder();

// Create a Random object
Random random = new Random();

// Define the pool of alphanumeric characters
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

// Generate random characters and append them to the StringBuilder
for (int i = 0; i < length; i++) {
  // Select a random character from the pool
  char letter = chars.charAt(random.nextInt(chars.length()));
  sb.append(letter);
}

// Convert the StringBuilder to a String and print it
String randomString = sb.toString();
System.out.println(randomString);

This code will generate a random string that is exactly 10 characters long and consists of a combination of digits (0-9) and letters (a-z or A-Z).

For security-sensitive use cases, consider replacing java.util.Random with java.security.SecureRandom.

I hope this helps! Let me know if you have any other questions.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.