Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.out.println vs PrintWriter

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();
like image 618
Nikhil Avatar asked Dec 21 '13 18:12

Nikhil


People also ask

Is PrintWriter faster than system out Println?

By using PrintWriter than using System. out. println is preferred when we have to print a lot of items as PrintWriter is faster than the other to print data to the console.

What is the difference between system out Println and system out print?

The only difference between println and print method is that println throws the cursor to the next line after printing the desired result whereas print method keeps the cursor on the same line.

What is PrintWriter Println?

The println(String) method of PrintWriter Class in Java is used to print the specified String on the stream and then break the line. This String is taken as a parameter. Syntax: public void println(String string)

Why do we use PrintWriter in Java?

The main reason to use the PrintWriter is to get access to the printXXX methods (like println(int)). You can essentially use a PrintWriter to write to a file just like you would use System. out to write to the console.


3 Answers

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();
    }
}
like image 67
Abhinav Mani Avatar answered Oct 21 '22 18:10

Abhinav Mani


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.

like image 44
MultiplyByZer0 Avatar answered Oct 21 '22 20:10

MultiplyByZer0


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.

like image 21
Mitesh Pathak Avatar answered Oct 21 '22 19:10

Mitesh Pathak