Take the 2-minute tour ×

I have this piece of code that generates a random characters (ASCII)

public char getRandChar(){ return (char)rand.nextInt(27); }

and then I'll print it out using this

System.out.println(new Character(getRandChar()));

How but apparently it is returning a blank value

share|improve this question
maybe you are getting a non-printing ASCII character –  gtgaxiola Sep 30 '12 at 3:05
You're generating a character whose ASCII value is between 0 and 26, and these are all non-printing characters. If your intention was to print a random letter of the alphabet, then you should probably add 'A' to your integer instead of directly casting it to (char). –  David Wallace Sep 30 '12 at 3:10
@DavidWallace you're right, it is returning a non-printing character, a little question, why should I add an 'A'? rather than just this? (char) rand.nextInt(25) + 65? –  KyelJmD Sep 30 '12 at 7:24
Adding 65 is equivalent to adding 'A'. But your program will be easier for future maintainers to understand if you have 'A' in there. –  David Wallace Sep 30 '12 at 7:34

1 Answer 1

up vote 3 down vote accepted

This is because rand.nextInt(27); is returning unprintable character codes. This will be evident if you change your code to return (char)65; for example.

share|improve this answer

Your Answer


