templates · Java for online assessments

Fast input & output for online assessments

  • An online assessment where you read stdin yourself (HackerRank, HackerEarth, Codeforces style)
  • Input of 10⁵ – 10⁶ numbers, where Scanner alone can take seconds
  • Many output lines: calling System.out.println for each one is slow

the one rule

The invariant

Read through one big buffer, write through one big buffer, and flush exactly once at the end.

write it from memory

The template

the Main class you submit

javajava.io.* · java.nio.charset.StandardCharsets · java.util.*
public class Main {    public static void main(String[] args) throws IOException {        FastReader in = new FastReader(System.in);        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));        solve(in, out);        out.flush();                                  // forget this and the judge sees nothing    }     /** Example OA: n numbers, then q queries "l r" → the sum of a[l..r], one per line. */    static void solve(FastReader in, PrintWriter out) throws IOException {        int n = in.nextInt();                         // read exactly what the input format says        long[] prefix = new long[n + 1];              // long: n * 10^9 does not fit in an int        for (int i = 0; i < n; i++) prefix[i + 1] = prefix[i] + in.nextInt();        int q = in.nextInt();        while (q-- > 0) {            int l = in.nextInt(), r = in.nextInt();            out.println(prefix[r + 1] - prefix[l]);   // buffered: no flush per line        }    }}

Keep main tiny: set up the reader and writer, call solve, flush. All the problem's logic goes in solve. Name the class exactly what the judge asks for: often Main, sometimes Solution.

fill in the blanks — only these lines change per problem

  1. line 11The input format: how many numbers, in which order. Read exactly that.
  2. line 17What you print per test case or per query.
  3. line 6Never remove this. Without it the output stays in the buffer and the judge sees nothing.

FastReader

javajava.io.* · java.nio.charset.StandardCharsets · java.util.*
/** Reads numbers straight from bytes: no Scanner, no regex, no String per number. */class FastReader {    private final InputStream in;    private final byte[] buf = new byte[1 << 16];     // 64 KB chunks    private int len = 0, ptr = 0;     FastReader(InputStream in) {        this.in = in;    }     private int read() throws IOException {        if (ptr == len) {                             // buffer used up: fetch the next chunk            len = in.read(buf, 0, buf.length);            ptr = 0;            if (len <= 0) {                len = 0;                return -1;                            // end of input            }        }        return buf[ptr++];    }     private int skipSpaces() throws IOException {        int c = read();        while (c != -1 && c <= ' ') c = read();       // spaces, tabs, \n and \r        if (c == -1) throw new EOFException("no more input");        return c;    }     long nextLong() throws IOException {        int c = skipSpaces();        boolean negative = c == '-';        if (negative) c = read();        long value = 0;        while (c >= '0' && c <= '9') {            value = value * 10 + (c - '0');            c = read();        }        return negative ? -value : value;    }     int nextInt() throws IOException {        return (int) nextLong();    }     /** One word (any run of non-space characters). */    String next() throws IOException {        StringBuilder sb = new StringBuilder();        int c = skipSpaces();        while (c > ' ') {            sb.append((char) c);            c = read();        }        return sb.toString();    }}

Paste it under Main in the same file. It skips any whitespace, so the numbers may be spread over lines in any way.

complexity

What it costs

time O(input size + output size)
Each byte is read once from a 64 KB buffer. No regex, no String per number, and output goes out in large blocks.
space O(1) extra
A fixed 64 KB input buffer and the writer's buffer, apart from what your solution stores.

watch out

Common bugs

  • Forgetting out.flush(): the program runs fine and prints nothing.
  • Storing a sum of 10⁵ numbers up to 10⁹ in an int. It overflows; use long.
  • Mixing Scanner and this reader on the same System.in. The first one buffers input the second never sees.

use it

Practise it on

learn it properly