How to close scanner class if we did not create reference variable for object so how to avoid resource leak warning message

Viewed 337

How to close scanner class if we did not create object for it to avoid warning messages stating unassigned closable value, resource leak?

As I need to get input only once from user, I did not create reference variable for object Scanner class.

My declaration to get input

int num = new Scanner(System.in).nextInt();
3 Answers

i did not created object for Scanner class

yes, you did: new Scanner(System.in)

In case, you are allowed to use try-with-resource:

try(Scanner sc=new Scanner(System.in)){
  int num = sc.nextInt();
  /* TO DO */
}

OR, just use the .close():

Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
sc.close();

Or you can use try/finally:

Scanner sc = null;
try
{
    sc = new Scanner(System.in);
    int num = sc.nextInt();
}
finally
{
    if(sc!=null)
    {
       sc.close();
    }
}

There is no way with your syntax to close the scanner object.

Only one way I can think of right now is, if Scanner would not have been a final class, we could created a class which extends it says ScannerAutoClose and declare/override a finalize method for it and close the object in it using this.close(). The finalize method would have been called at the time of garbage collection so it get's closed automatically. But since Scanner is final class, this is out of the picture.

Related