I have seen in the System
class that the out
object (of type PrintStream
) is initialized with a null
value. How can we call method like System.out.prinln("");
?
In System class out variable initialized like this way:
package java.lang;
public final class System {
public final static PrintStream out = nullPrintStream();
private static PrintStream nullPrintStream() throws NullPointerException {
if (currentTimeMillis() > 0) {
return null;
}
throw new NullPointerException();
}
}
As per shown above code out
variable initialized by null and this variable is final, so it can not initialized further then how can we use "out" variable.
JVM calls the private static void initializeSystemClass()
method which initializes it.
See these two lines of code :
setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
setErr0(new PrintStream(new BufferedOutputStream(fdErr, 128), true));
These are the two native methods :
private static native void setOut0(PrintStream out);
private static native void setErr0(PrintStream err);
There is a nice article on it.