Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to console with System.out and PrintWriter

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?

like image 292
Chander Shivdasani Avatar asked Feb 29 '12 06:02

Chander Shivdasani


1 Answers

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.

like image 194
Henrik Andersson Avatar answered Oct 14 '22 01:10

Henrik Andersson