How to generate a random alpha-numeric string

I've been seeking a straightforward Java algorithm to create a pseudo - random alpha - numerical string. In my scenario it would certainly be made use of as an one-of-a-kind session/key identifier that would certainly "likely" be one-of-a-kind over 500K+ generation (my demands do not actually call for anything far more innovative).

Preferably, I would certainly have the ability to define a size relying on my individuality requires. As an example, a created string of size 12 could look something like "AEYGF7K0DM1X".

2022-06-07 15:16:05
Source Share
Answers: 5

If you enjoy to make use of Apache courses, you can make use of org.apache.commons.text.RandomStringGenerator (Apache Commons Text).


RandomStringGenerator randomStringGenerator =
        new RandomStringGenerator.Builder()
                .withinRange('0', 'z')
                .filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)
randomStringGenerator.generate(12); // toUpperCase() if you want

Since Apache Commons Lang 3.6, RandomStringUtils is deprecated.

2022-06-08 01:54:18

I located this remedy that creates a random hex inscribed string. The given device examination appears to stand up to my key usage instance. Although, it is a little extra intricate than several of the various other solutions given.

 * Generate a random hex encoded string token of the specified length
 * @param length
 * @return random hex string
public static synchronized String generateUniqueToken(Integer length){ 
    byte random[] = new byte[length];
    Random randomGenerator = new Random();
    StringBuffer buffer = new StringBuffer();


    for (int j = 0; j < random.length; j++) {
        byte b1 = (byte) ((random[j] & 0xf0) >> 4);
        byte b2 = (byte) (random[j] & 0x0f);
        if (b1 < 10)
            buffer.append((char) ('0' + b1));
            buffer.append((char) ('A' + (b1 - 10)));
        if (b2 < 10)
            buffer.append((char) ('0' + b2));
            buffer.append((char) ('A' + (b2 - 10)));
    return (buffer.toString());

public void testGenerateUniqueToken(){
    Set set = new HashSet();
    String token = null;
    int size = 16;

    /* Seems like we should be able to generate 500K tokens 
     * without a duplicate 
    for (int i=0; i<500000; i++){
        token = Utility.generateUniqueToken(size);

        if (token.length() != size * 2){
            fail("Incorrect length");
        } else if (set.contains(token)) {
            fail("Duplicate token generated");
        } else{
2022-06-07 17:11:45

Java provides a means of doing this straight. If you do not desire the dashboards, they are very easy to remove out. Simply make use of uuid.replace("-", "")

import java.util.UUID;

public class randomStringGenerator {
    public static void main(String[] args) {

    public static String generateString() {
        String uuid = UUID.randomUUID().toString();
        return "uuid = " + uuid;


uuid = 2d7428a6-b58c-4008-8575-f05549f16316
2022-06-07 17:11:40

Here it remains in Java:

import static java.lang.Math.round;
import static java.lang.Math.random;
import static java.lang.Math.pow;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static org.apache.commons.lang.StringUtils.leftPad

public class RandomAlphaNum {
  public static String gen(int length) {
    StringBuffer sb = new StringBuffer();
    for (int i = length; i > 0; i -= 12) {
      int n = min(12, abs(i));
      sb.append(leftPad(Long.toString(round(random() * pow(36, n)), 36), n, '0'));
    return sb.toString();

Here is an example run:

scala> RandomAlphaNum.gen(42)
res3: java.lang.String = uja6snx21bswf9t89s00bxssu8g6qlu16ffzqaxxoy
2022-06-07 15:52:57


To create a random string, concatenate personalities attracted arbitrarily from the set of appropriate icons till the string gets to the wanted size.


Here is some rather straightforward and also really adaptable code for creating random identifiers. Read the details that adheres to for vital application notes.

public class RandomString {

     * Generate a random string.
    public String nextString() {
        for (int idx = 0; idx < buf.length; ++idx)
            buf[idx] = symbols[random.nextInt(symbols.length)];
        return new String(buf);

    public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static final String lower = upper.toLowerCase(Locale.ROOT);

    public static final String digits = "0123456789";

    public static final String alphanum = upper + lower + digits;

    private final Random random;

    private final char[] symbols;

    private final char[] buf;

    public RandomString(int length, Random random, String symbols) {
        if (length < 1) throw new IllegalArgumentException();
        if (symbols.length() < 2) throw new IllegalArgumentException();
        this.random = Objects.requireNonNull(random);
        this.symbols = symbols.toCharArray();
        this.buf = new char[length];

     * Create an alphanumeric string generator.
    public RandomString(int length, Random random) {
        this(length, random, alphanum);

     * Create an alphanumeric strings from a secure generator.
    public RandomString(int length) {
        this(length, new SecureRandom());

     * Create session identifiers.
    public RandomString() {


Usage instances

Create a troubled generator for 8 - personality identifiers:

RandomString gen = new RandomString(8, ThreadLocalRandom.current());

Create a safe and secure generator for session identifiers:

RandomString session = new RandomString();

Create a generator with very easy - to - read codes for printing. The strings are longer than complete alphanumeric strings to make up for making use of less icons:

String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
RandomString tickets = new RandomString(23, new SecureRandom(), easy);

Use as session identifiers

Generating session identifiers that are most likely to be one-of-a-kind is unsatisfactory, or you can simply make use of a straightforward counter. Opponents pirate sessions when foreseeable identifiers are made use of.

There is stress in between size and also security. Much shorter identifiers are less complicated to presume, due to the fact that there are less opportunities. Yet much longer identifiers eat even more storage space and also transmission capacity. A bigger set of icons aids, yet could create inscribing troubles if identifiers are consisted of in URLs or re - gotten in by hand.

The underlying resource of randomness, or worsening, for session identifiers need to originate from a random number generator made for cryptography. Nonetheless, booting up these generators can occasionally be computationally pricey or slow-moving, so initiative needs to be made to re - usage them when feasible.

Usage as object identifiers

Not every application calls for security. Random assignment can be a reliable means for numerous entities to create identifiers in a common room with no control or partitioning. Control can be slow-moving, specifically in a gathered or dispersed setting, and also dividing a room creates troubles when entities wind up with shares that are also tiny or also large.

Identifiers created without taking actions to make them uncertain need to be shielded by various other methods if an opponent could be able to watch and also adjust them, as takes place in the majority of internet applications. There need to be a different consent system that shields things whose identifier can be presumed by an opponent without accessibility approval.

Treatment has to be additionally be required to make use of identifiers that are long sufficient to make crashes not likely offered the awaited complete variety of identifiers. This is described as "the birthday celebration paradox." The probability of a collision, p , is about n 2/ (2q x ), where n is the variety of identifiers in fact created, q is the variety of distinctive icons in the alphabet, and also x is the size of the identifiers. This need to be a really handful, like 2 50 or much less.

Functioning this out programs that the opportunity of crash amongst 500k 15 - personality identifiers has to do with 2 52 , which is possibly much less most likely than unseen mistakes from planetary rays, etc.

Contrast with UUIDs

According to their requirements, UUIDs are not made to be uncertain, and also need to not be made use of as session identifiers.

UUIDs in their typical layout take a great deal of room: 36 personalities for just 122 littles worsening. (Not all littles a "random" UUID are picked arbitrarily.) An arbitrarily picked alphanumeric string loads even more worsening in simply 21 personalities.

UUIDs are not adaptable ; they have a standard framework and also format. This is their primary merit along with their major weak point. When teaming up with an outdoors event, the standardization supplied by UUIDs might be handy. For totally inner usage, they can be ineffective.

2022-06-07 15:46:19