G
G
Gach1much11sMyFuture2017-09-03 18:40:30
Java
Gach1much11sMyFuture, 2017-09-03 18:40:30

How to understand how a piece of code works?

I do not really understand what is happening in the first 3 lines, please explain.

InputStream inputStream = System.in;
        Reader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String name = bufferedReader.readLine();
        String sAge = bufferedReader.readLine();

And here too.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

It is also interesting how BufferedReader differs from Scanner and why it is recommended to use the first one.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor, 2017-09-04
@EgorNS

InputStream inputStream = System.in;
Reader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

In the first line, we assign to the inputStream variable an object of the InputStream class, a reference to which is contained in System.in. The InputStream class is used in Java as a byte stream for inputting data into your program. Since we are working with an object referred to by System.in, this means that we will be dealing with a standard stream that will read the input data that is entered into the console from the keyboard.
Further, in the second line, an object of type InputStreamReader is created and assigned to a variable.
InputStreamReader is a converter between byte and character streams , which takes as an argument a byte stream (in our case inputStream) and converts its bytes into characters, which will then be transferred to a character stream.
The third line creates an object of the BufferedReader class. BufferedReader is a subclass of the Reader class, which is used in Java as a character stream.for data entry. BufferedReader differs from other subclasses of Reader in that it can read not only single characters, but lines of characters at once. BufferedReader, when created, requires an object of any character stream as an argument from which it will then read data. Since our inputStream is a byte stream, it cannot be passed to the BufferedReader as an argument. For this, there are stub objects of type InputStreamReader. Such an object is passed to the BufferedReader as an argument. At the same time, the InputStreamReader encapsulates the object of our inputStream byte stream that we passed to it when it was created on the second line.
In this line, everything is the same, only in an abbreviated form. This style is most applicable when writing code, as it is more readable and compact than the example above.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question