0

I have the following code. But i see that before passing Input.txt file, the "in" and "out" variable is set to null. Why do we do that?

package Test;
import java.io.*;

public class CopyFile {
public static void main(String args[]) throws IOException {  
      FileInputStream in = null;
      FileOutputStream out = null;

      try {
         in = new FileInputStream("input.txt");
         out = new FileOutputStream("output.txt");

         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }

}
Nikki
  • 1
  • 2

3 Answers3

0

As you may know, in a try...finally block, if an exception is thrown, the execution of the try block stops and it immediately goes to the finally block.

If you do not initialise the streams as nulls first, they might not be assigned any value, because an exception can very well be thrown during the initialisation of the first stream:

in = new FileInputStream("input.txt"); // may throw exception

If an exception is thrown here, in and out will not be initialised (all local variables have to be initialised first), so you cannot use them in the finally block:

if (in != null) { // in might not be initialized
    in.close();
}

Let's look at a simpler situation where the same thing happens.

int x;
if ... {
    x = 0;
}
System.out.println(x);

x is not assigned if the if statement condition is false, so the last print statement gives you a compiler error.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

As the answer in the first comment to your question indicates, you do not know for sure what your variables contain if you do not initialize them. Initializing them to null guarantees that nothing is in them which guarantees these lines will not have unexpected behavior. This is considered good practice.

Carl
  • 90
  • 1
  • 11
0

Initializing a variable to null allows for Lazy initialization.(initializing only when needed).
Member variables are often initialized to null and this often does not occur for local variables.
A local variable is initialized to null when we need to catch an exception that the constructor may throw and closing it in finally caluse as below.

 FileInputStream in = null;      
    try {
       in = new FileInputStream("input.txt");
        // ...
    } finally {
        if (in != null) {
            in.close();
        }
    }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Raj Vujji
  • 1
  • 1