Saturday, July 16, 2016

Java - Standard input and output in competitive programming

Java provides several classes for taking standard input and printing to standard output.

For input
  • Scanner class
  • BufferedReader and InputStreamReader classes
  • DataInputStream class
  • Console class
For output
  • PrintStream class (System.out.print)
  • BufferedWriter and OutputStreamWriter classes
  • PrintWriter class
We can use any of the above classes to interact with std in/out. But the performance of the above classes differ with the way they are implemented.

Sometimes the time taken to get user input or the time taken to print back to the user becomes important. One such occasion is competitive programming.

Competitive programming websites like or sets timouts to run the solutions. These timeouts are generally set to check whether the competitor has solved the problem using an efficient algorithm.

But sometimes although the competitor has used an efficient algorithm, timeouts may occur. This is due to inefficiency in taking input or printing the output. Below is an implementation of a java class which can be easily used take input and print output efficiently.