How to Generate Random Characters in Java
Random character generation in Java does not exist, but there are several ways to do this. It's generate a random number using java.util.Random.nextInt() and then convert the integer to a character according to its ASCII code.Generate a character between a-z
The ASCII code of the first lowercase alphabetic character is 65 ( a) and the last one is 97+26=122 (z). The number generated is in the range [97, 122] or in the range [0,26] + 97.Random rand = new Random();We can replace the ASCII code 97 with the 'a':
char c = (char)(rand.nextInt(26) + 97);
System.out.println(c);
(char)(rand.nextInt(26) + 'a');
Generate string
To get n characters, the preceding code must be surrounded by a for.
Random rand = new Random();
String str="";
for(int i = 0 ; i < 20 ; i++){
char c = (char)(rand.nextInt(26) + 97);
str += c;
System.out.print(c+" ");
}
f s e u k t m d a e b i m u y a y u s n
Generate alphanumeric from a set
In this example, We will generate alphanumeric characters from a set of defined characters. Let's do this:
- Create a String with the set you want
- Retrieve string length
- Call rand.nextInt which returns the position k between 0 and length-1
- alphabet.charAt(k) is the randomness of the alphabet
Random rand = new Random();
String alphabet="abcd1235";
int length = alphabet.lentgh();
for(int i = 0; i < 30; i++) {
int k = rand.nextInt(length);
System.out.print(alphabet.charAt(k)+" ");
}
b 1 3 1 d b b b 2 5 5 b a c 5 1 2 b 5 2 c b a 3 3 5 3 d b c 1