15

Is there a difference in using these two? When would you use one over the other?

System.out.println(result);

versus

PrintWriter out = new PrintWriter(System.out);
out.println(result);
out.flush();
MultiplyByZer0
  • 6,302
  • 3
  • 32
  • 48
Nikhil
  • 797
  • 6
  • 12
  • 30
  • 1
    One's a PringStream and the other's a PrintWriter. PrintStreams can allow more flexibility with encoding. I'm guessing that some system encodings are used, but I'm not sure. – Hovercraft Full Of Eels Dec 21 '13 at 18:23
  • 2
    `System.out` is a [PrintStream](http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html) and `PrintWriter` is ... a [PrintWriter](http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html) – Brian Roach Dec 21 '13 at 18:30
  • 1
    `PrintWriter` is also about twice as fast for printing text. – Luigi Plinge Dec 06 '18 at 22:28

4 Answers4

12

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

For most use cases, there is no difference.

MultiplyByZer0
  • 6,302
  • 3
  • 32
  • 48
5

System.out is instance of PrintStream

So your question narrows down to PrintStream vs PrintWriter

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

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

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180
Mitesh Pathak
  • 1,306
  • 10
  • 14
4

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

I got this by running these snippets 3 times each for n=10^1 to 10^7 and then taking 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();
    }
}
Abhinav Mani
  • 300
  • 1
  • 2
  • 11
0

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

MultiplyByZer0
  • 6,302
  • 3
  • 32
  • 48
Muhammad
  • 6,725
  • 5
  • 47
  • 54