[ACCEPTED]-System.out.println vs PrintWriter-printstream

Accepted answer
Score: 12

The main difference is that System.out is a PrintStream and the 5 other one is a PrintWriter. Essentially, PrintStream should be 4 used to write a stream of bytes, while PrintWriter should 3 be used to write a stream of characters (and thus 2 it deals with character encodings and such).

For 1 most use cases, there is no difference.

Score: 5

System.out is instance of PrintStream

So your question narrows 6 down to PrintStream vs PrintWriter

  • All characters printed by a 5 PrintStream are converted into bytes using the platform's 4 default character encoding. (Syso writes 3 out directly to system output/console)

  • The 2 PrintWriter class should be used in situations that 1 require writing characters rather than bytes.

Score: 3

I recommend using PrintWriter if you have 4 to print more than 10^3 lines in one go. Performace comparison up to 10^5 Performace comparison up to 10^7

I 3 got this by running these snippets 3 times 2 each for n=10^1 to 10^7 and then taking 1 mean of there execution time.

class Sprint{
    public static void main(String[] args) {
        int n=10000000;
        for(int i=0;i<n;i++){
            System.out.println(i);
        }
    }
}

import java.io.*;
class Pprint{
    public static void main(String[] args) {
        PrintWriter out = new PrintWriter(System.out);
        int n=10000000;
        for(int i=0;i<n;i++){
            out.println(i);
        }
        out.flush();
    }
}
Score: 0

Yes, there is a slight difference. out.println() is short 2 and is used in JSP while PrintWriter is used in servlets. out.println() is 1 also derived from PrintWriter.

More Related questions