Java - closing BufferedReader

When I use BufferedReader for reading input in Java:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

and before end of main method I close this reader by calling br.close(), I got NZEC error. If I remove br.close(), I got correct answer.
Can anyone explain this behaviour?

People had faced similar problem : In Java solution of the following problem, getting NZEC on closing bufferedReader. - general - CodeChef Discuss & SPOJ BYTESM2 : JAVA RUNTIME ERROR (NZEC) - general - CodeChef Discuss

Brother, the close() method checks to see if the underlying Readable also implements the Closeable interface, and if it does it closes it. In your situation you are saying this is not a concern because it will be closed later.

But the close() method also sets some internal flags indicating that the Scanner (and underlying Readable) are closed. Many of the public methods first check to see if the Scanner has been closed. So the danger here would be that maybe your underlying Readable has been closed, but further calls to the Scanner don’t immediately throw an IllegalStateException, and instead fail in some other way as they proceed.

If you can ensure that nothing else has a handle to the Scanner instance in question, and won’t try to call any further methods on it, then you may be ok.

The close() method also nulls out its reference to the Readable, so if this doesn’t happen the Scanner wouldn’t get garbage collected as soon as it would have had you called close(). So avoid .close().

4 Likes