5
\$\begingroup\$

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();
      }
    }
\$\endgroup\$
7
\$\begingroup\$

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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