The easiest way:
// constant declared in the class static final int LETTERS_COUNT = 'z'-'a'+1; char[] randomChars = new char[500]; Random r = new Random(); for(int i=0; i<randomChars.length; i++) { randomChars[i] = (char)(r.nextInt(LETTERS_COUNT) + (r.nextBoolean() ? 'a' : 'A')); }
If you don't like accessing the random number generator twice, you can generate numbers from 0 to 51:
for(int i=0; i<randomChars.length; i++) { int num = r.nextInt(LETTERS_COUNT*2); randomChars[i] = (char)(num >= LETTERS_COUNT ? 'a'+(num-LETTERS_COUNT) : 'A'+num); }
However, I do not see any advantages of this approach. Internally, r.nextInt can also change its internal state several times. The distribution should be the same in both cases.
source share