Algorithm

To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.

Implementation

Here's some fairly simple and very flexible code for generating random identifiers. Read the information that follows for important 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() {
        this(21);
    }

}

Usage examples

Create an insecure generator for 8-character identifiers:

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

Create a secure generator for session identifiers:

RandomString session = new RandomString();

Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:

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

Use as session identifiers

Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.

There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.

The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.

Use as object identifiers

Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.

Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.

Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." The probability of a collision, p, is approximately n2/(2qx), where n is the number of identifiers actually generated, q is the number of distinct symbols in the alphabet, and x is the length of the identifiers. This should be a very small number, like 2โ€‘50 or less.

Working this out shows that the chance of collision among 500k 15-character identifiers is about 2โ€‘52, which is probably less likely than undetected errors from cosmic rays, etc.

Comparison with UUIDs

According to their specification, UUIDs are not designed to be unpredictable, and should not be used as session identifiers.

UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.

UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.

Top answer
1 of 16
1642

Algorithm

To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.

Implementation

Here's some fairly simple and very flexible code for generating random identifiers. Read the information that follows for important 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() {
        this(21);
    }

}

Usage examples

Create an insecure generator for 8-character identifiers:

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

Create a secure generator for session identifiers:

RandomString session = new RandomString();

Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:

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

Use as session identifiers

Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.

There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.

The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.

Use as object identifiers

Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.

Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.

Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." The probability of a collision, p, is approximately n2/(2qx), where n is the number of identifiers actually generated, q is the number of distinct symbols in the alphabet, and x is the length of the identifiers. This should be a very small number, like 2โ€‘50 or less.

Working this out shows that the chance of collision among 500k 15-character identifiers is about 2โ€‘52, which is probably less likely than undetected errors from cosmic rays, etc.

Comparison with UUIDs

According to their specification, UUIDs are not designed to be unpredictable, and should not be used as session identifiers.

UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.

UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.

2 of 16
903

Java supplies a way of doing this directly. If you don't want the dashes, they are easy to strip out. Just use uuid.replace("-", "")

import java.util.UUID;

public class randomStringGenerator {
    public static void main(String[] args) {
        System.out.println(generateString());
    }

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

Output

uuid = 2d7428a6-b58c-4008-8575-f05549f16316
๐ŸŒ
Java67
java67.com โ€บ 2018 โ€บ 01 โ€บ how-to-create-random-alphabetic-or-alphanumeric-string-java.html
How to Create Random Alphabetic or AlphaNumeric String of given length in Java? SecureRandom Example | Java67
If you want to know more about ThreadLocalRandom and SecureRandom and their difference, I suggest you check these advanced Java Performance courses for experienced Java developers. It's a great resource for anyone who wants to learn advanced Java concepts. Now, that you know how you can use SecureRandom or ThreadLocalRandom class to generate a random string of given length and characters e.g. alphabetic, alphanumeric, and numeric.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ generate-random-string-of-given-size-in-java
Generate random String of given size in Java - GeeksforGeeks
July 11, 2025 - // Java program generate a random AlphaNumeric String // using CharSet method import java.util.*; import java.nio.charset.*; class RandomString { static String getAlphaNumericString(int n) { // length is bounded by 256 Character byte[] array ...
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2021 โ€บ 05 โ€บ 3-examples-to-generate-random-alphanumeric-string-in-java0.html
3 Examples to Generate Random Alphanumeric String in Java - UUID Example
="abcdefghijklmnopqrstuvwxyzABCDEFGHIJK LMNOPQRSTUVWXYZ0123456789".toCharArray(); StringBuilder random = new StringBuilder(); for(int i =0; i < length; i++) { int index = (int) (Math.random()ALPHANUMERIC.length); random.append(ALPHANUMERIC[index]); ...
๐ŸŒ
CodeJava
codejava.net โ€บ coding โ€บ generate-random-strings-examples
Generate Random Strings in Java Examples
First we define a String object alphanumericCharacters that contains all letters and numbers. Then we generate a random String with each character is randomly chosen from the predefined set.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 372158 โ€บ java โ€บ Generating-random-alphanumeric-strings
Generating random alphanumeric strings. (Java in General forum at Coderanch)
You can convert this int n to a character: Then just put six of these in a StringBuffer, and you've got a random ID. If you need to make sure no ID is ever repeated, you could add a HashSet which stores all the IDs used so far, and check each new random ID to see if it's in the set.
๐ŸŒ
Quickprogrammingtips
quickprogrammingtips.com โ€บ java โ€บ random-alphanumeric-generator-in-java.html
Random Alphanumeric Generator in Java
It is also possible to specify a subset of character set in the random string by modifying the CHARACTER_SET variable. import java.security.SecureRandom; // Example - Random alphanumeric generator in Java public class RandomAlphaNumericGenerator { private static SecureRandom random = new SecureRandom(); private static final String CHARACTER_SET="0123456789abcdefghijklmnopqrstuvwxyz"; public static void main(String[] args) { System.out.println("Random Alphanumeric String:"+getRandomString(32)); } // Create a random alphanumeric string private static String getRandomString(int len) { StringBuffer buff = new StringBuffer(len); for(int i=0;i<len;i++) { int offset = random.nextInt(CHARACTER_SET.length()); buff.append(CHARACTER_SET.substring(offset,offset+1)); } return buff.toString(); } }
๐ŸŒ
codippa
codippa.com โ€บ home โ€บ how to generate random string in java / 4 ways to generate random string in java
How to generate random string in java / 4 ways to generate random string in java - codippa
January 13, 2025 - Its static randomUUID method acts as a random alphanumeric generator and returns a String of 32 characters. If you want a string of a fixed length or shorter than 32 characters, you can use substring method of java.lang.String.
Find elsewhere
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java โ€บ java โ€“ how to generate a random string
Java - How to generate a random String - Mkyong.com
May 4, 2019 - Generate a random String of 32 alphanumeric characters (hexadecimal) and 4 hyphens, read this UUID format ... package com.mkyong; import java.util.UUID; public class UUIDExample { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println(generateRandomStringByUUIDNoDash()); } for (int i = 0; i < 10; i++) { System.out.println(generateRandomStringByUUIDNoDash()); } } public static String generateRandomStringByUUID() { return UUID.randomUUID().toString(); } public static String generateRandomStringByUUIDNoDash() { return UUID.randomUUID().toString().replace("-", ""); } }
๐ŸŒ
Xperti
xperti.io โ€บ home โ€บ generate random string in java
Easiest Ways To Generate A Random String In Java
May 9, 2022 - This function also takes an integer as an argument and returns a numeric string of that length. It returns a random alphanumeric string consisting of upper case, lower case and digits.
๐ŸŒ
JavaMadeSoEasy
javamadesoeasy.com โ€บ 2015 โ€บ 12 โ€บ example-to-generate-random-alphanumeric.html
JavaMadeSoEasy.com (JMSE): Example to generate random alphanumeric string in java
In the above program 6 is length of random alphanumeric string to be generated. ... Must read : 5 programs to Generate random numbers in given specific range before java 7, in java 7 and java 8
๐ŸŒ
DZone
dzone.com โ€บ data engineering โ€บ data โ€บ generate a random alpha numeric string
Generate a Random Alpha Numeric String
August 9, 2012 - private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; public static String randomAlphaNumeric(int count) { StringBuilder builder = new StringBuilder(); while (count-- != 0) { int character = (int)(Math.r...
๐ŸŒ
W3Schools Blog
w3schools.blog โ€บ home โ€บ how to create random alphanumeric in java?
how to create random alphanumeric in java?
October 1, 2024 - It provides several methods to generate random numbers of type integer, double, long, float etc. Note: Random class objects are not suitable for security sensitive applications so it is better to use java.security.SecureRandom in these cases. package com.w3schools; import java.util.Random; public class Test { private static final String CHAR_LIST = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static final int RANDOM_STRING_LENGTH = 10; public String randomString(){ StringBuffer randomString = new StringBuffer(); for(int i=0; i<RANDOM_STRING_LENGTH; i++){ int number
Top answer
1 of 4
7
for
        (double i = 0; i < length; i++)

And related loops should have the "for" on the same line (as this is a common coding convention.)

(randroll <= (1.0 / 36.0 * j))

This doesn't have to be a double; instead, the random number can be generated as an integer (to select which element from the array.)

randchar = '@';

Unless the random string is not random, I would not initialize the variables with sample data. I'd just leave them blank and then adjust the loop to always run at least once (a do-while loop) so that it becomes initialized.

for
            (int j = 1; j <= 36; j++)
            {
                if
                (randroll <= (1.0 / 36.0 * j))
                {
                    randchar = charstring.charAt(j - 1);
                    break;
                }
            }

I would remove the inner if-statement and un-hardcode the values so it can work with strings with any size. Applying these suggestions, it can be simplified to:

import java.util.Random;
class Main {
  public static void main(String[] args) {
    int strLen = 100;
    String randString = "";
    Random r = new Random();
    String[] chars = "abcdefghijklmnopqrstuvwxyz0123456789".split("");
    while (randString.length() < strLen)
        randString += chars[randBetween(r, 0, chars.length - 1)];

    System.out.println(randString);
  }

  /*
  Generates a random number from min to max inclusive
  */
  public static int randBetween(Random r, int min, int max) {
    return r.nextInt((max - min) + 1) + min;
  }
}

This approach is not optimal as the string is constantly being appended to, meaning that the string has to be re-copied every iteration.

Java introduced Streams, which allows reading forever from certain generators. Knowing this, we can read a stream of random numbers up until the string length that the user wants, and then get the character at the random string length:

import java.util.Random;
class Main {
  public static void main(String[] args) {
    int strLen = 100;
    String chars = "abcdefghijklmnopqrstuvwxyz0123456789";

    StringBuilder randomOutput = new StringBuilder();
    new Random().ints(strLen, 0, chars.length())
                .forEach(c -> randomOutput.append(chars.charAt(c)));

    System.out.println(randomOutput);
  }
}

StringBuilder is used to append the random character as it doesn't have to be re-copied for every loop iteration.

2 of 4
6

Separate random generator

I would either extract the random number generator into an extra method, or simply use new Random().nextInt(36) from package java.util to generate a random integer between 0 and 35 (both inclusive).

You could also make the method more generic by adding boundary parameters (min, max). So you can reuse within other limitations.

See: Math.random() explanation

Variable names

Typical Java convention would name things using Camel-case. Also following Cleancode would put as much meaning into their names.

So variables (except simple loop counters) can be renamed:

  • characterOptions or possibleCharacters or alphaNumericChars
  • randomCharacterChoice or randomCharIndex
  • randomString or randomAlphaNumericSequence
๐ŸŒ
Kodejava
kodejava.org โ€บ how-do-i-generate-random-alphanumeric-strings
How do I generate random alphanumeric strings? - Learn Java by Examples
The following code snippet demonstrates how to use RandomStringGenerator class from the Apache Commons Text library to generate random strings. To create an instance of the generator we can use the RandomStringGenerator.Builder() class build() method. The builder class also helps us to configure ...
๐ŸŒ
Java Lessons
javalessons.com โ€บ home โ€บ blog โ€บ generating random strings: detailed explanation
Java Generating Random Strings: Step-By-Step Guide
October 9, 2023 - How can I generate a random string with a specific length? You can specify the length of the random string by controlling the number of characters generated. For example, you can use the limit() method when using Java 8 ...
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ examples โ€บ generate-random-string
Java Program to Create random strings
import java.util.Random; class ... = "abcdefghijklmnopqrstuvwxyz"; String numbers = "0123456789"; // combine all strings String alphaNumeric = upperAlphabet + lowerAlphabet + numbers; // create random string builder StringBuilder sb = new StringBuilder(); // create an object ...
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ java โ€บ random alphanumeric string in java
How to Generate Random String in Java | Delft Stack
February 2, 2024 - import java.nio.charset.*; import java.util.*; class AlphaNumericStringGenerator { static String getRandomString(int i) { byte[] bytearray; String mystring; StringBuffer thebuffer; bytearray = new byte[256]; new Random().nextBytes(bytearray); mystring = new String(bytearray, Charset.forName("UTF-8")); // Create the StringBuffer thebuffer = new StringBuffer(); for (int m = 0; m < mystring.length(); m++) { char n = mystring.charAt(m); if (((n >= 'A' && n <= 'Z') || (n >= '0' && n <= '9')) && (i > 0)) { thebuffer.append(n); i--; } } // resulting string return thebuffer.toString(); } public static void main(String[] args) { // the random string length int i = 15; // output System.out.println("A random string: " + getRandomString(i)); } }
๐ŸŒ
Medium
medium.com โ€บ beingcoders โ€บ ways-to-generate-random-string-in-java-6d3b1d964c02
Ways to Create a Random String in Java: Ultimate Guide with Scenarios | BeingCoders
March 16, 2025 - I am writing this article to explore different ways to make a random string using various libraries, I explored it and found it awesome to generate a random string with one-liner code. It will definitely save you a lot of time too. Mostly, I love the approach using the Apache Commons Lang library, it's so simple and effective, using a single line you can do many things in the code, anyway letโ€™s move ahead! Letโ€™s have a deep dive into different available ways to make a random String in java. Java 8 Introduced Random.ints,โ€” to generate an alphabetic String,