Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Scanner "unassigned closeable value" is never closed [Eclipse]

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);
}
like image 371
RickiE Avatar asked Jun 28 '26 04:06

RickiE


2 Answers

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

like image 76
Andreas detests censorship Avatar answered Jun 30 '26 17:06

Andreas detests censorship


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.

like image 28
Shailesh Jain Avatar answered Jun 30 '26 18:06

Shailesh Jain