faster input in java

How to read a whole line in java through faster input method which most programmers use on codechef??

import java.util.Scanner;
public class abc
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int a= scan.nextInt();
String b= scan.nextLine();
}
}

Scanner class is slow. Read about BufferedReader class. CodeChef_Java.
How fast is BufferedReader?

1 Like

As per codechef wiki BufferedInputStream is the fastest

import java.io.*;
class FastIO
{
    static BufferedInputStream in = new BufferedInputStream(System.in);
    static int readInt() {
        int no = 0;
        boolean minus = false;
        try {
            int a = in.read();
            while (a == 32 || a == 10) //10 is newline & 32 is ASCII for space
                a = in.read();
            if (a == '-') {
                minus = true;
                a = in.read();
            }
            while (a != 10 && a != 32 && a != -1) {
                no = no * 10 + (a - '0');
                a = in.read();
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
        return minus ? -no: no;
    }
    static String read() {
        StringBuilder str = new StringBuilder();
        try {
            int a = in.read();
            while (a == 32)
                a = in.read();
            while (a != 10 && a != 32 && a != -1) {
                str.append((char)a);
                a = in.read();
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
        return str.toString();
    }
	public static void main (String[] args)	{
	    /*Accepting input in the format
         *<integer> <word>
         */
        int no = readInt();
        String str = read();
	}
}

Apart from Buffered Reader, you might want to take a look at Print Writer also, it’s considerably faster than System.out.println (I’ve tested it in a Codechef problem and it reduced the time by 0.08 ~ 0.1 seconds ).
After all output speed is as important as the input speed, isn’t it?

1 Like

Use BufferedReader it is very very fast than System.out.println()!!

I use the fast IO method which I found on quora and is currently used by many programmers

question on quora: link

Many of the top programmers use a plugin known as CHelper.I havent used it yet but It is made by the great programmer Egor(red on topcoder and codeforces) so it must be good.
codeforces manual : link

Use below tutorials …