Resource leak: 'sc' is never closed in vs code (I'm using the java coding pack from vs code website)

3.7k Views Asked by At

Why is vs code giving me a warning on this: (The warning is below the code)

import java.util.Scanner;

public class Input {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string");
        String input = sc.nextLine();
        System.out.println(input);
    }
}

The warning is:

Resource leak: 'sc' is never closed

1

There are 1 best solutions below

1
Utkarsh Sahu On

You can simply put sc.close() and this error will no more be displayed. It is not a compulsion. Without this statement also program works fine but if your eyes are getting disturbed by again and again popping u of the message of error then you can put sc.close(). Note that after you put it, you can not use sc to get input after that statement. To sort this error:

import java.util.Scanner;
public class Input {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string");
        String input = sc.nextLine();
        System.out.println(input);
        sc.close();
    }
}