How to generate random alphanumeric strings with a custom length in Java

A lot of developers don't know how to generate random string with letters and digits. This feature can be really useful to generate random identifiers that we'll use temporary for some sake. In Java, there's a plenty way to generate such strings.

In this article, we will show you 3 alternatives to generate random strings with Java easily.

A. Generate random alphanumeric string with specific characters [a-ZA-Z0-9]

In order to generate a random string with a custom implementation, you can use the following method as helper in your own project:

import java.security.SecureRandom;

/**
 * This method returns a random string generated with SecureRandom
 * 
 * @param length
 * @return 
 */
public static String generateRandomString(int length) {
    // You can customize the characters that you want to add into
    // the random strings
    String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz";
    String CHAR_UPPER = CHAR_LOWER.toUpperCase();
    String NUMBER = "0123456789";

    String DATA_FOR_RANDOM_STRING = CHAR_LOWER + CHAR_UPPER + NUMBER;
    SecureRandom random = new SecureRandom();

    if (length < 1) throw new IllegalArgumentException();

    StringBuilder sb = new StringBuilder(length);
    
    for (int i = 0; i < length; i++) {
        // 0-62 (exclusive), random returns 0-61
        int rndCharAt = random.nextInt(DATA_FOR_RANDOM_STRING.length());
        char rndChar = DATA_FOR_RANDOM_STRING.charAt(rndCharAt);

        sb.append(rndChar);
    }

    return sb.toString();
}

This class implements a random string generator using the SecureRandom class of Java.security. This class provides a cryptographically strong random number generator (RNG). A cryptographically strong random number minimally complies with the statistical random number generator tests specified in FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1. Additionally, SecureRandom must produce non-deterministic output. Therefore any seed material passed to a SecureRandom object must be unpredictable, and all SecureRandom output sequences must be cryptographically strong. 

You only need to basically call the generateRandomString method providing as first argument the length of the string that you want to generate, for example:

// Your own package
package com.ourcodeworld.mavensandbox;

// Import required class
import java.security.SecureRandom;

/**
 * Basic example of random strings with SecureRandom
 * 
 */
public class Index {
    
    public static void main(String[] args){
        for (int i = 0; i < 5; i++) {
            System.out.println("Random string: " + generateRandomString(10));
            System.out.println("\n");
        }
    }
    
    /**
     * This method returns a random string generated with SecureRandom
     * 
     * @param length
     * @return 
     */
    public static String generateRandomString(int length) {
        String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz";
        String CHAR_UPPER = CHAR_LOWER.toUpperCase();
        String NUMBER = "0123456789";

        String DATA_FOR_RANDOM_STRING = CHAR_LOWER + CHAR_UPPER + NUMBER;
        SecureRandom random = new SecureRandom();
    
        if (length < 1) throw new IllegalArgumentException();

        StringBuilder sb = new StringBuilder(length);
        
        for (int i = 0; i < length; i++) {
            // 0-62 (exclusive), random returns 0-61
            int rndCharAt = random.nextInt(DATA_FOR_RANDOM_STRING.length());
            char rndChar = DATA_FOR_RANDOM_STRING.charAt(rndCharAt);

            sb.append(rndChar);
        }

        return sb.toString();
    }
}

The previous class generates within a loop 5 random strings that will be printed in the console, it will output something like:

Random string: iU5OHBDJ34

Random string: PDfkpDQMYz

Random string: 7OXEtv4PTT

Random string: CvYpocv3bE

Random string: yyBeOe5cee

B. Generate random string Apache Commons Lang

If you don't want to implement by your own this feature, you can rely on a third party package, specifically one of Apache. The standard Java libraries fail to provide enough methods for manipulation of its core classes. Apache Commons Lang provides these extra methods.

The Commons Lang package provides a host of helper utilities for the java.lang API, notably String manipulation methods, basic numerical methods, object reflection, concurrency, creation and serialization and System properties. Additionally it contains basic enhancements to java.util.Date and a series of utilities dedicated to help with building methods, such as hashCode, toString and equals.

If you use maven to handle dependencies of your project, modify the pom.xml file and add the package as a dependency:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

Or you can download the .jar file of the package and manually add it to your project. For more information about this package, please visit the official page at the Maven Repository. After including the package in your project, you will be able to import the RandomStringUtils class from the package. In this class you can call the static methods to generate random strings:

  • RandomStringUtils.randomNumeric: Creates a random string whose length is the number of characters specified.
  • RandomStringUtils.randomAlphabetic: Creates a random string whose length is between the inclusive minimum and the exclusive maximum. Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z).
  • RandomStringUtils.randomAlphanumeric: Creates a random string whose length is the number of characters specified. Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z) and the digits 0-9.

For example:

package com.ourcodeworld.mavensandbox;

// Import required class
import org.apache.commons.lang3.RandomStringUtils;

/**
 * Basic example of random strings with RandomStringUtils
 * 
 */
public class Index {
    
    public static void main(String[] args){
        System.out.println("\nNumeric string: [0-9]");

        System.out.println(RandomStringUtils.randomNumeric(10));

        System.out.println("\nAlphabetic String: [a-zA-Z]");

        System.out.println(RandomStringUtils.randomAlphabetic(10));

        System.out.println("\nAlphanumeric String: [a-zA-Z0-9]");

        System.out.println(RandomStringUtils.randomAlphanumeric(10));
    }
}

This code will generate an output like:

Numeric string: [0-9]
9688507775

Alphabetic String: [a-zA-Z]
BdNbwFqntH

Alphanumeric String: [a-zA-Z0-9]
IZdNATmcQs

C. Generating an universally unique identifier (UUID)

In case that you want to generate an UUID in Java, the util package of Java offers already a feature to generate such ID. The UUID class of Java.util represents an immutable universally unique identifier (UUID). A UUID represents a 128-bit value. There exist different variants of these global identifiers. The methods of this class are for manipulating the Leach-Salz variant, although the constructors allow the creation of any variant of UUID (described below).

We will show you how to generate this UUID with 2 variants, the first one generates the ID with dashes (default implementation) and the second one without the dashes:

package com.ourcodeworld.mavensandbox;

// Import required class
import java.util.UUID;

/**
 * Basic example of random strings with randomUUID
 * 
 */
public class Index {
    
    public static void main(String[] args){
        for (int i = 0; i < 5; i++) {
            System.out.println(generateRandomUUID());
        }

        for (int i = 0; i < 5; i++) {
            System.out.println(generateRandomUUIDWithoutDash());
        }
    }
    
     public static String generateRandomUUID() {
        return UUID.randomUUID().toString();
    }

    public static String generateRandomUUIDWithoutDash() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}

This will generate the following output:

eccfd644-07b0-4817-ae37-da394cc1e6d3
87d6524d-5892-437c-b8fa-a06f5f98f3a2
35949777-141d-4a7f-a868-d385f0c6d86a
1528594e-9687-42df-937d-241637746056
dc9b998a-83f2-4e83-83ba-9b0f5ba0be7a


b5cdbc574e8a4294b402234321818a4e
6b450556572d47228ea03bacf335c3ec
475d7823bd2d41c2a28b72aea6933526
eb1dba5a4e864bc1aa4655e671cd5201
ea40ef86685f4508a5429835d1aba78a

Happy coding !

This could interest you

Become a more social person