DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • High-Performance Java Serialization to Different Formats
  • Did You Know the Fastest Way of Serializing a Java Field Is Not Serializing It at All?
  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality

Trending

  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • AI Meets Vector Databases: Redefining Data Retrieval in the Age of Intelligence
  1. DZone
  2. Coding
  3. Languages
  4. Serialization and De-Serialization in Java

Serialization and De-Serialization in Java

Not sure what serialization means for your code? Look no further.

By 
Dev Bhatia user avatar
Dev Bhatia
·
Nov. 27, 18 · Presentation
Likes (11)
Comment
Save
Tweet
Share
82.4K Views

Join the DZone community and get the full member experience.

Join For Free

when you create a class, you may create an object for that particular class and once we execute/terminate the program, the object is destroyed by itself via the garbage collector thread.

what happens if you want to call that class without re-creating the object? in those cases, what you do is use the serialization concept by converting data into a byte stream.

object serialization is a process used to convert the state of an object into a byte stream, which can be persisted into disk/file or sent over the network to any other running java virtual machine. the reverse process of creating an object from the byte stream is called deserialization . the byte stream created is platform independent. so, the object serialized on one platform can be deserialized on a different platform.

how to make a java class serializable?

serializability can be enabled in your java class by implementing the java.io.serializable interface. it is a marker interface that means it contains no methods or fields and only serves to identify the semantics of being serializable.

what if we are trying to serialize a non-serializable object?

we will get a runtimeexception saying: exception in thread "main" java.io.notserializableexception: java.io.objectoutputstream.

what is the serialversionuid?

serialversionuid is an id, which is stamped on an object when it gets serialized usually with the hashcode of the object. we can find serialversionuid for the object by the serialver tool in java.
syntax: serialver classname

serialversionuid is used for version control of an object. the consequence of not specifying serialversionuid is that when you add or modify any field in the class, then the already-serialized class will not be able to recover because the serialversionuid was generated for the new class and the old serialized object will be different. the java serialization process relies on correct serialversionuid for recovering the state of the serialized object and throws java.io.invalidclassexception in case of serialversionuid mismatch.

transient keyword

the transient modifier/keyword is applicable only for variables but not for methods and classes.
at the time of serialization, if we don't want to serialize the value of a particular variable to meet security constraints, then we should declare that variable as transient.

while performing serialization, the jvm ignores the original value of the transient variable and save default value to the file. hence, transient means not to serialize.

transient vs. static

a static variable is not part of an object state, and hence, it won't 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 causes no impact.

now, let us consider a program that shows serialization and de-serialization in java.

this pojo class employee implements the serializable interface:

package com.java.serialization;

import java.io.serializable;

public class employee implements serializable {

private static final long serialversionuid = 1l;

private string serializevaluename;
private transient int nonserializevaluesalary;

public string getserializevaluename() {
return serializevaluename;
}
public void setserializevaluename(string serializevaluename) {
this.serializevaluename = serializevaluename;
}
public int getnonserializevaluesalary() {
return nonserializevaluesalary;
}
public void setnonserializevaluesalary(int nonserializevaluesalary) {
this.nonserializevaluesalary = nonserializevaluesalary;
}

@override
public string tostring() {
return "employee [serializevaluename=" + serializevaluename + "]";
}
}


the following serializingobject program instantiates an employee object and serializes it to a file.

package com.java.serialization;

import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.objectoutputstream;


public class serializingobject {

public static void main(string[] args) {

employee employeeoutput = null;
fileoutputstream fos = null;
objectoutputstream oos = null;

employeeoutput = new employee();
employeeoutput.setserializevaluename("aman");
employeeoutput.setnonserializevaluesalary(50000);

try {
fos = new fileoutputstream("employee.ser");
oos = new objectoutputstream(fos);
oos.writeobject(employeeoutput);

system.out.println("serialized data is saved in employee.ser file");

oos.close();
fos.close();

} catch (ioexception e) {

e.printstacktrace();
} 
}
}


output :

serialized data is saved in employee.ser file.


the following deserializingobject program deserializes the employee object created in the serializingobject program.

package com.java.serialization;

import java.io.fileinputstream;
import java.io.ioexception;
import java.io.objectinputstream;

public class deserializingobject {

public static void main(string[] args) {

employee employeeinput = null;
fileinputstream fis = null;
objectinputstream ois = null;

try {
fis = new fileinputstream("employee.ser");
ois = new objectinputstream(fis);
employeeinput = (employee)ois.readobject();

system.out.println("serialized data is restored from employee.ser file");

ois.close();
fis.close();

} catch (ioexception | classnotfoundexception e) {
e.printstacktrace();
} 

system.out.println("name of employee is : " + employeeinput.getserializevaluename());
system.out.println("salary of employee is : " + employeeinput.getnonserializevaluesalary());
}
}


output:

serialized data is restored from employee.ser file
name of employee is : aman
salary of employee is : 0


Serialization Java (programming language) Object (computer science) Transient (computer programming)

Published at DZone with permission of Dev Bhatia. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • High-Performance Java Serialization to Different Formats
  • Did You Know the Fastest Way of Serializing a Java Field Is Not Serializing It at All?
  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!