Showing posts with label Static Keyword. Show all posts
Showing posts with label Static Keyword. Show all posts

Tuesday, 4 October 2016

Java Tutorial : Java IO (Java Serialization with static data member)

🚀 Enjoying Java Tutorials?

Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!

🔔 Subscribe to Ram N Java

Introduction

A classic interview and core Java conceptual question is: What happens to a static data member during object serialization? In Java, serialization is designed to persist the state of an object instance. Because static members belong to the class definition rather than any single instance, their behavior during serialization follows distinct rules.

Why Static Variables Are Not Serialized

In Java, static variables are loaded into memory when the class itself is loaded and are shared across all instances of that class.

  • Instance State vs Class State: Serialization persists only an instance's non-static fields. Static fields represent class-level state and are completely skipped by ObjectOutputStream.
  • No Storage in Byte Stream: The byte stream created during serialization contains no record of the static variable's value at the time the object was serialized.

What Happens During Deserialization?

When the object is deserialized using ObjectInputStream, Java loads the class if it is not already loaded. The static field will reflect whatever value is currently loaded in the JVM's memory, not the value it held when the object was written to the stream.

If the static variable was modified after serialization took place, reading the object back will expose that updated static value—proving it was never persisted with the object.

Static vs Transient in Serialization

Feature static Variable transient Variable
Belongs To Class level Object instance level
Serialized? No No
Value After Deserialization Current value in JVM memory Default data type value (null, 0, false)

Related Tutorials from Ram N Java


Click here to watch in Youtube :
https://www.youtube.com/watch?v=zVAKxCyCedk&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial : Java IO (Java Serialization with static data member) 
See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Tutorials