Home > Software engineering >  Is there any difference between printing statements using PrintStream object and System.out.println(
Is there any difference between printing statements using PrintStream object and System.out.println(

Time:06-30

I have printed the data by using PrintStream object as below.

PrintStream ps = new PrintStream(System.out); ps.println("Printing");

And I have also printed the data using System.out.println(); System.out.println(("Printing"));

I see no difference between these two statements. Do anyone clarify about this?

CodePudding user response:

In your example it would work in a similar way, but System.out.println("") is generally used as an easy way to log to the console, while the new PrintStream() could also be used to redirect to a different stream, such as a remote endpoint. Generally the System.out.println is the more commonly used way to print things to the console.

Btw, you can actually redirect the System.out to something else by using the System.setOut(stream), so you wouldn't lose flexibility if you would System.out.println.

CodePudding user response:

I see no difference between these two statements.

I agree, functionally they're the same.

System.out returns a PrintStream, so this is fine:

PrintStream out = System.out;
out.println("Printing");

Creating a new PrintStream using the constructor where you pass in an OutputStream – as you did with this: new PrintStream(System.out) – will create a new PrintStream object wrapped around the constructor argument.

So when you did the code below, you're simply putting a wrapper around the same underlying output stream.

PrintStream ps = new PrintStream(System.out);
ps.println("Printing");

Either way, when you call println("Printing"), it's resolving to the same println() method.

  •  Tags:  
  • java
  • Related