-1

enter image description here

enter image description here

public class Main {
   public static final PrintStream x = null;

   public static void main(String[] args) {

      /*Line 8*/ System.out.println("Da");
      /*Line 9*/ x.println("Da");

   }
}

Why is line 8 working, even if the "out" reference is null, and on line 9, where I made another reference same as the reference "out" (static final of type "PrintStream" with a value of null) is not working and I get "NullPointerException"?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 5
    Please post your code here as text. – Scary Wombat Oct 02 '20 at 07:35
  • 1
    This is NOT a classic NPE question. Trust me on this ..... – Stephen C Oct 02 '20 at 07:41
  • @luk2302 it is `final` field, so it is reasonable to expect that value would not change. In this case it changes, but only because of `JVM` magic. – talex Oct 02 '20 at 07:44
  • One thing you can try, `System.out.println( System.out + ", " + x );` that way you can see System.out is not null but x is null when you make the call. – matt Oct 02 '20 at 08:29

2 Answers2

5

I think your second image is showing a snippet of the code of java.lang.System.

And I think you are asking "how come System.out.println works despite System.out being final and initialized to null".

The answer is ... magic!!

There is some deep dark magic in the JVM initialization that reassigns non-null values to System.in, System.out and System.err. Indeed, the specialness of these fields even gets a mention in the Java Language Specification (17.5.4 if you are curious).

Similar magic is used to make System.setOut(...) and friends work.

IMO, it is best to just trust that it works ... and not ask how.


And the corollary is that the reason your attempt to do something similar doesn't work is that your x field is behaving as expected. It has been initialized to null, and it stays that way. No magic going on here. Your code isn't "special".

(For what it is worth, in some contexts it is possible to use reflection to modify the value of a final field. But it is a bad idea. For a start, the JLS carefully does not specify what happens when you do this; see 17.5.3.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
4

System.out is somewhat magical field. Despite the fact that it is final and initialized with null it actually have non-null value.

It happens because JVM have special treatment for that (and some other) fields.

You can't reproduce such behavior with pure java, you need to use unsafe magic.

talex
  • 17,973
  • 3
  • 29
  • 66