Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On system.out, clarification needed

I was looking at someone's code and saw that he repeatedly declared

PrintStream out = System.out;

and later called

out.println("blah");

I actually thought this was kind of neat. Is this a common practice? Was he just being fancy?

like image 385
James Raitsev Avatar asked Jun 14 '10 22:06

James Raitsev


2 Answers

This is a reasonable approach. He is basically creating an alias for System.out. There are a number of advantages:

  • Less typing.
  • Easier to later change the code to output to a different PrintStream.
  • Possibly a performance improvement, although it will be negligible.
like image 141
Mark Byers Avatar answered Oct 12 '22 00:10

Mark Byers


To avoid typing System.out.println specially when performing small test ( without an IDE ) I use import static java.lang.System.out instead

But that may make sense if you want to substitute the value of System.out later, perhaps to a wrapper to redirect to a file

 PrintStream out = new FilePrintStream("MyLogs.log"); // // System.out

And silence the standard output at once. I repeat it may make sense on some scenarios, because for this I would use a Logging framework.

BTW, it would be better to declare it as final and static also:

class YourClass  {
    private final static PrintStream out = System.out;
}
like image 26
OscarRyz Avatar answered Oct 11 '22 23:10

OscarRyz