Why a Scanner class object needs to be closed and a string class object can't?
Why it shows the warning UNUSED
for the object:
String obj = new String();
and can't be closed like:
Scanner sc = new Scanner(System.in);
Why a Scanner class object needs to be closed and a string class object can't?
Why it shows the warning UNUSED
for the object:
String obj = new String();
and can't be closed like:
Scanner sc = new Scanner(System.in);
A Scanner can hold reference to a resource(in your case it is the standard input stream). A stream needs to be first opened and then it is read.
So to use the same underlying resource without any issues, you need to close it. So the next call to open will not be blocked and the modifications made (if any) will not corrupt the resource.
You can't close a String
because it doesn't point to any IO resource like a file or a Stream. It points to a String object. In your house, you can close a door, but can you close a chair?
Why is shows warning UNUSED for the object:
Any Object that is created but not used is an unused object.
Why a Scanner class object needs to be close and a string class object can't
Scanner hold references to ressources like inputStream wich should be clossed. Strings doesn't do that.
Why is shows warning UNUSED for the object
Because you declare objects but never use it for reading the values.