Java: Generating a random char (a-z)

A random character between 'a' and 'z':

Random rnd = new Random();
char c = (char) ('a' + rnd.nextInt(26));

A random character from a string of characters:

String chars = "abcxyz";
Random rnd = new Random();
char c = chars.charAt(rnd.nextInt(chars.length()));


Every character corresponds to a number (a code point).

97 for example corresponds to a, and we can convert between the two easily:

char c = (char) 97;  // c == 'a'
int i = 'a';         // i == 97

So all we have to do is to come up with a random number between 97 (‘a’) and 122 (‘z’) and convert that number to a character.

This is done like so:

int randomNumber = 97 + rnd.nextInt(26);

We can replace 97 with ‘a’…

int randomNumber = 'a' + rnd.nextInt(26);

…and convert to char on the same line

char randomChar = (char) ('a' + rnd.nextInt(26));

See also


Be the first to comment!