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()));
- Java: Converting a char to an int
- Java: 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?
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'.