• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Why is it a good practice to use close when using the scanner class ?

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why does java ide  give a warning when I don't use close while using the scanner class ? Does it have any benefit ?
 
Marshal
Posts: 79706
381
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is that an example of Eclipse being too clever for its own good? It is right that leaving a Scanner object open risks a resource leak, but it probably doesn't actually tell you to call its close() method. If you leave a Scanner pointing to a file open, then that file may be locked as unavailable to reading at least until the current JVM exits. So Scanners pointing to files, sockets, etc must be closed when you have finished with them, but you don't call close(). Not unless you are using an old version of Java®, that is. Since Java7 all closing of files is better done with try with resources instead.
There is an exception; you must never close Scanners or readers pointing to System.in (or something pointing to System.out/System.err). You can find out about the dire consequences of closing System.in in this old thread.
 
It runs on an internal combustion engine. This ad does not:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic