Friday, 3 October 2014

Why, System.out and System.err are static in Java

     Most operating systems, support streams such as standard input - a keyboard, a file, or the output from another program and standard output - a terminal window, a printer, a file on disk, or the input to yet another program. standard error is for output the error messages that can be seen by the user even if the standard output is being redirected.

In java, these are assigned to static variables, System.out and System.err . When programs are start up on any operating systems, These streams are preassigned to particular platform dependent handles, or file descriptors. So that ordinary programs on these operating systems can read the standard input or write to the standard output or standard error stream without having to open any files or make any other special arrangements.

Java continued this tradition and included it in the System class. The static variables, System.out, and System.err are connected to the three operating system streams before your program begins execution. So, to read the standard input, you need only refer to the variable and call its methods. For example, to read one byte from the standard input, you call the read method of , which returns the byte in an integer variable.
package com.speakingcs.practice;


public class InputStreamDemo {

    public static void main(String[] args) {
 try {
     int b =;
 } catch (IOException e) {   

Don't forget to include read() method inside a try/catch block, because the read() throws an IOException. using read(), you can read a byte at a time from the standard input. if you want to read larger units such as integers, or a line of text, you can use Scanner, Reader classes. The Reader class has a character convertor, so that your program will work with multiple input encodings around the world. Use Buffer Reader class to read lines of characters.

To transfer results to console, use standard output (System.out), as shown in the previous program. println() method is an overloaded method which can be used to output any object to console.

To transfer error messages to the console, use standard error (System.err). The method println() is also available in System.err, which functions same as println() method of System.out.


Post a Comment

Note: only a member of this blog may post a comment.