Tuesday, November 26, 2013

Published 11/26/2013 by with 5 comments

Resource leak: 'scanner' is never closed

If you do not close the java.util.Scanner object after reading data, you can get an warning saying "Resource leak: 'scanner' is never closed".

In the code below see that the Scanner object is closed in a finally block after reading all inputs using the Scanner object.

int number1, number2;

Scanner scanner = new Scanner(System.in);

try
{
System.out.println("Ener the first number");
number1 = scanner.nextInt();
System.out.println("Ener the second number");
number2 = scanner.nextInt();
}
finally
{
scanner.close();
}

    email this       edit

5 comments:

  1. can you please explain what scanner.close(); actually does?

    ReplyDelete
    Replies
    1. You can read at http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close()

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. int number1, number2;

    Scanner scanner = new Scanner(System.in);

    try
    {
    System.out.println("Ener the first number");
    number1 = scanner.nextInt();
    System.out.println("Ener the second number");
    number2 = scanner.nextInt();
    }
    finally
    {
    scanner.close();
    }

    http://tehapps.com/

    ReplyDelete