compiler optimizes away a final field added to a serialized class
<p>This is a strange one, am wondering if this is by design or a compiler bug.  Am using Sun Java 6 on a PC, but also seen with Sun Java 5 on a linux box.</p>

<p>Suppose I have a file on disk containing a serialized class.  I then add a final field to the class and declare and initialize the field in one statement:</p>

<pre><code>public final int newField = 2;
</code></pre>

<p>If I read in an object that was serialized before this field was added, this new field is given a default value of 0, which is correct.  However, the compiler replaces occurrences of the field by the constant "2".  OTOH, if I instead initialize the new field inside of a constructor:</p>

<pre><code>Data (int d) {
    this.oldField = d;
    this.newField = 2;
}
</code></pre>

<p>then the field does not get optimized away and everything works as expected.</p>

<p>More explicitly, here is my Main class:</p>

<pre><code>import java.io.*;
public class Main {
    public static void main(String[] args) {
        try {       
            FileInputStream fis = new FileInputStream ("Data.txt");
            ObjectInputStream ois = new ObjectInputStream (fis);

            Data d = (Data)ois.readObject();
            ois.close();
            fis.close();

            d.print();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code></pre>

<p>and here is the Data class:</p>

<pre><code>import java.io.*;
public class Data implements Serializable {
    private static final long serialVersionUID = 1;
    private int oldField;
    private final int newField = 2;

    Data(int d) {
        this.oldField= d;
    }

    public void print() {        {
        System.out.println(this.oldField + " " + this.newField);
    }
}
</code></pre>

<p>So my Data.txt file has a serialized instance of the original class with just "oldField = 1".  So the expected output of running this is</p>

<pre><code>1 0
</code></pre>

<p>but instead I get</p>

<pre><code>1 2
</code></pre>

<p>whereas if I move the initialization into the constructor the output is correct.</p>

<p>Is this expected behaviour?  My feeling is that the compiler should not be optimizing away fields in serialized classes, precisely for this reason.  Perhaps that is asking too much.  Thanks!</p>
