Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What input class does System.in belongs to and why?

The code

import java.io.*;

class ioTest1{
   public static void main(String args[]){
      System.out.println(System.in.getClass());
   }
}

returns that System.in belongs to the BufferedInputStream class. Why is that?

Since class System defines System.in to be InputStream, I can see how the result isn't impossible. But why can't the previous code return another class inherited from InputStream,like for example DataInputStream?

like image 451
Themistoklis Haris Avatar asked Aug 17 '15 13:08

Themistoklis Haris


2 Answers

As explained in the comments, there's nothing that would have prevented System.in from being DataInputStream, but given that BufferedInputStream is a no-frills InputStream that includes buffering of data (always a good idea), it makes more sense to give the most generic type possible.

Developers can then wrap the buffered stream with for example a DataInputStream if the program is fed piped binary data, or an InputStreamReader if the program is receiving text data from the user.

System.in is a BufferedInputStream because it doesn't need to be anything else.

like image 116
Kayaman Avatar answered Sep 24 '22 18:09

Kayaman


The simple answer is that it is just how it's implemented.

If you look at the source code of java.lang.System class, you will see that System.in is set natively (See Java_java_lang_System_setIn0).

Different JVM implementers may use any InputStream implementation they prefer. In your case BufferedInputStream is used, presumably, for its efficiency.

like image 27
Amila Avatar answered Sep 26 '22 18:09

Amila