Thursday, May 15, 2014

System.out.println



System           

final class
out      

static member of final class and of type printStream
println 
method  of class printStream


System

 System is a Final class from java.lang package

public final class System extends object

Since it is a final class it  can’t be instantiated and inherited by other classes
err,in and out are some static fields in System class.


Out [public static final PrintStream out]
Of type printStream,  already open and ready to accept output data and print data to outputstream [console]
In  [public static final InputStream in]
Of type inputStream, open and ready to supply input data ,generally keyboard
err  [public static final PrintStream err]
Of type printStream, already open and ready to accept output data, and print data to standard error output stream[error console in eclipse]


Out

  A static member of  final System class  and type of PrintStream (standard output stream)

public static final PrintStream out

This stream is already opened by JVM during start-up and ready to accept output data. It is mapped to standard O/P console host.

When JVM is initialized it will call initializeSystemClass() and will initialize the system class and the out variable.  This will use the setout() to set the output to console.

println

A method of class PrintStream . Used to print on standard output. It will print the data to console and a newline. Internally it will call print()and then write() + newLine()

User can customize the out object setout() method. By default the O/P the data to console,  we can redirect it to any file using this setout()

      System.setOut(new PrintStream(new FileOutputStream("print.txt")));
      System.out.println(" output from console ");

In the above example, all the contents of the println will be written to the file “print.txt”




Disadvantage:

Use System.out.println only for our learning and internal debugging purpose. It will degrade performance . Since just println will call a sequence of print + write+ newline. Also system.out is not synchronized , implementing synchronization is very complex and that will degrade performance.
Use  Log4J for debugging purpose in your code , it has multiple levels of debugging options. Also Loggers are synchronized.




No comments:

Post a Comment