Good Practice Methods For Fast Input And Output in Java
Posted By : Navin Purohit | 26-May-2018
Fast Input/Output in Java
In a programming language, input/output plays a very important role. Depend on what kind of input/output your programming followed, it will slow down your processing time.
In this blog, we discussed various ways to get around the difficulty and change TLE (time limit Exceed) to AC (Accepted solution).
1. Scanner
Scanner class is used to read the desired object after initiating the scanner class with the input stream. Its very easy and we have to write very less coding in it. But its never recommended because it's very slow and in most of the cases we get TLE. It has in-built methods to read for ex. NextLine(), nextInt(), nextDouble(), next() etc.
Example :
// Using Scanner import java.util.*; public class ScannerDemo { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int k = s.nextInt(); System.out.println(“n =”+n+” and k =”+k); } }
2. BufferedReader
BufferedReader is faster than scanner but it requires a lot of typing. BufferedReader class reads input from the character-input stream, buffering characters to provide an efficient reading of char, arrays, and lines. We need to parse value everytime to get the desired type. This method not recommended as it has high complexity because of Stringtokenizer which reads multiple words form a single line.
Example:
// Using BufferedReader import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class BufferedReaderDemo { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); System.out.println(“n =”+n+” and k =”+k); } }
3. User-defined FastReader Class
It uses the bufferedReader and StringTokenizer to get time advantage and to reduce more coding by user-defined methods. This method is widely used to solve the competitive coding question as its easy to remember and fast enough.
Example:
// Using userdefined FastReader class import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class UDFastReaderDemo { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader s=new FastReader(); int n = s.nextInt(); int k = s.nextInt(); int count = 0; while (n-- > 0) { int x = s.nextInt(); if (x%k == 0) count++; } System.out.println(count); } }
4. Using Reader Class
This is the fastest method out of 3 methods which I discussed till now. But the interesting part is that it not recommended over method 3 as it requires very complicated methods in its implementation. For reading it uses input stream data through the stream of data and uses read() and nextInt() methods to read data. Although its the fastest method but it is not easy to remember its methods.
Example:
// Using Reader Class import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class readerDemo { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException { Reader s=new Reader(); int n = s.nextInt(); int k = s.nextInt(); int count=0; while (n-- > 0) { int x = s.nextInt(); if (x%k == 0) count++; } System.out.println(count); } }
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Navin Purohit
Navin has an experience of 4 years in Java and NodeJS. He is eager to learn new technologies and want to explore his inner strengths.