Tuesday, August 3, 2010

SOP statements

During one of my friend's interview few questions were asked about SOP statements. Those are as follows.

How do you write message on standard output?
This is very trivial question and most of the Java developer have used SOPs several times while writing code,  debugging code or providing additional information to the user.

System.out.println("Write SOP Here");

In eclipse type Syso, and press CTRL+Enter, it will expand it to System.out.println. This was the very simple question to answer.

Sequel of the first question was, What do these components represent?
Few of us may know and few may not. So lets have a look on each of them.

There are 3 component of the statement.
System class can neither be instantiated nor be overridden as its default constructor which is marked as private. This class provide few utility important utility methods.

Out is the final and static instance of the PrintStream class. It is instantiated with the application and remain unchanged and log the data on the configuration of the system. PrintStream class belongs to java io package.

println is a method which flushes data and appends a New line character to printstream instance.

Sometime this information is not sufficient to answer this question efficiently. There is one more question that struck to my mind.

java.io have many other write streams also, so why was PrintStream chosen to write data on standard output?

Many of us may not know the answer. Lets start with what java doc has to say about it.

PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkError method. Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written.

As it does not throw any exception and data flushes after certain amount of bytes. This class provides suitable mechanism to use as a standard output stream to display all stack in exceptional scenarios as well.

After writing this entry my own fundamentals have improved about SOP and its components. I hope it helped you as well.

Disclaimer: All the material here is the result of research and understanding of other material. If there is some content which is either incorrect or inappropriate to the context of the article I am always open for discussion.