Search code examples
javanullpointerexceptionprintstream

A PrintStream that does nothing


I am trying to make a PrintStream that does nothing every time its methods are invoked. The code has no error apparently, but when I try to use it I get a java.lang.NullPointerException: Null output stream. What am I doing wrong?

public class DoNothingPrintStream extends PrintStream {
    
    public static final DoNothingPrintStream doNothingPrintStream = new DoNothingPrintStream();

    private static final OutputStream support = new OutputStream() {
        public void write(int b) {}
    };
    // ======================================================
        // TODO | Constructor
    
    /** Creates a new {@link DoNothingPrintStream}.
     * 
     */
    private DoNothingPrintStream() {
        super( support );
        if( support == null )
            System.out.println("DoNothingStream has null support");
    }
    
    
}

Solution

  • The problem is in the initialisation order. Static fields are initialised in the order that you have declared them ("textual order"), so doNothingPrintStream is initialised before support.

    When doNothingPrintStream = new DoNothingPrintStream(); is executing, support has not been initialised yet, because its declaration is after the declaration of doNothingPrintStream. This is why in the constructor, support is null.

    Your "support is null" message doesn't get printed, because the exception got thrown (at the super() call) before it could be printed.

    Just switch around the orders of the declarations:

    private static final OutputStream support = new OutputStream() {
        public void write(int b) {}
    };
    
    public static final DoNothingPrintStream doNothingPrintStream = new DoNothingPrintStream();