What would really happen if I don't use x.close() if I want to close a Scanner object or any other object.What is the usage of close() method.Please give example of what happens if we don't use close method.
Asked
Active
Viewed 5,176 times
1
-
The `close()` method releases the resources held by the Scanner. You can do a try-with-resources to automatically close the Scanner. – callyalater Feb 15 '16 at 21:49
-
You can refer to this link: [http://stackoverflow.com/questions/7118603/explain-the-close-method-in-java-in-laymans-terms](http://stackoverflow.com/questions/7118603/explain-the-close-method-in-java-in-laymans-terms) – Orin Feb 15 '16 at 21:49
-
It really depends on what the object is -- but generally, the risk is that you won't be freeing up limited system resources. For instance, a database will often limit how many concurrent connections it allows, so if you open a database connection and don't close it when you're done, you could prevent other connections (from your app or another). – yshavit Feb 15 '16 at 21:50
-
If you don't call `x.close()` on `new Scanner(System.in)`, that's fine - you generally don't want to close streams that you didn't open. It might have unexpected consequences subsequently-executed code. – Andy Turner Feb 15 '16 at 21:51
-
So calling x.close() is a way to close objects that I'm done working with.Suppose I have created 3 objects: x1, x2, x3 and done working with x1 and x2 but not x3, I will do x1.close() , x2.close()? And it is considered good practice, right? @everyone who replied – Elijah Dayan Feb 15 '16 at 22:15
2 Answers
3
The method's purpose really depends on the class it belongs to, but in your example (Scanner) and in most cases that involves some IO operations like file reader, streams, connection and such - the idea behind close() method is to close the connection and release the resource, which is usually something that consumes memory from the program.
If you don't do it - well, you're using a resource you don't need, which will make the cpu/memory work harder than it needs, so it is recommended to always use it when you're done with the object

Nir Levy
- 12,750
- 3
- 21
- 38
-
The good thing about closing your objects is it also gives the system a chance to clean up properly - lots of writers buffer their output, and closing lets it know that it should flush the output and then release the resource – Jeeter Feb 15 '16 at 21:55
1
The most effective example is file object.When you create a file object, you exit the file using the close() method,otherwise it will be kept open while you're doing some other operations.