2

Whenever I type the scanner as a "nested line" it will warn me that [Resource leak: 'unassigned closeable value' is never closed] and advised me to add @SuppressWarnings("resource") at top of it.

Is it right to just add the @SuppressWarnings("resource") as it advised or there is another way which is more preferable?

public static void main(String [] args){
    String name = new Scanner(System.in).nextLine();    
    System.out.printf("My name is %s", name);
}
RickiE
  • 25
  • 1
  • 5
  • Store the scanner in a variable, and then use `scanner.close()` at the end to close it – user Jul 14 '20 at 15:48
  • What is telling your this? The java compiler (what version?) or an IDE? When I run your code on the command line in Java 9, I am getting no such warning. – Scratte Jul 14 '20 at 16:36
  • It seems a bit superfluous to complain about resources not getting freed on termination in any case. – user13784117 Jul 14 '20 at 16:40
  • 1
    Check out this: https://stackoverflow.com/q/11463327/5468463 – Vega Jul 14 '20 at 16:55

2 Answers2

1

You can use try-with-resource construct as below:

try(Scanner scanner = new Scanner(System.in)){
        String name = scanner.nextLine();
        System.out.printf("My name is %s", name);
    }

Scanner is a resource and it needs to be closed. Either close it manually by calling close() method in finally block or use try-with-resource as above so that it closes the resource automatically.

  • 6
    Be careful: closing the Scanner will also close System.in, and you will not be able to do another `new Scanner(System.in)` in your application after you close it. – DodgyCodeException Jul 14 '20 at 16:02
1

Your IDE is likely warning you about not calling close(), because Scanner implements Closable. As you don't want to close System.in, suppress the warning, and forget about it. You can check your IDE's settings for what it should warn about (resource). It is simply just not detecting that the scanner is using System.in.

IntelliJ IDEA? You have probably enabled one or more of these:

Preferences -> Editor -> Inspections -> Resource management -> ...

enter image description here