Java: Generating a random char (a-z)

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

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

A random character from an arbitrary string of characters:

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

See also

Comments (2)

User avatar

Hello thanks for the quick tutorial. Please could you explain how char c = (char) (rnd.nextInt(26) + 'a'); works?

by Michael Olafisoye |  Reply
User avatar

This relies on two facts:

  1. a char value can be used both as a number and as a character, and

  2. chars 'a' through 'z' have consecutive numeric values (c.f. the ASCII table). If you print for instance (char) 98 you'll get a 'b'.

by Andreas Lundblad |  Reply

Add comment