Short answer: No, but it is however in many cases very advisable to do so.
A scanner works on some kind of resource. This can be a String
, but in many cases it is either the standard input channel, a file, network stream or another resource.
For stdin
, that's not much of a problem. The stdin
normally lives (and dies) with your application. It is better not to close the stream, since perhaps another object is interested in reading from the standard input channel.
If you however read from files/network/driver/... this means Java has asked the operating system first if it could use that resource. This means the resource is allocated to the application. Other applications that wish to write to the file (or read and write in case your program should write to the file) are (at least temporary) denied access to that resource. It is thus interesting to give up resources as soon as possible.
The last aspect is not obliged however. The Java virtual machine will when it is terminated/the garbage collector passes by close the resources that are no longer accessible by the program. Furthermore the operating system will definitely release the resources if your Java application is killed (terminated) by you, another program,...
It is however polite to give up resources as soon as possible (don't take it too literally it's not a huge problem if you release them a few (milli)seconds later). Furthermore not giving up resources early enough can get the system into a deadlock or livelock. In the case of a deadlock, two programs are waiting for a resource to become available again while holding the other resource. Since none of the programs give up their own resource, the programs will wait forever. If this situation occurs the system is stuck.
Finally active resources also result in additional memory/cpu usage. After all the OS manages these resources, so it is reasonable to assume that to manage them, they will a use a small amount of CPU. In many cases active files are loaded (partly) into memory. The same goes for network resources,... In general the footprint isn't very huge, but you can imagine if all programs would keep resources until they terminate, this would have a large impact.
stdin
, no, it's not a good idea. In most other cases, it is... – Mallard