Why does Eclipse give me the warming "Resource leak: 'in' is never closed" in the following code?
public void readShapeData() {
Scanner in = new Scanner(System.in);
System.out.println("Enter the width of the Rectangle: ");
width = in.nextDouble();
System.out.println("Enter the height of the Rectangle: ");
height = in.nextDouble();
Generally, instances of classes that deal with I/O should be closed after you're finished with them. So at the end of your code you could add
in.close()
.I fixed it by declaring in as a private static Scanner class variable. Not sure why that fixed it but that is what eclipse recommended I do.
It will close
Scanner
and shut the warning.The Scanner should be closed. It is a good practice to close Readers, Streams...and this kind of objects to free up resources and aovid memory leaks; and doing so in a finally block to make sure that they are closed up even if an exception occurs while handling those objects.
You need call
in.close()
, in afinally
block to ensure it occurs.From the Eclipse documentation, here is why it flags this particular problem (emphasis mine):
Full explanation here.