3

Can somebody help on try with resource in java

try(InputStream inputStream = new FileInputStream(new File(some file)))
{
     if(inputStream == null)       //Line 3
     {
      }
}
catch(IOException e)
{
}

I want to know, is it necessary to check null on line 3. Will there be any situation or circumstances where inputStream can be null at line 3 ?

Dark Matter
  • 300
  • 2
  • 15

2 Answers2

3

Given your code, no:

InputStream inputStream = new FileInputStream(new File(some file)) will be executed before the contents of the try block. Either it will succeed, so inputStream will not be null, or it will fail, throwing an exception in the process, so the contents of the try block will never be executed.

MyStackRunnethOver
  • 4,872
  • 2
  • 28
  • 42
1

I want to know, is it necessary to check null on line 3.

No. As long as you keep the expression new FileInputStream(new File("path/to/file")), the result will be a non-null object of FileInputStream. The check on line 3 is unnecessary.

Will there be any situation or circumstances where inputStream can be null at line 3?

Yes. If you assign any expression that returns null to inputStream. It's not really practical since you can't do anything with the stream except for checking it on null. In that case, the check on line 3 may come in handy.

For example,

try (InputStream s = null) {}
catch (IOException e) {}
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142