Generate Random String in Java: Simple Code & Tips

How-to basics · Updated November 23, 2026

To generate a random string in Java, use java.util.UUID.randomUUID().toString() for a quick, unique, 36-character string, or build your own with java.security.SecureRandom and a character set for custom lengths and characters. This article explains the main methods, how to choose between them, and common pitfalls to avoid.

Why You Might Need a Random String

Random strings appear in many real-world Java applications:

  • Session IDs or tokens for authentication
  • Password reset links or verification codes
  • File names or temporary directory names
  • Unique database keys when you don’t want an auto-increment number
  • Test data for unit tests or load testing

Each use case has different requirements: some need uniqueness, some need unpredictability, and some just need to look random. The right approach depends on which of these matters most.

Method 1: Using UUID (Simplest)

The UUID class generates a 128-bit value formatted as 36 characters (32 hex digits plus 4 hyphens). It’s built into Java, requires no extra libraries, and is unique enough for most non-security purposes.

String random = UUID.randomUUID().toString();
// Example output: 3f2a8c1e-9b4d-4f6a-8c3e-1a2b3c4d5e6f

Pros: One line, no dependencies, extremely low collision risk.
Cons: Contains hyphens, only uses hex characters (0-9, a-f), and is not cryptographically secure (though UUID v4 uses random bits, the format is predictable).

If you need a string without hyphens, replace them: UUID.randomUUID().toString().replace("-", "").

Method 2: Using SecureRandom with Custom Character Set

For full control over length and characters, use java.security.SecureRandom (or java.util.Random for non-security cases). Here’s a reusable method:

import java.security.SecureRandom;

public static String generateRandomString(int length, String charset) {
    SecureRandom random = new SecureRandom();
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
        int index = random.nextInt(charset.length());
        sb.append(charset.charAt(index));
    }
    return sb.toString();
}

// Example usage:
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
String random = generateRandomString(10, alphabet);

This method lets you specify exactly which characters appear. For a 10-character alphanumeric string, the example returns something like a8Kd3PqZx2.

Choosing Between Random and SecureRandom

Java has two main random number generators:

  • java.util.Random – fast, but not cryptographically secure. Use for test data, random game elements, or any non-security purpose.
  • java.security.SecureRandom – slower, but produces unpredictable values. Use for passwords, tokens, session IDs, or anything that could be attacked.

Rule of thumb: If a human could gain an advantage by guessing the string, use SecureRandom. Otherwise, Random is fine.

Common Pitfalls and How to Avoid Them

Several mistakes appear frequently when generating random strings in Java:

  1. Using Math.random() for character selection – This works but is less readable and not secure. Prefer Random or SecureRandom.
  2. Forgetting to specify a character set – If you use UUID but need only digits, you’ll have to filter or convert, which is messy.
  3. Using Random for security tokens – This is a serious vulnerability. Always use SecureRandom for anything security-related.
  4. Not handling empty or null inputs – If your character set is empty, nextInt(0) throws an exception. Add a check.
  5. Creating a new SecureRandom every call – This is wasteful. Create one instance and reuse it (it’s thread-safe).

Performance and Thread Safety

Random and SecureRandom are both thread-safe, so you can share a single instance across threads. However, SecureRandom can be slow to initialize (it may block while gathering entropy), so create it once and reuse it.

For high-throughput scenarios (e.g., generating millions of strings), Random is faster. If you need both speed and security, consider using ThreadLocalRandom (which is not secure) or SecureRandom with a pre-seeded instance (but be careful: seeding a SecureRandom yourself can weaken security if done incorrectly).

Alternatives and Libraries

If you don’t want to write your own method, several libraries offer random string utilities:

  • Apache Commons Lang – RandomStringUtils.randomAlphanumeric(int) is a one-liner. Note: it uses Random, not SecureRandom.
  • Google Guava – BaseEncoding.base64().encode(byte[]) can generate random base64 strings from random bytes.
  • Passay – For password-specific generation with rules (e.g., must contain an uppercase letter).

These libraries add dependencies but save time if you already use them.

Frequently Asked Questions

How do I generate a random alphanumeric string of a specific length?
Use the SecureRandom method above with a character set that includes letters and digits. For example, generateRandomString(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789").

Is UUID.randomUUID() cryptographically secure?
Not strictly. UUID v4 uses random bits, but the format is predictable and the spec doesn’t guarantee cryptographic strength. For security tokens, use SecureRandom to generate bytes and encode them (e.g., Base64).

Can I generate a random string without any special characters?
Yes, define a character set that excludes symbols. The UUID method only uses hex and hyphens, so if you need only letters and digits, use a custom method.

Why does my random string sometimes contain the same character twice?
That’s expected. Random selection with replacement allows duplicates. If you need unique characters, use a shuffle approach (e.g., copy the charset to a list, shuffle, take first n).

What’s the difference between Random and SecureRandom?
Random is fast and uses a deterministic algorithm (linear congruential generator). SecureRandom uses an unpredictable entropy source and is slower but secure. Use SecureRandom for anything that could be attacked.

How do I generate a random string in Java 8 or earlier?
The same methods work. UUID and SecureRandom have been available since Java 1.5 and 1.4 respectively. No special version needed.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.