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:
- Defining a set of allowed characters
- Repeatedly picking random characters from that set
- 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
Randomare fine for basic non-security use cases. - Cryptographically secure generators like
SecureRandomshould 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 is the safer choice in real applications.
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.
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 {
System.out.println(generate());
System.out.println(generate());
}
}
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)
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.
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.
Common Mistakes
1. Using Random for security-sensitive IDs
Broken example:
import java.util.Random;
Random random = new Random();
Why it is a problem:
Randomis 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 is or negative, the method may behave unexpectedly or fail.
Comparisons
Java options for random string generation
| Approach | Best for | Security level | Notes |
|---|---|---|---|
Random | Simple non-sensitive random values | Low | Fine for casual use, not for auth or sessions |
SecureRandom | Tokens, session IDs, reset codes | High | Preferred for security-related identifiers |
UUID.randomUUID() | General unique identifiers | Good practical uniqueness | Fixed format, not customizable like a chosen length |
Custom random string vs UUID
| Feature | Custom alphanumeric string | UUID |
|---|
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
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.
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
- Create a method that accepts the desired code length.
- Use uppercase letters and digits as the allowed characters.
- Validate that the requested length is greater than 0.
- Use
SecureRandomto select characters. - Print at least 5 generated codes from
main.
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.