0

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();
1

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.