Java @ Desk: Serialization | Java at your desk

Serialize static variable in java

Can we serialize static variable in java?
No. Since static members are associated with the class and they do not belong to the individual objects, they are not serialized. Static field values will be reinitialized to whatever value they are set to when the class is loaded.
Consider a below class with a static field with initial value as 10.

Person.java
 package com.serialization;  
 import java.io.Serializable;
 public class Person implements Serializable {  
   private static final long serialVersionUID = -8935100740005343248L;
   static int staticField = 10; 
   private String firstName;  
   private String lastName;  
   public Person(String firstName, String lastName) {  
     super();  
     this.firstName = firstName;  
     this.lastName = lastName;  
   }  

Serialization java example

To implement a very basic example of Serialization in java, lets create Person.java that implements Serializable interface.
Person.java
 package com.serialization;  
 import java.io.Serializable;
 public class Person implements Serializable {  
   private String firstName;  
   private String lastName;  
   public Person(String firstName, String lastName) {  
     super();  
     this.firstName = firstName;  
     this.lastName = lastName;  
   }  

Serialization in java

Serialization in java

What is serialization?
Serialization is a process to translate an object in a state/format that can be transferred over a network, stored in a file and the transmitted state/format can be used to get back the original object.
An object is converted to bytes and stored in a file. This process is called serialization.
Conversion of bytes into a original object is called de-serialization.

How to serialize an object in java?