• + 1 comment

    tl;dr = I see how the overhead for Scanner is significanty more than the overhead for BufferedReader. However, the different techniques for reading the input - whole line vs. one value at a time - make almost no difference. The same work has to be done either way.

    Testing the runtimes is a great suggestion, but I think this is a more helpful comparison that would have better illustrated your point:

    Scanner (overhead only) - 28.667 milliseconds (average) on a simple test case

    Scanner in = new Scanner(System.in);
    int testCount = in.nextInt();
    int arraySize = in.nextInt();
    in.close();
    

    BufferedReader (overhead only) - 0.333 milliseconds (average) on a simple test case

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int testCount = Integer.parseInt(in.readLine());
    int arraySize = Integer.parseInt(in.readLine());
    in.close();
    

    BufferedReader obviously takes a lot less time to setup - 28.334 milliseconds less!

    However, we were mainly discussing the approach to reading the entire array as one line vs. one value at a time. Check out the change in runtimes when we read the first array:

    Scanner - 31.667 milliseconds (average) on a simple test case - increase of 3 milliseconds

    Scanner in = new Scanner(System.in);
    int testCount = in.nextInt();
    int arraySize = in.nextInt();
    for (int i = 1; i <= arraySize; i++) {
        System.out.println(in.nextInt());
        // Calculations would go here
    }
    in.close();
    

    BufferedReader - 3.333 milliseconds (average) on a simple test case - increase of 3 milliseconds

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int testCount = Integer.parseInt(in.readLine());
    int arraySize = Integer.parseInt(in.readLine());
    int[] array = new int[arraySize];
    int i = 0;
    for(String integer: in.readLine().split(" ")) {
        array[i++] = Integer.parseInt(integer);
    }
    for (int j = 0; j < arraySize; j++) {
        System.out.println(array[j]);
        // Calculations would go here
    }
    in.close();
    

    You can see that the different approaches to reading the actual values of the array don't make much difference at all. In fact, they're pretty much doing the same thing once you get down to it. It's really all about the overhead.

    Thanks tat_lim, for following through with your explanation. I definitely learned something interesting!

    (Note: BufferedReader also throws an IOException that has to be dealt with somehow. Not a big deal for our examples, but worth noting if you get an error trying to use it. This is probably why Scanner is the recommended class to start with for reading input - it's much easier to use.)