Reputation: 452
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.
Upvotes: 1
Views: 6912
Reputation:
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.
Upvotes: 1
Reputation: 12953
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
Upvotes: 3