EN
Java - generate random string from letters and digits of size 10
13
points
1. Generate random string with ThreadLocalRandom
public static String randomString(int len) {
String alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789";
StringBuilder b = new StringBuilder();
for (int i = 0; i < len; i++) {
int randIdx = ThreadLocalRandom.current().nextInt(alphabet.length());
char randChar = alphabet.charAt(randIdx);
b.append(randChar);
}
return b.toString();
}
Example:
System.out.println(randomString(10)); // oBmUYZ3MIg
System.out.println(randomString(10)); // 8gGOjO5Ga2
System.out.println(randomString(10)); // RVrvgA9Okd
Generated random text will contains:
- upper letters: A-Z
- lower case letters: a-z
- digits: 0-9