Themistoklis Haris
Themistoklis Haris

Reputation: 365

How does java.io.InputStream.read() work?

Why does this :

import java.io.*;

class ioTest2 {
  public static void main(String args[])throws IOException{
      int b;
      while( (b = System.in.read() ) != -1)
          System.out.print((char)b);
  }
}

work as expected,i.e print exactly what you type, and this:

import java.io.*;

class ioTest2 {
  public static void main(String args[])throws IOException{
    int b;
    while( (b = System.in.read() ) != -1)
        System.out.print(b);
  }
}  

does not? Why do I have cast b to a character to make the code correct?

Upvotes: 0

Views: 1075

Answers (3)

Solomon Slow
Solomon Slow

Reputation: 27115

System.out.print((char)b) calls a different method from System.out.print(b). They do different things.

Which method to call is not just determined by the name, but by the name and the type signature (i.e., by the types of the arguments). Different methods can have the same name, so long as they have different argument lists.

Read the JavaDoc:

http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#print%28int%29

Versus

http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#print%28char%29

Upvotes: 0

user4979686
user4979686

Reputation:

The read() method returns an integer, or -1 if the end of stream has been reached.

A char, or character, is a primitive type, and can be represented as a number. Since you cast the integer to a character, it's represented on screen.

Upvotes: 0

rgettman
rgettman

Reputation: 178253

The read() method returns an int that stores the next byte that is read from the stream. You need to cast it to a char, or otherwise the int value will be printed.

If you type "ABCD", then without casting, then the println(int) method is called (System.out is a PrintStream), and the values of the bytes are printed.

  B   D
  vv  vv
65666768
^^  ^^
A   C

If you cast it to a char, then a different overloaded method, println(char) is called, which knows to print the character specified, so it "works" (echoes to you the characters you typed).

Upvotes: 1

Related Questions