4

How System.out.println method works in both static and non static context?

Is there any JVM specific implementation is the answer for this?

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
bpn
  • 47
  • 3

1 Answers1

2

System.out is a static field / global object / singleton.

It is accessible everywhere, no need for a non-static context.

On that object (a PrintStream instance) you can call the println method.

Note that PrintStream#println is not a static method. But you can call non-static methods even from static methods as long as you have an instance to call them on (such as System.out here).

Static vs non-static context only makes a difference if you need access to this (the current instance of your own class). That is not needed here (unless you want to do System.out.println(this) -- that would not work from inside a static method).

None of this is "special" about System.out or requires internal JVM magic.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 1
    Actually System class static block get initialized with registerNatives() .. And VM will invoke private initializeSystemClass() which calls a private native method setOut0(....native calls to c) which intializes PrintStream out to system depending output stream object. Thanks 4 Ur answers. – bpn Sep 25 '19 at 09:53