I was asked the following question during an interview:
Does
System.out.println()
have any other use than printing output to the console?
I was asked the following question during an interview:
Does
System.out.println()
have any other use than printing output to the console?
System.out
System.out
is a static
object of type PrintStream
. It holds a reference to the standard output stream which is usually the console. Usually, printing to the console is useful when you want to interact or display messages to the user in a console application, log status and error messages to the console. It is very useful for debugging to print out the values of variables, and to check if the program reaches a specific if-else
branch or loop.
System.err
There is also an object called System.err
which holds a reference to the standard error stream. It also usually is the console, the same console that System.out
holds a reference too. Therefore, you can write:
System.err.println("Message");
And you would get a message on the console just like you had used System.out
. But err
is usually recommended to print out error messages.
Although System.out
holds a reference to the console, the System
class provides you a method called setOut()
:
public void setOut(PrintStream out)
Similarly, there are methods setErr(PrintStream)
and even a setIn(InputStream)
which can be used to change out
, err
and in
to reference a different stream, like a file, so you can do something like:
PrintStream standardOut = System.out;
PrintStream fileOut = new PrintStream(new File("filename.txt");
System.setOut(fileOut);
System.out.println("Hello World!") // This will output to the file
System.setOut(standardOut); // Reset to the standard output stream
PrintStream
Other than println
, PrintStream
defines methods like printf
and format
which also allow you to format your input, like you would in a language like C. Both of these methods are identical:
int n1 = 10, n2 = 20;
int sum = n1 + n2;
System.out.printf("%d + %d = %d", n1, n2, sum);
System.out.format("%d + %d = %d", n1, n2, sum);
Strictly speaking, the statement System.out.println("xyz")
serves no other purpose than writing the passed string (xyz
) and a line separator (System.lineSeparator()
) to the PrintStream
assigned to System.out
.
Notice that the console was not mentioned in the above statement. Since it is possible to re-assign the "standard" output stream (System.out
), we can write to places other than the console by executing System.out.println("xyz")
.
Here is an example:
PrintStream fileOut = new PrintStream(new FileOutputStream("output.txt"), true);
PrintStream console = System.out; // store current System.out
System.setOut(fileOut);
System.out.println("This will be written to output.txt");