1

In my code I opened two scanner methods but closing one scanner closes all`

class x{
    public static void main(String args[]){
        Scanner s = new Scanner(System.in);
        void print(){
        Scanner xd = new Scanner (System.in);
         xd.close()
     }
}

`here xd.close closes my scanner s too why so? and how can it overcome this? friends I need to know why?. And is there any other way to temporarily close my scanner to prevent memory leakage?

somes k
  • 31
  • 9

2 Answers2

4

Why? Because that is how the specification says it should behave; see @Sun's answer for the reference and the text from the spec.

And how can it overcome this?

Don't call close() in a Scanner that wraps System.in. This is just an application of the general principle that a resource should be closed by the same code that opens it. (The JVM opens System.in so you shouldn't close it.)

Alternatively if you must close the Scanner, write or find a InputStream wrapper class that ignores the close() method and then use that to wrap System.in.

By the way, it is a bad idea to instantiate new Scanner(System.in) more than once. The problem is that a Scanner may read any or all type-ahead. If you have two or more of them wrapping the same underlying stream, one Scanner can capture input that a later one needs to read. This can lead to occasional unexpected behavior, and is likely to cause your application to fail if standard input is redirected ... at the shell level.

Stephen C
  • 632,615
  • 86
  • 730
  • 1,096
3

Because Scanner.close will close System.in implicitly:

If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked.

xingbin
  • 23,890
  • 7
  • 43
  • 79