senpai YJ
senpai YJ

Reputation: 41

Why is Scanner.close() useful in Java?

I know it's operated for the sake of resources. But wouldn't it automatically be closed if no further use is detected, just like other objects? For the same reason, I never deconstruct a single object, is it a bad habit? Thank you very much.

Upvotes: 4

Views: 8027

Answers (4)

Subodh Karwa
Subodh Karwa

Reputation: 2725

When a new Scanner is created, technically you are holding reference to the resource. Lets say, we are reading a file using InputStream, you will be having a pointer to the InputStream object.

When, we are done reading the object/file and the handler is still open, we are still referencing that object even though we don't need this. Calling close explicity asks the resouces to be released as we are not using this. This makes a bit easier - if we have constraint on resources(Eg: constraints on DB , 500 reads allowed) as well as easier for GC's as unused references are released and less time may be required.

A better way to imagine, in an SQLConnection. Why would you hold one connection if you are not using it ?

Upvotes: 0

OTM
OTM

Reputation: 654

We need to close the scanner because

  1. It nulls out the underlying Readable object (input source) to aid in garbage collection.
  2. Futher operations on the scanner object will not be allowed and will result iIllegalStateException.

So, its a recommended practice to use close().

Upvotes: 1

user7777664
user7777664

Reputation:

The java.util.Scanner.close() method closes this scanner.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. If this scanner is already closed then invoking this method will have no effect.

Upvotes: 1

user2768308
user2768308

Reputation:

Scanner opens an underlying OS's file descriptor (or file channel, or stream), which typically is written in a non-managed(typically C language).

A stream kept open, can sometimes stay opened until the kernel decides to close it(like, after the program has completed execution... highly implementation dependent).

Hence its a good idea to close the resource explicitly.

Upvotes: 1

Related Questions