+ 1

Why should I close the scan variable?

I usualy not close the scan and never get an error. But I saw in some codes the scan.close() method. Is it really necessary? What is the problem if I don`t do it?

22nd Jun 2017, 5:18 PM
Renan
Renan - avatar
5 ответов
+ 3
it won't give any error.. it is similar like handling file.. when u open a file then at the end the file must be closed.. similarly if u don't close the scanner class, the resources allocated for it will ne there until the process get over.. and u don't need to close it unless u r handling multiple of scanner objects.. And JVM usually do it for u.. which increases the time for compiling
22nd Jun 2017, 5:27 PM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
+ 3
@Sami Slight correction: The methods are not static, that's why you must create an object of the class to use them. You also said scan is not a variable, then you said it is a reference variable. 😜
22nd Jun 2017, 5:44 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
and btw scan is not a local variable.. Scanner is a class of utilities package.. and when u write Scanner scan= new Scanner(System.in); here it can be anything scan, src, obj or anything of your choice here scan is the reference variable which act as a pointer to the object Scanner(System.in) now by using scan u can fetch the Scanner class methods like scan.nextLine();
22nd Jun 2017, 5:33 PM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
0
in general variable we mean either the local or global.. but here it is the reference variable which is sort of pointer
22nd Jun 2017, 5:45 PM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
0
oh yes the methods which ate non-static can be accessed by the reference variable and the members which are static can be accessed using the class Name directly.. always get confused in it. 😅
22nd Jun 2017, 5:57 PM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar