3

I just wanted to know if the out variable in System.out.println() is initialized in the static block of the System class. The out field is declared as a final static variable, which equals null (public final static PrintStream out = null;) . Since out is pointing to null, I assume it is being pointed to the PrintStream object somewhere. But I can't see the code except a native method called registerNatives(). Is it being pointed to in a native method? Why is it being done that way (any performance advantage)? Also, the documentation for the out variable in System says:

The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user."

Thanks.

entpnerd
  • 10,049
  • 8
  • 47
  • 68
javaAndBeyond
  • 520
  • 1
  • 9
  • 26
  • I'm guessing that `out` just varies from a platform to an other. So it wouldn't make any sense to initialize it in Java. Each platform must then create the object according to their respective architecture – Gaktan Jan 16 '16 at 04:58
  • 2
    It's actually well known that the JVM plays special tricks with `out`, for example if `out` is `final` how can you call `System.setOut()` on it? The answer is it isn't really final, and the JVM has been hard coded to ignore the modifier (although the assignment is still thread safe -- that's also hard coded). – markspace Jan 16 '16 at 05:28

1 Answers1

5

Reference JDK 1.8

The out registration flow

Java Virtual Machine (JVM) invokes

private static void initializeSystemClass() at line-1155

The function call

setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding"))) at line-1192 invokes

actual native method defined

private static native void setOut0(PrintStream out); at line-258;

then setOut0 then initializes the out class memeber.

Arjun
  • 3,248
  • 18
  • 35