1

In JAVA when you import the Scanner class and create a Scanner object, how does the underlying logic work to capture the input and write it onto memory? I understand that the following statement

Scanner sc = new Scanner (System.in) 

means you are creating a new Scanner class object called sc which will inherit the attributes and methods of the Scanner class to be used in a certain way. But I would like to know what does the System.in argument do?

When the compiler goes through the class instantiation step, it would first create a class constructor which takes in System.in as an argument which is an object of the InputStream class. Which means that when you call a nextInt() or nextln() method of the Scanner class, what you are essentially doing is sending that input into that method which would perform some syntactic check on it and then pass it onto the InputStream class which would turn it into bytes which can then be written onto the memory.

Is that how it works? or am I totally off the rails with this?

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
mrarvind901
  • 11
  • 1
  • 2
  • I assume it wraps the `InputStream` (e.g. System.in) you provide in an `InputStreamReader`, then parses it using some sort of `BufferedReader` or something. I haven't look at it before, I just know that it's slow. – byxor Dec 17 '16 at 12:32
  • `System.in` is an input stream that assigned by the runtime to the standard input (i.e. the stuff you type on the console) of the process. This question is a little too broad for here, though, you probably want to ask shorter, more specific things. – pvg Dec 17 '16 at 12:34
  • 4
    You can also read the source and see for yourself: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/Scanner.java/. – Tom Dec 17 '16 at 12:39

1 Answers1

2

Scanner class can be used for reading input from different sources. Scanner object holds the address of InputStream object present in the System class. Input Stream object of system class reads data from keyboard which is byte stream/byte form. The Scanner class converts this read byte into specific data type. Scanner class was introduced in Java5.0, until then BufferedReader was preferred mode of reading data which read data as string. For ex:

Scanner scan=new Scanner(System.in);

In this line, scan is an object of Scanner class, this object holds the address of Input Stream object. When a byte of data is read from the keyboard, the Input Stream object, which holds the address of keyboard(every device is established as either a byte/block special or character special file in the OS, hence address of a device is essentially the starting address of the block/character special file in memory) transfers that data to Scanner class object, which could be manipulated to read data as a specific data type.

KumarAnkit
  • 713
  • 1
  • 9
  • 26