How does the JAVA Scanner class work internally?

2.8k Views Asked by At

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?

1

There are 1 best solutions below

0
On

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.