0

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);
Christian
  • 22,585
  • 9
  • 80
  • 106
  • Why can't a `String` be closed? Well I imagine it's become there's nothing that gets opened. – christopher Jan 28 '15 at 08:10
  • 1
    See documentation for [`close()`](http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html#close()) method. Also read about the [garbage collector](http://stackoverflow.com/questions/3798424/what-is-the-garbage-collector-in-java). – gknicker Jan 28 '15 at 08:14
  • As @gknicker said, you need to read the documentation on both [Closable.close()](http://docs.oracle.com/javase/7/docs/api/java/lang/Closeable.html#close()) and [AutoClosable.close()](http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html#close()) - There is a subtle difference, but should be enough for you to understand. – ha9u63a7 Jan 28 '15 at 08:27
  • Why can you close a door but you can't close a fish? – Stephen C Jan 28 '15 at 09:14

2 Answers2

2

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.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • What is a stream? What is meant by "an open stream" ? – Koray Tugay Jan 28 '15 at 08:15
  • 1
    @KorayTugay - Answer to that question is [here](http://docs.oracle.com/javase/tutorial/essential/io/streams.html). An open stream is the one that is *opened* but not *closed*. - do you think it is necessary to explain the intrinsic details here?. because I think the OP will not be able to understand some things. – TheLostMind Jan 28 '15 at 08:18
  • 1
    @k - Anyways, I edited the answer to make it more generic by using the word *resource* . – TheLostMind Jan 28 '15 at 08:20
1

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.

Jens
  • 67,715
  • 15
  • 98
  • 113