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:
xxxxxxxxxx
1
package tmpOperations3;
2
3
import java.security.SecureRandom;
4
5
public class Example {
6
7
static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
8
"abcdefghijklmnopqrstuvwxyz" +
9
"0123456789";
10
static SecureRandom random = new SecureRandom();
11
12
static String randomString(int len) {
13
StringBuilder sb = new StringBuilder(len);
14
for (int i = 0; i < len; i++)
15
sb.append(ALPHABET.charAt(random.nextInt(ALPHABET.length())));
16
return sb.toString();
17
}
18
19
public static void main(String[] args) {
20
int n = 10;
21
System.out.println(randomString(n));
22
}
23
}
Example output:
xxxxxxxxxx
1
nmAlwCyp75