Why there is no null pointer exception? [duplicate

2019-09-24 18:12发布

问题:

This question already has an answer here:

  • System.out is declared as static final and initialized with null? 2 answers

In the documentation code of java "out" is an object of PrintStream class which is initialized in the System class of package lang.This object "out" is initialized to null.So why does'nt the code throws a null pointer exception whenever the line

System.out.println(...); is used

回答1:

It is the field declaration.

Look at the initializeSystemClass() static method :

setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")))

The out is well initialized at a time by the VM.

The method is commented with this :

/**
 * Initialize the system class.  Called after thread initialization.
 */


回答2:

The .out variable is a static variable of System. It's the default outputStream and not null.

Java Documentation: This stream is already open and ready to accept output data.