-2

I had a line of code

Scanner input = new Scanner (System.in);

and I use input to get some user input.

My program warns me that there is a resource leak because input is never closed.

Once I add the line

input.close();

it stops complaining and everything works fine.

I am new to Java and was wondering what is the purpose of closing input? what does it do.

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
psj01
  • 3,075
  • 6
  • 32
  • 63
  • 1
    Note: in this case it's not necessarily a good idea, because `input.close()` also calls `System.in.close`. If you're working with files, or sockets, or anything else, then you do want to close them, hence the warning. – user253751 Aug 19 '15 at 03:40
  • Closing resources is a good practice to avoid leaks. However, for the usage in this question, you should also take a look at http://stackoverflow.com/questions/14142853/close-a-scanner-linked-to-system-in as your `Scanner` is tied to `System.in`. – Dante WWWW Aug 19 '15 at 03:42

1 Answers1

1

It prevents memory leaks. When Scanners (or any other File I/O classes) are closed, their resources are released and memory is freed.

saagarjha
  • 2,221
  • 1
  • 20
  • 37