Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I would like to know what is null test in java? How to rewrite the below code by avoiding null test. I was asked this question in an online test. I'll be grateful for any help offered.

String mystere() throws IOException {
      InputStream input = null;
      try {
        input = new InputStream(new File("foo.txt"));
        return new Scanner(input).nextLine();
      } finally {
        if (input != null)
          input.close();
      }
    }
share|improve this question

1 Answer

up vote 6 down vote accepted

The null test is the input != null condition here.

In your code if the constructor of the stream throws an exception the reference remains null so there is no way to call close on it, therefore the constructor call could be before the try-catch block. The generic pattern is the following:

    final InputStream input = new FileInputStream(new File("foo.txt"));
    try {
        // do something with the stream
    } finally {
        input.close();
    }

Please note that I've changed new InputStream(...) to new FileInputStream(...). InputStream an interface, you cannot instantiate it.

In Java 7 it's a little bit simpler:

try (final InputStream input = new FileInputStream(new File("foo.txt"))) {
    // do something with the stream
}

References: Guideline 1-2: Release resources in all cases in the Secure Coding Guidelines for the Java Programming Language, Version 4.0 documentation.

share|improve this answer
1  
It's so cool in java 7. Thank you so much. – linguini Sep 2 '12 at 9:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.