serialize static variables in java

serialize static variables in java

In Java, static variables are class-level variables, meaning they belong to the class itself rather than to any specific instance of the class. Serialization, on the other hand, is an instance-level mechanism that deals with the state of individual objects. Because of this fundamental difference, static variables are not serialized when an object is serialized.

serialize static variables in java

Key Points About Static Variables and Serialization

  • 1. Static Variables Belong to Class: Static variables are shared among all instances of a class. They are initialized when the class is loaded and remain in memory as long as the class is loaded.
  • 2. Serialization is Instance-Specific: Serialization captures the state of an object, which includes the non-static (instance) fields of that object. Static fields are not part of this state since they do not belong to any one object.
  • 3. Static Fields are Not Serialized: When an object is serialized, only its instance fields are written to the output stream. Static fields are ignored.

Example
```java
import java.io.*;

class Example implements Serializable {
    private static final long serialVersionUID = 1L;

    static int staticValue = 100;
    int instanceValue;

    Example(int instanceValue) {
        this.instanceValue = instanceValue;
    }

    public void displayValues() {
        System.out.println("staticValue: " + staticValue + ", instanceValue: " + instanceValue);
    }
}

public class StaticSerializationDemo {
    public static void main(String[] args) {
        Example example = new Example(200);

        // Display initial values
        System.out.println("Before serialization:");
        example.displayValues();

        // Serialize the object
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("example.ser"))) {
            oos.writeObject(example);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Change static value
        Example.staticValue = 300;

        // Deserialize the object
        Example deserializedExample = null;
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("example.ser"))) {
            deserializedExample = (Example) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        // Display values after deserialization
        System.out.println("After serialization:");
        if (deserializedExample != null) {
            deserializedExample.displayValues();
        }
    }
}
```

Explanation:

  • 1. Class Definition: The `Example` class implements `Serializable` and has both a static field (`staticValue`) and an instance field (`instanceValue`).
  • 2. Object Creation: An `Example` object is created with `instanceValue` set to 200.
  • 3. Serialization: The object’s state is displayed and then it is serialized to a file named “example.ser”.
  • 4. Modifying Static Value: After serialization, the static field `staticValue` is changed to 300.
  • 5. Deserialization: The object is deserialized from the file and its state is displayed again.

6. Output
Before serialization:
     ```
     staticValue: 100, instanceValue: 200
     ```
After serialization:
     ```
     staticValue: 300, instanceValue: 200
     ```

Conclusion:

As the example demonstrates, static fields are not serialized. The value of the static field `staticValue` changed after serialization but before deserialization, and this change is reflected in the deserialized object. This shows that static fields are not part of the serialized state of an object. Only instance fields are serialized and deserialized, preserving the object-specific state while ignoring class-level static fields.