Search code examples
javautility

Should utilites like the Scanner class be closed before application exit?


This is a fairly simple question, but I'm curious if it is standard to always close things like Scanner before the application exits.

For example, if I always want Scanner searching for next input in my application- if the application is closed should I close the Scanner object before exiting the application?


Solution

  • You should try to clean up resources as you go. When you are done with them, close them (except System.in unless you know it won't be used again)

    In the case of a shutdown, this can be ignored, but in general you shouldn't assume a program is about to shutdown, and using try-with-resources is a better option.

    try (Scanner in = .....) {
       // use "in"
    }
    // you might add code here later.
    

    In short, you don't need to worry about it in your case, but it would be best practice to clean up as you go.