0

I notice that the following line of code exists a lot. (For example on this website.)

char ch = (char) System.in.read();  // uses a char, and requires a cast.

Now to test for a particular character keystroke, or an ASCII value, or an escape sequence, etc..

if (ch == 'a' || ch == 65 || ch == '\n' || ch == 13) System.out.print("true");

Does using a char above provide any benefits over the following line of code below, which uses an int?

int i = System.in.read();  // uses an int, which requires no cast.

The int variable "i" can be used in the same if statement as previously shown, above.

user2911290
  • 1,396
  • 1
  • 16
  • 26
  • 1
    Honestly, the answer is probably as simple as readability. The intention is to use it as a char, so programmers cast it to a char. – riwalk Nov 27 '13 at 16:39

2 Answers2

2

There is no reason for the cast at all. This is fine

int i = System.in.read();
if(i == 'a'){
   // do something
}

You can do this, because 'a' is a value within the range of an int.

Also, be aware that doing the cast directly to a char may be problematic when reading files and such, because what InputStream.read() does is read a byte not a char. A char is two bytes wide.

MadConan
  • 3,749
  • 1
  • 16
  • 27
2

Neither approach is correct. The correct way to read characters from System.in is to use an InputStreamReader (or a Scanner if that provides the right functionality). The reason is that InputStream.read() reads a single byte, not characters, and some characters require reading more than one byte. You can also specify the character encoding to be used when converting bytes to characters.

Reader rdr = new InputStreamReader(System.in);
int i = rdr.next();
if (i == -1) {
    // end of input
} else {
    // normal processing; safe to cast i to char if convenient
}
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • Regarding the first line in your sample code: `Reader rdr = new InputStreamReader(System.in);` Please can you explain why the variable "rdr" is of type Reader, and not of type InputStreamReader? Specifically, please can you explain the benefit that this provides. Thanks a lot. Also, in your code sample, when you used the method next(), did you mean read()? – user2911290 Nov 27 '13 at 17:56
  • 1
    @user2911290 - No particular benefit in this case. It's just habit; I usually program to an interface unless I need the specific functionality of a more concrete type. It makes future evolution of the code easier. (For instance, I could switch to a `CharArrayReader` or a `PipedReader` without worrying about whether there were dependencies on methods or behavior specific `InputStreamReader`.) – Ted Hopp Nov 27 '13 at 18:13