Java: Generating a random char (a-z)
A random character between
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()));
- Converting a char to an int
- Random with a random seed
- Generating a random String (password, booking reference, etc)
Hello thanks for the quick tutorial. Please could you explain how
char c = (char) (rnd.nextInt(26) + 'a'); works?
by Michael Olafisoye |
This relies on two facts:
a char value can be used both as a number and as a character, and
chars 'a' through 'z' have consecutive numeric values (c.f. the ASCII table). If you print for instance
(char) 98you'll get a 'b'.