How to generate a random alphanumeric string in Java?
Hello everyone! I'm writing a small application for generating passwords and temporary identifiers. I need to create random strings containing only Latin letters (a-z, A-Z) and digits (0-9). For example, something like "k3R9tB2x" or "A7fD1qP8".
I tried using UUID, but it produces strings with hyphens, which I don't need. I attempted to write my own logic based on Math.random(), but the code turns out cumbersome and unreliable — sometimes it generates only letters or only digits. Here's what I came up with:
```java
String generateRandomString(int length) {
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
int index = (int)(Math.random() * chars.length());
sb.append(chars.charAt(i
No answers yet.
Log in to leave an answer
Blogs
CI/CD for Kotlin Projects with GitHub Actions: A Step-by-Step Guide