Reputation: 1497
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();
Upvotes: 0
Views: 829
Reputation: 201439
Whenever you are dealing with system io you need to ensure that you can handle all valid byte input values. However, you then need a mechanism to indicate that the stream has been exhausted. The javadoc for InputStream.read()
(System.in
is a global InputStream
) says (emphasis added),
Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.
If you were to cast -1
to char
you would get 65535 because char
is unsigned. With byte
, it's even worse in that -1
is a valid value. Regardless, you aren't reading char
values; you are reading byte
(s) encoded as int
in the range 0-255 plus -1 to indicate end of stream. If you want char
(s) I suggest you look at an InputStreamReader
which is described in the javadoc as
An
InputStreamReader
is a bridge from byte streams to character streams
Upvotes: 0
Reputation: 393811
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 char
s.
If you change 90 to 90000, the code won't compile:
char ch;
ch = 90000;
Upvotes: 2