1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
import java.util.Random;
class Main {
public static void main(String[] args) {
// create a string of all characters
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// create random string builder
StringBuilder sb = new StringBuilder();
// create an object of Random class
Random random = new Random();
// specify length of random string
int length = 7;
for(int i = 0; i < length; i++) {
// generate random index number
int index = random.nextInt(alphabet.length());
// get character specified by index
// from the string
char randomChar = alphabet.charAt(index);
// append the character to string builder
sb.append(randomChar);
}
String randomString = sb.toString();
System.out.println("Random String is: " + randomString);
}
}
|