Search code examples
javabluej

Is there really a difference between referencing and creating new object from reference of PrintStream?


Below are the two ways of getting reference of the PrintStream object:

class Ex1 {
    public static void printEx() {
        //line 1: Direct Reference
        PrintStream ps1 = System.out;
        //line 2: Passing Reference as argument in constructor
        PrintStream ps2 = new PrintStream(System.out);
    }
}

Is there really a significant difference between those two lines in terms of usage or can (or should) it be used interchangeably?


Solution

  • Take as a reference this page;

    import java.io.*;
    public class SystemOutPrintlnDemo
    {
      public static void main(String[] args) 
      {
        //creating PrintStream object
        PrintStream ps = new PrintStream(System.out);
        ps.println("Hello World!");
        ps.print("Hello World Again!");
        //Flushes the stream
        ps.flush();
      }
    }