+ 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 ?

17th Oct 2019, 8:06 PM
Mayank Singh
Mayank Singh - avatar
3 Antworten
+ 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
17th Oct 2019, 8:21 PM
Odyel
Odyel - avatar
+ 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
19th Oct 2019, 4:43 PM
Mayank Singh
Mayank Singh - avatar
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) ;) { ... }
18th Oct 2019, 10:46 AM
zemiak