Question

How to Generate a Random Alphanumeric String in Java

javastringrandomalphanumeric

Question

I am looking for a simple Java algorithm to generate a pseudo-random alphanumeric string. In my case, it will be used as a session or key identifier that should be likely unique across 500,000 or more generated values.

Ideally, the algorithm should allow the string length to be configured based on the required level of uniqueness. For example, a generated string of length 12 might look like this:

AEYGF7K0DM1X

Short Answer

By the end of this page, you will understand how to generate random alphanumeric strings in Java, how to control their length, which random generator to choose, and how to think about practical uniqueness for IDs such as session tokens or temporary keys.

Concept

Random alphanumeric string generation means creating a string made from letters and digits, such as A-Z, a-z, and 0-9, where each character is chosen randomly.

In Java, this is usually done by:

  1. Defining a set of allowed characters
  2. Repeatedly picking random characters from that set
  3. Building a string of the desired length

A simple version often uses characters like:

ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789

This gives 36 possible characters for each position.

If you generate a 12-character string from 36 possible characters, the total number of possible combinations is:

36^12

That is a very large number, which makes collisions unlikely for many practical applications.

Why this matters

Developers use random strings for:

  • Session identifiers
  • Temporary access codes
  • Password reset tokens
  • Invitation codes
  • Order references
  • Test data generation

Pseudo-random vs secure random

This distinction is important:

  • Pseudo-random generators like Random are fine for basic non-security use cases.
  • Cryptographically secure generators like SecureRandom should be used for anything related to authentication, sessions, password resets, or security-sensitive identifiers.

Even if your uniqueness needs are modest, session identifiers are usually security-related, so SecureRandom is the safer choice in real applications.

Length affects uniqueness

The longer the string, the more possible combinations exist.

For example, using 36 characters:

  • Length 6: 36^6
  • Length 8: 36^8
  • Length 12: 36^12

So increasing length is the main way to reduce the chance of duplicates.

Mental Model

Imagine a bag filled with allowed characters:

A B C ... Z 0 1 2 ... 9

To build a random ID:

  • Reach into the bag
  • Pick one character
  • Write it down
  • Put it back
  • Repeat until the string is long enough

Each pick is independent, and the final result is just a sequence of random draws.

The bigger the bag and the more times you draw, the more unique combinations you can create.

So a random alphanumeric string is like making a custom license plate by choosing one random symbol at a time.

Take Quiz

Syntax and Examples

Basic approach in Java

import java.security.SecureRandom;

public class RandomStringGenerator {
    private static final String ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final SecureRandom RANDOM = new SecureRandom();

    public static String generate(int length) {
        StringBuilder result = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            int index = RANDOM.nextInt(ALPHANUMERIC.length());
            result.append(ALPHANUMERIC.charAt(index));
        }

        return result.toString();
    }

    public static void main(String[] args) {
        System.out.println(generate(12));
        System.out.println(generate(8));
    }
}

How it works

  • ALPHANUMERIC stores the characters we allow.
  • SecureRandom generates random numbers.
  • nextInt(ALPHANUMERIC.length()) gives a valid random index.
  • charAt(index) picks one character.
  • StringBuilder efficiently builds the final string.

Example output

AEYGF7K0DM1X
P8Z1M2QA

Lowercase and mixed-case version

If you want uppercase, lowercase, and digits:

private static final String ALPHANUMERIC =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

This increases the character set size and reduces collision chances further.

Reusable utility method with validation

import java.security.SecureRandom;

public class IdGenerator {
    private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final SecureRandom RANDOM = new SecureRandom();

    public static String randomId(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("length must be greater than 0");
        }

        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(CHARS.charAt(RANDOM.nextInt(CHARS.length())));
        }
        return sb.toString();
    }
}

This version is better for real code because it checks invalid input.

Step by Step Execution

Consider this code:

import java.security.SecureRandom;

public class Demo {
    private static final String CHARS = "ABC123";
    private static final SecureRandom RANDOM = new SecureRandom();

    public static String generate(int length) {
        StringBuilder sb = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            int index = RANDOM.nextInt(CHARS.length());
            sb.append(CHARS.charAt(index));
        }

        return sb.toString();
    }
}

Suppose we call:

generate(4)

Step-by-step trace

  • CHARS is "ABC123"
  • Its length is 6
  • The loop runs 4 times because we want a 4-character result

Possible loop execution:

  1. i = 0

    • nextInt(6) returns 2
    • CHARS.charAt(2) is 'C'
    • sb becomes "C"
  2. i = 1

    • nextInt(6) returns 4
    • CHARS.charAt(4) is '2'
    • sb becomes "C2"
  3. i = 2

    • nextInt(6) returns 0
    • CHARS.charAt(0) is 'A'
    • sb becomes "C2A"
  4. i = 3

    • nextInt(6) returns 5
    • CHARS.charAt(5) is '3'
    • sb becomes "C2A3"

The method returns:

C2A3

Every run may produce a different result because the indexes are random.

Real World Use Cases

Random alphanumeric strings are used in many common programming tasks.

Session and authentication flows

  • Session IDs for logged-in users
  • Password reset tokens
  • Email verification codes
  • One-time login links

For these, SecureRandom is strongly preferred.

Application identifiers

  • Temporary file names
  • Upload tracking IDs
  • Transaction references
  • Cache keys
  • Invitation or referral codes

Testing and development

  • Generating sample IDs for unit tests
  • Creating mock data for demos
  • Stress-testing systems with many unique identifiers

APIs and background jobs

  • Correlation IDs for logs
  • Job reference IDs
  • Request tracking tokens

In practice, developers often combine random strings with timestamps, prefixes, or database uniqueness checks depending on the business need.

Take Quiz

Real Codebase Usage

In real Java projects, random string generation is usually wrapped in a utility class or service instead of being written inline repeatedly.

Common patterns

Guard clauses for validation

Developers usually reject invalid lengths early:

if (length <= 0) {
    throw new IllegalArgumentException("length must be positive");
}

This keeps the method predictable.

Centralized character sets

Instead of repeating the allowed characters in multiple places, projects keep them in constants:

private static final String UPPERCASE_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

This makes changes easy and avoids inconsistency.

Dedicated ID generators

A service class may expose methods like:

String sessionId();
String referralCode();
String tempPassword();

Each method may use a different length or character set.

Uniqueness checks

If duplicates must not happen, developers do not rely on randomness alone. They often:

  • Check the database before saving
  • Regenerate on collision
  • Use database unique constraints
  • Use UUIDs where appropriate

Security-sensitive usage

For authentication, developers avoid Random and use SecureRandom because predictable values can be exploited.

Configuration-based lengths

A codebase may define lengths in config files:

session.id.length=32
invite.code.length=10

This avoids hardcoding values throughout the application.

Common Mistakes

1. Using Random for security-sensitive IDs

Broken example:

import java.util.Random;

Random random = new Random();

Why it is a problem:

  • Random is not meant for secure tokens
  • Session IDs and reset tokens should not be predictable

Better:

import java.security.SecureRandom;

SecureRandom random = new SecureRandom();

2. Forgetting to validate length

Broken example:

public static String generate(int length) {
    StringBuilder sb = new StringBuilder(length);
    // ...
    return sb.toString();
}

If length is 0 or negative, the method may behave unexpectedly or fail.

Better:

if (length <= 0) {
    throw new IllegalArgumentException("length must be greater than 0");
}

3. Building strings with + inside a loop

Broken example:

String result = "";
for (int i = 0; i < length; i++) {
    result += CHARS.charAt(random.nextInt(CHARS.length()));
}

Why it is a problem:

  • It creates many temporary string objects
  • It is less efficient than StringBuilder

Better:

StringBuilder sb = new StringBuilder(length);

4. Assuming random means guaranteed unique

A random generator reduces collision chances, but does not guarantee uniqueness.

If uniqueness is mandatory:

  • Add a unique constraint
  • Check before storing
  • Retry on collision

5. Using too short a length

Broken idea:

  • Generating 4-character IDs for a large system

Why it is risky:

  • Fewer possible combinations
  • More chance of duplicates

Choose a length based on the number of values you expect to generate.

6. Choosing a confusing character set

Sometimes characters like O and 0, or I and 1, are hard to distinguish.

If humans must type the code, use a safer set such as:

ABCDEFGHJKLMNPQRSTUVWXYZ23456789

This removes ambiguous characters.

Comparisons

Java options for random string generation

ApproachBest forSecurity levelNotes
RandomSimple non-sensitive random valuesLowFine for casual use, not for auth or sessions
SecureRandomTokens, session IDs, reset codesHighPreferred for security-related identifiers
UUID.randomUUID()General unique identifiersGood practical uniquenessFixed format, not customizable like a chosen length

Custom random string vs UUID

FeatureCustom alphanumeric stringUUID
Custom lengthYesNo
Custom character setYesNo
Easy to readOften yesSometimes less friendly
Common in databases and APIsYesYes
Good default uniquenessDepends on designYes

Uppercase-only vs mixed-case

Character setExampleProsCons
Uppercase + digitsAEYGF7K0DM1XEasy to read and typeFewer combinations than mixed-case
Uppercase + lowercase + digitsaE7kP2mX9qL0More combinationsHarder to read aloud or type manually

When to choose what

  • Choose custom alphanumeric strings when you want readable IDs and control over length.
  • Choose SecureRandom when IDs relate to security.
  • Choose UUIDs when you want a built-in unique identifier format with minimal setup.
Take Quiz

Cheat Sheet

Quick reference

Character set

String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

Secure generator

SecureRandom random = new SecureRandom();

Basic method

public static String generate(int length) {
    if (length <= 0) {
        throw new IllegalArgumentException("length must be greater than 0");
    }

    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
        sb.append(CHARS.charAt(random.nextInt(CHARS.length())));
    }
    return sb.toString();
}

Rules to remember

  • Use SecureRandom for session IDs and tokens
  • Use StringBuilder inside loops
  • Validate length
  • Random does not mean guaranteed unique
  • Longer strings reduce collision risk

Good defaults

  • Human-readable code: uppercase + digits
  • Security-sensitive ID: SecureRandom
  • Mandatory uniqueness: combine randomness with database constraints or retries

Ambiguous characters to avoid for user-facing codes

0 O 1 I l

Alternative built-in option

UUID.randomUUID().toString()

Use this when custom length and character set are not required.

FAQ

Is Random good enough for generating session IDs in Java?

Usually no. For session IDs and other security-sensitive values, use SecureRandom.

How long should a random alphanumeric string be?

It depends on how many values you need and how low you want the collision risk to be. For many practical cases, 12 or more characters is a reasonable starting point.

Does a random string guarantee uniqueness?

No. It only makes collisions unlikely. If uniqueness is required, add a database unique constraint or a collision check.

Should I use a UUID instead of a random string?

Use a UUID when you want a built-in unique identifier format. Use a custom random string when you need a specific length or character set.

Can I include lowercase letters too?

Yes. Adding lowercase letters increases the number of possible combinations.

What is the best class to build the string in Java?

StringBuilder is the usual choice because it is efficient for repeated appends in a loop.

Why avoid characters like O and 0?

They can be confused by users when reading or typing codes manually.

Can I generate 500,000 IDs with this approach?

Yes, that is practical with a sensible character set and sufficient length, but collisions are still theoretically possible, so enforce uniqueness if it matters.

Take Quiz

Mini Project

Description

Build a small Java utility that generates invitation codes for a web application. Each code should be uppercase and numeric only, have a configurable length, and be suitable for generating many likely-unique values. This demonstrates how to define a character set, use SecureRandom, validate input, and generate repeatable utility methods for real applications.

Goal

Create a Java program that generates configurable random alphanumeric invitation codes and prints several sample codes.

Requirements

  1. Create a method that accepts the desired code length.
  2. Use uppercase letters and digits as the allowed characters.
  3. Validate that the requested length is greater than 0.
  4. Use SecureRandom to select characters.
  5. Print at least 5 generated codes from main.
Take Quiz

Keep learning

Related questions

View more