0

I have a program in java, in which I have to get user input, however, I only need to get the user input once, after that, I do not need a scanner anymore. Doing the following:

int userInput = new Scanner(System.in).nextInt();

Gives me a Resource Leak warning, saying that <unassigned closeable value> is never closed.

Is there another way I can use a Scanner only once, and get rid of it afterwards so there's no Resource Leak? Maybe something similar to C#'s using statement.

user2864740
  • 54,112
  • 10
  • 112
  • 187
Shadow
  • 3,666
  • 4
  • 17
  • 40

3 Answers3

6

The equivalent to C#'s using is a try-with-resources. Don't use that, it will close the System.in and you don't want that. Ignore the warning for this particular case. Let the garbage collector claim the Scanner and leave the standard input as is.

Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683
0

I can see the following two options... Option #1 : Explicitly close the scanner as soon as you read the input once.

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

Option #2 : Use the try-with-resource statement

try(Scanner sc1 = new Scanner(System.in)) {
   int userInput1 = sc1.nextInt();
}

The downside of option #2 is that it will close all the resources that exist in try-with-resource statement, which included System.in.

Nagakishore Sidde
  • 1,769
  • 13
  • 9
0

Java has Automatic garbage collection. Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.
This means you shall not to worry about this type of warnings. Additionally in Eclipse you can use@SuppressWarning to get rid of annoying warnings.

iColdBeZero
  • 255
  • 2
  • 11