Why is Scanner.close () useful in Java?
Scanner
opens a base OS file descriptor (or pipe or stream), which is usually written in a non-managed (usually C
language).
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.
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?
source to share