Why is Scanner.close () useful in Java?

I know it worked for the resources. But won't this be automatically closed if no further use is detected, like other objects? For the same reason I never deconstruct one object, is that a bad habit? Thank you very much.


source to share

4 answers


opens a base OS file descriptor (or pipe or stream), which is usually written in a non-managed (usually C


A stream that is open open can remain open until the kernel decides to close it (for example, after the program finishes executing ... highly implementation dependent).

Hence, it is a good idea to close the resource explicitly.



The method java.util.Scanner.close()

closes this scanner. If this scanner is not already closed, then if its underlying readable also implements the interface Closeable

, then the readable close method will be called. If this scanner is already closed, calling this method will have no effect.



We need to close the scanner because

  • It removes the underlying readable object (input source) for garbage collection.
  • Further actions on the scanner object will not be allowed and will result in an iIllegalStateException.

So, it is recommended to use the close () function.



When a new scanner is created, technically you keep the link to the resource. Let's say we are reading a file using an InputStream, you have a pointer to an InputStream object.

When we have finished reading the object / file and the handler is still open, we are still referring to that object, although we do not need it. Calling a private explication requires resources to be released as we are not using that. This will make it a little easier - if we have a resource limit (ex: DB limits, 500 reads allowed) and also easier for the GC as unused references are freed up and it may take less time.

The best way to present is in SQLConnection. Why are you keeping one connection if you are not using it?



All Articles