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); } 
Add Comment
2 Answer(s)

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

Answered on July 16, 2020.
Add Comment

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.

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.