39

While reading about Java I/O, i realized that there are two ways through which i can write to the standard output.

Following is the snippet that uses both the techniques

import java.io.*;
public class ConsoleIO {

    public static void main(String[] args) {
        System.out.println("Method 1");

        PrintWriter writer = new PrintWriter(System.out);
        writer.println("Method 2");
        writer.flush();
        writer.close();
    }
}

Are there any performance benefits of using one over the other?

2
  • 3
    fact remains that no matter what technique you use, writing to the console is always expensive.
    – frewper
    Commented Feb 29, 2012 at 6:26
  • I was curious about frewper's assertion that writing to the console is expensive. I've noticed it myself, but wondered why. The short of it is I/O buffering. For a longer (Python-centric) discussion check out Piët Delport's answer on this thread: stackoverflow.com/questions/3857052/… Commented Apr 28, 2016 at 14:37

6 Answers 6

21

A quick Google revealed a thread on Coderanch which was useful.

There are several other ways of doing console writing but there seems to be no real benefit of using one or the other apart from less code to write and that the creation of a new PrintWriter object will take up more memory (eventually).

PrintWriter can write to other sources than just the console, it can write to an HttpResponse for example whilst System.out.println only writes to console.

19

different of two approach is:

  • When you use System.out.print("") you actually used a PrintStream instance.
  • Actually the difference is in two classes PrintStream and PrintWriter which are:

    1. PrintStream is a stream of bytes while PrintWrite is a stream of characters.
    2. PrintStream uses platform's default encoding while with the PrintWriter you can however pass an OutputStreamWriter with a specific encoding. for sample: PrintStream stream = new PrintStream(output); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"));

You can select a approach with your requirements.

5

Depending on how much I/O you will be performing, there can be a lot of benefits to using a buffer. Ideally, you should limit the number of calls to your input source, and read the bytes in as chunks.

Imagine a bucket with 10 pebbles, and you want to move them to another bucket. You could grab a handful of pebbles and just move them over. You don't need to go grab a shovel, that's to much overhead. But if the bucket has thousands of pebbles, you are going to want a shovel, and it is worth the effort to get get the shovel (in this analogy, the buffer is the shovel)... The moral of the story is that you should use a buffer when you are going to be making lots of calls to the data source.

This article may explain it better, and in more detail... http://pzemtsov.github.io/2015/01/19/on-the-benefits-of-stream-buffering-in-Java.html

Here is a link to the Oracle's website explaining how the PrintWriter class works. https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html

Here is a working example... You can use the PrintWriter class to write to the console if you instantiate the object with System.in. Be sure to also pass in "true" so that it will auto-flush.

import java.io.*;

public class PrintWriterExample
{
    public static void main(String args[]) throws IOException
    {
        int [] id = {12456, 323, 345, 3423};
        String [] firstName = {"John", "Paul", "George", "Ringo"};
        String [] lastName = {"Lennon", "McCartney", "Harrison", "Star"};

        PrintWriter outFile = new PrintWriter(System.out, true);
        String format = "ID: %5d (%s, %s)\n";

            for (int i=0; i<id.length; i++)
            {
                outFile.printf(format, id[i], firstName[i], lastName[i]);
            }
    }
}

Here is the output:

ID: 12456 (John, Lennon)
ID:   323 (Paul, McCartney)
ID:   345 (George, Harrison)
ID:  3423 (Ringo, Star)
0
2

There are not only two ways, you can also find some other ways to do this. For example using Consol class of io package, and may some more classes present for this.

But if you just want to print something in the consol, then I think first method is the best. Why should you go for 4 to 5 lines of code if it can be done in just 1 line.

2

Using PrintWriter makes the output internationalizable - because encodings like UTF-8 can be specified. Both PrintWriter and PrintStream classes should only be used for activities like console output - not for network programming - because of their platform-dependent treatment of line-breaks and swallowing of exception conditions. The second chapter of "Java Network Programming" has a good discussion on this.

1

Use:

System.out.println("Method 1");

It is a static call which is faster than the other option. Plus, you don't create any additional object such as PrinterWriter object in the second option.

Not the answer you're looking for? Browse other questions tagged or ask your own question.