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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  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.

Dev Bhatia user avatar by
Dev Bhatia
·
Nov. 27, 18 · Presentation
Like (11)
Save
Tweet
Share
81.04K 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.

Popular on DZone

  • The Future of Cloud Engineering Evolves
  • How To Generate Code Coverage Report Using JaCoCo-Maven Plugin
  • Kotlin Is More Fun Than Java And This Is a Big Deal
  • A Complete Guide to AngularJS Testing

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: