What's the fastest way to output a string to system out?

Viewed 23325

I'm doing something like this:

for (int i = 0; i < 100000; i++) {
   System.out.println( i );
}

Basically, I compute an integer and output a string about 10K-100K times and then need to write the result to system.out, each result separated by a newline.

What's the fastest way to achieve this?

5 Answers

This includes fast input and output method as well

import java.io.*;
public class templa{
    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) throws Exception {
        OutputStream outputStream =System.out;
        PrintWriter out =new PrintWriter(outputStream);
        FastReader in =new FastReader();
        int testcase = in.nextInt();
        while(testcase-- >0){
            //in object works same as Scanner Object but much faster
            //out.println() works faster than System.out.println()
            //Write your code here
        }
        out.close();
      }
}
Related