1

As to access the methods of PrintStram class an object must be created, so how the out variable is able to access those methods when it is assigned null.

  public final static PrintStream out = null;

This is the declaration in System class.

I tried to write the similar code but then it gives NullPointerException. My code is given below.

class First{

public  void display(){
    System.out.println("Hello");
}

}

 class Second{

public final static  First s1=null;

 }

  public class  Third{

  public static void main(String[] args) {

    Second.s1.display();

 }
 }

To make this code run i will have to make either display method static or define s1 as-

public final static  First s1=new First(); 
Prafull Bajpai
  • 33
  • 1
  • 2
  • 5

2 Answers2

0

The field isn't null at runtime. It's assigned the relevant stream stdout or something else if it has been redirected. The mechanism is internal to the JVM, so the code isn't readily visible in the JDK sources. You can use System.setOut() to modify the field, which again uses internal mechanisms as the field is final and normally wouldn't be assignable.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

You may have missed the System.initializeSystemClass() which according to the documentation is called after the class initialization. It initialize the in, out and err stream. It use native methods to do that, so it doesn't have to respect the final modifiers.