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
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
}