Serialization in Java
=====================================
Introduction
Serialization
- The process of writing state of an object to a file is called Serialization.
- It is the process of converting an object from Java supported form into either file supported form or network supported form.
- By using FileOutputStream and ObjectOutputStream classes we can implement serialization.
De-Serialization
- The process of reading state of object from the file is called de-serialization.
- It is the process of converting an object from either file supported form or network supported form into java supported form.
- By using FileInputSream and ObjectInputStream classes we can implement de-serialization.
Ex.
- We can serialize only Serializable object.
- An object is said to be Serializable, if and only if the corresponding class implement Serializable interface.
- Serializable interface present in java.io package and it does not contain any method.
- It is also called marker interface.
- If we are trying to serialize a non serializable object then get NotSerializableException.
Transient Keyword:
- transient keyword ( Modifier ) applicable only for variables, but not for method or classes.
- At the time of serialization if we do not want to save the value of a particular variable to meet security concern then we should declare that variable as transient.
- While performing serialization, JVM ignores original value of transient variable and save default value to the file.
transient Vs static
- static variable is not part of object state and hence it would not participate in serialization.
- Due to this declaring static variable as transient there is no use.
final Vs transient
- final variables will be participated in serialization directly by the value.
- Hence declaring a final variable as transient there is no impact.
Summary
- We can serialize any number of object to the file but in which order we serialized in the same order only we have to de-serialized.
- Means, order of object is important in serialization.
Ex.
If we don't know order of object in serialization
Related Topic