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?
This is a reasonable approach. He is basically creating an alias for System.out
. There are a number of advantages:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With