HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMinor

what is Null Test in java? and how to rewrite the code to do the same by avoiding null test

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
samethewhatnullrewritejavacodetesthowand

Problem

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();
      }
    }

Solution

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.

Code Snippets

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

Context

StackExchange Code Review Q#15275, answer score: 7

Revisions (0)

No revisions yet.