Java char variable

The following code within a program allows 90 to be assigned to the variable ‘ch’. ‘Z’ is then printed to the console.

char ch;
ch = 90;
System.out.println(ch);

However, the following code, that lies within a program, does not compile. If the following code requires the input to the ch variable to be a character type, i.e. (char) System.in.read();, then why does the same not apply when 90 is assigned to ch above? Why doesn’t it have to be ch = (char) 90?

char ch;
ch = System.in.read();

Answer

The compiler knows that 90 is a valid value for char. However, System.in.read() can return any int, which may be out of the valid range for chars.

If you change 90 to 90000, the code won’t compile:

 char ch;
 ch = 90000;

Leave a Reply

Your email address will not be published. Required fields are marked *