To generate a random alphanumeric string in Java, you can use a combination of characters and a random number generator. Here are two common approaches:
1. Using Random
or SecureRandom
(Core Java)
This method uses a predefined set of alphanumeric characters and selects characters randomly using Random
or SecureRandom
:
import java.security.SecureRandom;
import java.util.Random;
public class RandomString {
// Define alphanumeric characters (62 total)
private static final String ALPHA_NUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// Generate a random string of length `length`
public static String generate(int length) {
if (length <= 0) throw new IllegalArgumentException("Length must be positive");
StringBuilder sb = new StringBuilder(length);
Random random = new SecureRandom(); // Use SecureRandom for security
for (int i = 0; i < length; i++) {
// Pick a random index from the ALPHA_NUMERIC string
int index = random.nextInt(ALPHA_NUMERIC.length());
sb.append(ALPHA_NUMERIC.charAt(index));
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(generate(10)); // Example: "X8sL3aQ9pZ"
}
}
2. Using Java 8+ Streams (Concise)
For a more concise approach, use Java 8’s IntStream
and Random
:
import java.security.SecureRandom;
import java.util.stream.IntStream;
public class RandomString {
private static final String ALPHA_NUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
public static String generate(int length) {
if (length <= 0) throw new IllegalArgumentException("Length must be positive");
SecureRandom random = new SecureRandom();
return IntStream.range(0, length)
.map(i -> random.nextInt(ALPHA_NUMERIC.length()))
.mapToObj(index -> String.valueOf(ALPHA_NUMERIC.charAt(index)))
.collect(Collectors.joining());
}
public static void main(String[] args) {
System.out.println(generate(10)); // Example: "7GgF2kL9qY"
}
}
Key Notes
- Security: Use
SecureRandom
instead ofRandom
for cryptographic safety (e.g., session IDs, tokens). - Character Set: The
ALPHA_NUMERIC
string contains 62 characters (uppercase, lowercase, digits). - Efficiency: Both methods use
StringBuilder
(or streams) for efficient string concatenation.
Alternative: Apache Commons Lang
If you’re using Apache Commons Lang, simplify with RandomStringUtils
:
import org.apache.commons.lang3.RandomStringUtils;
public class Example {
public static void main(String[] args) {
String randomString = RandomStringUtils.randomAlphanumeric(10); // Example: "x4Tp9sLm2A"
System.out.println(randomString);
}
}
Choose the method that best fits your use case!