How to generate a random string in Java without losing your mind?
\n\nImagine: you're writing a registration form for a website. You need to create a unique token for email confirmation. Or generate a password for a new user. Or just make a readable ID for a link. The first thing that comes to mind is to take UUID.randomUUID(), remove the hyphens, and be happy.
Stop. Did you know that a seemingly simple action can turn into a bottleneck for performance? The Stack Overflow question "How to generate a random alpha-numeric string" gathered thousands of views for a reason. The devil, as always, is in the details: the choice of random number generator, the algorithm, memory management. In this article, we won't just write code — we'll optimize it to the maximum.
\n\nGet your IntelliJ IDEA ready. Let's go!
\n\n1. The simplest (but slowest) way: UUID
\n\nLet's start with the classic. UUID generates a 128-bit value. If you remove the hyphens, you get 32 characters in hex format (0-9, a-f). This is already an alphanumeric string, but with a limited alphabet.
public static String generateWithUUID() {\n return UUID.randomUUID().toString().replace("-", "");\n}\n\n\nPros: One line of code. No thinking required.
\nCons: Cannot control the length. Only hex characters (16 alphabet characters). For passwords — too weak. For tokens — it'll do, but there's a catch.
\n\nBy the way, UUID.randomUUID() uses SecureRandom under the hood. It's cryptographically secure, but slow. If you need 10,000 strings per second — this method will disappoint you.
2. RandomStringUtils from Apache Commons Lang
\n\nA classic that moves from project to project. The commons-lang3 library offers a ready-made method:
import org.apache.commons.lang3.RandomStringUtils;\n\npublic static String generateWithCommons(int length) {\n return RandomStringUtils.randomAlphanumeric(length);\n}\n\n\nElegant? Yes. Performant? Not really.
\nUnder the hood, RandomStringUtils uses java.util.Random (not cryptographically secure) and creates many temporary objects. It's sufficient for most tasks, but if you're generating millions of strings — get ready for GC pauses.
3. Custom method with Random.nextInt()
\n\nLet's write our own wheel. The most obvious way:
\n\nimport java.security.SecureRandom;\nimport java.util.Random;\n\npublic class RandomStringGenerator {\n private static final String ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";\n private static final int BASE = ALPHANUMERIC.length();\n private final Random random;\n\n public RandomStringGenerator() {\n this.random = new SecureRandom(); // for cryptographic security\n }\n\n public String generate(int length) {\n StringBuilder sb = new StringBuilder(length);\n for (int i = 0; i < length; i++) {\n sb.append(ALPHANUMERIC.charAt(random.nextInt(BASE)));\n }\n return sb.toString();\n }\n}\n\n\nWhat's important here?
\n- \n
- We use
StringBuilderwith a known capacity — no unnecessary expansions. \n SecureRandomguarantees that the output cannot be predicted. For tokens — a must-have. \n - The alphabet is defined as a string — 62 characters (26+26+10). You can add special characters. \n
But there's a problem: SecureRandom can be slow on Linux (waiting for entropy). If speed is more important than security — use ThreadLocalRandom.current().
4. Optimization with char[] and ThreadLocalRandom
\n\nWant to squeeze out maximum performance? Let's ditch StringBuilder and work directly with a character array:
import java.util.concurrent.ThreadLocalR