Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.close() function in Java

So I’ve been following thenewboston java tutorials and in the 6th tutorial it shows the following code without any problem. But when I do it on VS code it gives the error "Resource leak: ‘bucky’ is never closed"

import java.util.Scanner;

class apples{
 public static void main(String args[]){
  Scanner bucky = new Scanner(System.in);
  System.out.println(bucky.nextLine());
 }
}

So I did a quick search on stackoverflow and found it needs,

bucky.close();

at the end

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why did the video’s code worked without the close() function?

>Solution :

Yes this is the warning you will get if you left any io/connection opened and never closed it after use. It simply means you have an unnecessary io opened which is a resource leak.
In your case it is a simple code which is taking input and printing it but let’s consider an application that do heavy tasks and leaving these opened io behind will cause your system out of resources soon.
If you want to avoid this by default then just try try-with-resources which will automatically close the scanner stream once you exist the try block.for eg

Scanner in=null;
try(in=new Scanner(System.in)){
// your stuff
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading