Search code examples
javaoopstream

Why do we need a Scanner Object for taking input in java


To print output we simply use System.out stream while to take input, we have to pass System.in in Constructor of a Scanner object and then use that object only.

Why is it so ? Why is there no direct method like System.in.nextInt() or something alike?


Solution

  • System.in is simply an InputStream. A pretty generic interface designed many years ago. Changing this aspect would break a lot of existing code. So changing the type of System.in is a no go.

    Adding the scanner methods to the stream would bloat the existing class on the other hand. Think of concepts such as single responsibility principle or segregation of concerns.

    You see - good object oriented design is about having small classes that have one responsibility. Not two, not 5 or 10.

    But I think you have a certain point - and if Java would be rewritten today, that input stream might end up being more convenient.