-1

This is probably something everybody knows already, which is why I haven't been able to find the answer anywhere, but here goes anyway.

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

sc.close();

OR

int n = new Scanner(System.in).nextInt();

I recently found out that Scanners need to be "closed" after you finish using them.
However, I have almost always instantiated my Scanners "on the fly" without creating a dedicated object, so I can't really close them.
I thought this was something the garbage collector handled.

Is this a bad practice?

Temp14
  • 1
  • 3
  • You have always created an object, it's the `new Scanner` that does it, the only thing you didn't do, is keep a reference of it in a variable – azro Aug 05 '23 at 13:12
  • 3
    Scanner implements AutoClosable you should do https://stackoverflow.com/a/29865407/7212686 – azro Aug 05 '23 at 13:14
  • 3
    You **don't** want to close a scanner, or any other reader, that wraps around `System.in` - [Close a Scanner linked to System.in](https://stackoverflow.com/questions/14142853/close-a-scanner-linked-to-system-in). – Chaosfire Aug 05 '23 at 13:22
  • *`I recently found out that Scanners need to be "closed" after you finish using them.`* Then find a new source of information. If you close a Scanner that has opened `System.in` you won't be able to read from that `inputStream` even if you create a new Scanner within the same program. – WJS Aug 05 '23 at 14:10
  • 1
    OP, as well as @azro - are making a big mistake: You __SHOULD NOT__ close scanners. You only close resources you made yourself - you didn't make `System.in`, and closing the scanner also closes System.in. Hence, do not close it. – rzwitserloot Aug 05 '23 at 14:17
  • It's always considered _"bad practice"_ to deviate from the intended use. In the instance of _System#in_, you could only do this if you don't plan on compiling and running numerous instances. Basically, the entire concept of the _[Closeable](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/io/Closeable.html)_ interface is to increase the precedence of the stream, within the objects. It's easier to maintain the stream rather than leave unfinished code. This won't typically be recommended by others, because if it creates code that can be confusing it decipher. – Reilas Aug 05 '23 at 22:12

0 Answers0