Updates

Friday 26 July 2013

The most used statement in java "System.out.println()"

What is System.out.println

I didn't like it when I'm using it at first time and do you guys know the reasons why ? I need to write a huge statement to  print a single line rather than simple printf and cout in C and C++ respectively.Later on, I fell in deep love with it. Didn’t you? How many times have we used it till now? It is one of the most number of times compiled statement in the History of java.

System.out.println prints the argument passed, into the System.out which is generally stdout.
  • System – is a final class and cannot be instantiated. Therefore all its memebers (fields and methods) will be static and we understand that it is an utility class. As per javadoc, “…Among the facilities provided by theSystem class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array…”
  • out – is a static member field of System class and is of type PrintStream. Itsaccess specifiers are public final. This gets instantiated during startup and gets mapped with standard output console of the host. This stream is open by itself immediately after its instantiation and ready to accept data. When running a program from windows command line, it is the standard console.
  • println – println prints the argument passed to the standard console and a newline. There are multiple println methods with different arguments (overloading). Every println makes a call to print method and adds a newline. print calls write() and the story goes on like that.

Change out of System.out.println

‘out’ object can be customized. out gets initialized by java runtime environment at startup and it can be changed by developer during execution. Instead of standard output, in default cases when you run a program through command line, the output is printing in the same command window. We can change that behavior usingsetOut method as below. In the following example, I have redirected the output to a text file in the same directory.
public class ChangeOut {
  public static void main(String args[]) {
    try {
      System.setOut(new PrintStream(new FileOutputStream("log.txt")));
      System.out.println("Now the output is redirected!");
    } catch(Exception e) {}
  }
}

No comments:

Post a Comment