0

Below is my sample code:

public class Hybrid {
public static void main(String[] args) {
    Cultivate cultivate1 = new Cultivate();
    try{
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("myfile"));
        os.writeObject(cultivate1);
        os.close();

        System.out.println("line 1 : "+ ++cultivate1.z+" ");

        ObjectInputStream is = new ObjectInputStream(new FileInputStream("myfile"));
        Cultivate cultivate2 = (Cultivate)is.readObject();
        is.close();

        System.out.println("line 2 : "+cultivate1.y+" "+cultivate2.z);

    } catch(Exception x){
        System.out.println("exc");
    }
}
}
class Cultivate implements Serializable{
    transient int y=3;
    static int z = 6;
}

and here is the output:

line 1 : 7 
line 2 : 3 7

Can someone explain why cultivate2.z prints 7? The value for cultivate1.z is incremented after the output stream is closed. So how is this modification reflected upon desialization?

2 Answers 2

2

Static variables are not serialized, So during deserialization static variable value will loaded from the class.(Current value will be loaded.)

Here the JavaDoc from ObjectOutputStream:

The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.

Sign up to request clarification or add additional context in comments.

Comments

2

z is a static field i.e. it is a Class level field and not an instance specific field.

Static variables belong to a class and not to any individual instance. The concept of serialization is concerned with the object's current state. Only data associated with a specific instance of a class is serialized, therefore static member fields are ignored during serialization.

So during deserialization, value of static variable value will be loaded from the class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.