+ 1
How to close the object of Scanner class ?
If you have created an object of Scanner class for taking input. Then it's recommended to close the object. Even though JAVA Garbage Collector does it automatically. Why ? And what are different ways to do so ?
3 Respuestas
+ 2
Scanner sc = new Scanner(System.in);
//close
sc.close();
Dunno all that much about garbage collector, but since the scanner object still has a reference it wont consider it garbage and wont delete it
+ 1
Thanks Kilowac.
A few cases for GC :-
1)SoftReference
2)WeakReference
3)PhantomReference
Check this link :-
https://dzone.com/articles/weak-soft-and-phantom-references-in-java-and-why-they-matter
0
explicit .close() saves memory space and GC consumes less time to work.
You can use try-with-resources for same effect
try ( var sc = new Scanner(System.in) ;) {
...
}