EN
Java - generate random string of size n characters
0
points
In this article, we would like to show you how to generate random string of size n characters in Java.
The following example presents how to generate random string of size n=10
using characters taken from ALPHABET
constant.
Practical example:
package tmpOperations3;
import java.security.SecureRandom;
public class Example {
static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789";
static SecureRandom random = new SecureRandom();
static String randomString(int len) {
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(ALPHABET.charAt(random.nextInt(ALPHABET.length())));
return sb.toString();
}
public static void main(String[] args) {
int n = 10;
System.out.println(randomString(n));
}
}
Example output:
nmAlwCyp75