简体   繁体   中英

Is there any difference between printing statements using PrintStream object and System.out.println() in Java?

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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM