Object read in with ObjectInputStream not retaining value after try-catch block
<p>So I write out an array of Car objects to a file. Then I when I try and read them back in the cars variable gets set on the statement <code>cars = (Car[])in.readObject();</code>. However when I step through it with the debugger the cars variable get 'unset' once I exit the try-catch block.</p>

<pre><code>Car[] cars;
try {
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename)));
    cars = (Car[])in.readObject();
    in.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}
</code></pre>

<p>If on the other hand I initialize the cars variable, for example to an empty array, the cars variable remains set after the try-catch block.</p>

<pre><code>Car[] cars = new Car[0];
try {
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename)));
    cars = (Car[])in.readObject();
    in.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}
</code></pre>

<p>So why is the cars variable retaining the reference to the Car[] that I read in with in.readObject only if I initialize it beforehand? I can't see why it should make any difference whether I initialize cars or not...either way it gets a reference to read in Car[] object in the try-catch block.</p>

<p>It seems like some of lazy-initialization is happening..that the virtual machine is only declaring space for the cars object in the try catch-block and hence it falls out of scope when it exits the block...</p>
