OptionalDataException in java
<pre><code>  package com.n;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class S implements Serializable {

    private static final long serialVersionUID = 1L;
     transient int i;


    public static void main(String[] args) throws Exception, IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
                "c:\\jav\\f.txt"));
        S obj1 = new S(10);
        oos.writeInt(obj1.i);
        oos.writeObject(obj1);


        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
        "c:\\jav\\f.txt"));

        System.out.println("Object contains &gt;&gt; "+ois.readObject());

        System.out.println("Transient variable written separately yields &gt;&gt; i= "+ois.readInt());
    }

    public S(int i) {

        this.i = i;
    }

    @Override
    public String toString() {

        return "i= " + i;
    }


}
</code></pre>

<p>The code above throws</p>

<pre><code> Exception in thread "main" java.io.OptionalDataException
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readObject(Unknown Source)
    at com.n.S.main(S.java:27)
</code></pre>

<p>but when i interchange the the output lines like</p>

<pre><code> System.out.println("Transient variable written separately yields &gt;&gt; i= "+ois.readInt());
    System.out.println("Object contains &gt;&gt; "+ois.readObject());
</code></pre>

<p>It runs fine. But why is it so and do i have to write as well as read the serialized primitive values 1st and then read or write the object ??? And what is optional data exception???</p>
