Developers · 5 min read

How to generate a random letter in Java

The core trick in Java is picking a random offset from 'A' and casting it to a char. Here's the standard approach, a thread-safe version, and how to restrict the range.

1. Using java.util.Random

import java.util.Random; Random random = new Random(); char letter = (char) ('A' + random.nextInt(26)); System.out.println(letter);

nextInt(26) returns 0–25, and adding that offset to 'A' (65 in ASCII) lands anywhere from A to Z.

2. Using ThreadLocalRandom (better for concurrent code)

If you're generating letters from multiple threads, ThreadLocalRandom avoids contention that a shared Random instance can cause:

import java.util.concurrent.ThreadLocalRandom; char letter = (char) ('A' + ThreadLocalRandom.current().nextInt(26)); System.out.println(letter);

3. Lowercase or mixed case

char lower = (char) ('a' + random.nextInt(26)); // mixed case boolean upper = random.nextBoolean(); char mixed = upper ? (char) ('A' + random.nextInt(26)) : (char) ('a' + random.nextInt(26));

4. Restricting to vowels or a custom set

String vowels = "AEIOU"; char randomVowel = vowels.charAt(random.nextInt(vowels.length())); System.out.println(randomVowel);

5. Generating a random string of letters

StringBuilder sb = new StringBuilder(); for (int i = 0; i < 5; i++) {sb.append((char) ('A' + random.nextInt(26)));}System.out.println(sb.toString());

Prefer not to write the code?

The random letter generator on this site covers all of this through a UI without writing the loop yourself.