As I know both out and err are of same class PrintStream
. Can anybody tell me how they differ...how they changed their behaviour?
System.in is the input stream connected to the console, much as System. out is the output stream connected to the console. In Unix or C terms, System.in is stdin and can be redirected from a shell in the same fashion. System.in is the static in field of the java.
System: It is a final class defined in the java. lang package. out: This is an instance of PrintStream type, which is a public and static member field of the System class.
The system is a class, out is the object of PrintStream class, println() is the method of PrintStream class which displays the result and then throws the cursor to the next line.
The main difference between the two is that print() retains the cursor in the same line after printing the argument, while println() moves the cursor to the next line.
The difference is not evident because by default in most of the Operating Systems they are written to the console (same file, console is also a file). However, you can have System.out
write to a file, and System.err
write to the console (monitor) - this is just one scenario.
Write a program that emits both System.out and System.err messages, and try this:
java MyProgram > out.txt 2> err.txt # On a *NIX.
System.out
messages will go to out.txt and System.err
messages will to err.txt. Basic point to remember is to think of System.out and System.err as streams to files (which is what they are) instead of a mechanism to output on the monitor, which is what I assumed as a beginner.
They go to the system stdout and stderr streams respectively. On most OSes these are distinct and can be sent to different places. For example, this might be useful if your program's output was to be parsed by another program - if it needed to report an error, stderr would normally be the better place for it as you might have set it up to get a human's attention.
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