Java Serialization

Have you ever seen what is inside a serialized object? I will explain you what is java serialization, then provide you with a sample for serialization. Finally most importantly, lets explore what is inside a serialized object and what it means. That is internals of java serialization and how does it works. If you want to have your own implementation of java serialization, this article will provide you with a good platform to launch.

What is Java Serialization?

Primary purpose of java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again. When there are two different parties involved, you need a protocol to rebuild the exact same object again. Java serialization API just provides you that. Other ways you can leverage the feature of serialization is, you can use it to perform a deep copy.

Why I used ‘primary purpose’ in the above definition is, sometimes people use java serialization as a replacement for database. Just a placeholder where you can persist an object across sessions. This is not the primary purpose of java serialization. Sometimes, when I interview candidates for Java I hear them saying java serialization is used for storing (to preserve the state) an object and retrieving it. They use it synonymously with database. This is a wrong perception for serialization.

How do you serialize?

When you want to serialize an object, that respective class should implement the marker interface serializable. It just informs the compiler that this java class can be serialized. You can tag properties that should not be serialized as transient. You open a stream and write the object into it. Java API takes care of the serialization protocol and persists the java object in a file in conformance with the protocol. De-serialization is the process of getting the object back from the file to its original form.

Here protocol means, understanding between serializing person and de-serializing person. What will be the contents of file containing the serialized object? This serves as a guideline to de-serialize. Have a look at the following sample and how its serialized file looks.

Sample Source Code for Java Serialization

package com.javapapers.sample;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class SerializationBox implements Serializable {

	private byte serializableProp = 10;

	public byte getSerializableProp() {
		return serializableProp;
	}
}

public class SerializationSample {

	public static void main(String args[]) throws IOException,
			FileNotFoundException, ClassNotFoundException {

		SerializationBox serialB = new SerializationBox();
		serialize("serial.out", serialB);
		SerializationBox sb = (SerializationBox) deSerialize("serial.out");
		System.out.println(sb.getSerializableProp());
	}

	public static void serialize(String outFile, Object serializableObject)
			throws IOException {
		FileOutputStream fos = new FileOutputStream(outFile);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(serializableObject);
	}

	public static Object deSerialize(String serilizedObject)
			throws FileNotFoundException, IOException, ClassNotFoundException {
		FileInputStream fis = new FileInputStream(serilizedObject);
		ObjectInputStream ois = new ObjectInputStream(fis);
		return ois.readObject();
	}
}
Ads by Google

Exploring Java Serialization

Look at following image. After serializing ‘SerializationBox’ in the above sample code, I opened the output in a hex editor. You can use Notepad++ and hex plugin to open the serialized file.

Let us look at contents byte by byte and find out what they are. It starts with “ac ed”. It is is called STREAM_MAGIC. It is a magic number (java API guys says) that is written to the stream header. It denotes that is start of serialzed content.Serialized Output

Similarly every character has a meaning. Actually the serialized file is more bulkier than you would expect, as it has a huge header the meta information of the classes involved and finally the content. Object Serialization Stream Protocol have a look at chapter 6.4.2 Terminal Symbols and Constants. It gives you list of symbols and constants used in serialization.

Decrypting Serialized Java Object

In the image, I have underline a unit of information in a separate color for you to easily identify.

ac ed – STREAM_MAGIC – denotes start of serialzed content
00 05 – STREAM_VERSION – serialization version
73 – TC_OBJECT – new Object
72 – TC_CLASSDESC – new Class Descriptor
00 26 – length of the class name
63 6f 6d 2e 6a 61 76 61 70 61 70 65 72 73 2e 73 61 6d 70 6c 65 2e 53 65 72 69 61 6c 69 7a 61 74 69 6f 6e 42 6f 78 – class name
57 fc 83 ca 02 85 f0 18 – SerialVersionUID
02 – this object is serializable
00 01 – count of properties in the serialzed class – one property in our example
42 00 10 – private byte
73 65 72 69 61 6c 69 7a 61 62 6c 65 50 72 6f 70 78 70 – property name – serializableProp in our example
0a – 10 the value – This is the persisted value of the property in our sample

This Core Java tutorial was added on 23/11/2009.

«

»

302 Responses to “Java Serialization”

  1. ken says:

    Thanks for the insight on serialization

  2. Prafulla says:

    Serialization Concept explained nicely. Thanks for Details.

  3. Omar says:

    Simple and easy-to-understand explanation. I liked the use of a broad use tool like notepad++ and the Constant mapping. By the way, in wich class this constans are defined?

  4. Ganesh Bhosale says:

    Excellent technical stuff, i ever came across on Blogs. Looking forward for new subjects

  5. Joe says:

    Omar, have a look at java API:

    http://java.sun.com/j2se/1.4.2/docs/api/java/io/ObjectStreamConstants.html

    it contains java serialization related constants.

  6. Suresh says:

    Thanks so much for the good explanation on serialization

  7. Shadab says:

    Thanks for such a precise and clear understanding.

  8. Arpit says:

    Very neatly explained…!

  9. [...] Also know some fundamentals of serialization. [...]

  10. Sandeep Kumar says:

    Today only I visited this site for the first time and wow..I am in love with its content….very informative indeed. Well its now in my fav list and I have planned to read one topic per day.

    Thanks a lot for creating such a useful blog!!!

  11. Nitin says:

    Hi there,

    Nice Explanation in simple and precise format.
    keep writing :) .

    Cheers
    Nitin.V

  12. Neha J says:

    You made serialization concept just so simple and understandable.

    Thanks and keep such articles coming up!

  13. Srilatha,K says:

    Nice and easily understandable explanation for java serialization. I have never came across this before.

  14. Jill says:

    Good Insight

  15. Sridhar says:

    Very Good Explanation. Its very understandable.Thanks

  16. Brijesh says:

    Nice understanding explanation..

    Thanks a lot

  17. Suwarna says:

    Hi

    Thanks the detail explanation.

    Regards,
    Suwarna

  18. Anand Garlapati says:

    Hi,
    It is very good material on serialization. But i have one doubt.

    In EJB we have ejbActivate() and ejbPassivate() methods. In CMP beans the container will serialize the object in ejbActivate() and deserialize in ejbPassivate() methods. Here we are not tranporting the objects via streams to other PCs using serialization protocol. Please explain me in the context of EJB serialization and deserialization?

    Thanks

    Anand Garlapati.

  19. divya says:

    Thanks for giving me this type of information.
    This is a very nice and easy to understande.

  20. Usman says:

    Good information.
    Thanks

  21. Akhilesh Balakrishnan says:

    You can get more details here

    http://www.javaworld.com/community/node/291
    5

  22. Hi,

    Just to add while writing Serializable class , its good practice to put a Seriazlizable alert in file so that when some one else add a new field in the class he must ensure that field is either transient or Serializable , so that Serializability of class should not break.

    Thanks
    Javin

  23. Shampa says:

    Thanks 4 clearing my serialization concept.

  24. [...] serialization, single instance contract of the singleton pattern can be violated. You can serialize and [...]

  25. Prahlad Gupta says:

    Explained very nicely and each line has clear message………….

  26. vidhi says:

    Nice to see detail description,it helps alot to understand internal details.

    Please keep posting such a nice blogs.

    -Vidhi

  27. [...] 使用序列化,单例模式与单例模式之间存在冲突。你可以序列化然后反序列化来获取新的相同的单例模式的类的实例。使用Java API,你可以实现如下的方法并从流中读取来覆盖实例。你可以确保总是有一个唯一的实例。 [...]

  28. Anonymous says:

    Really good knowledge i got on java serialization

    Thanks
    Prasanna

  29. Akshata says:

    Explained in a very Simple Manner.
    Thank You.

  30. Anji says:

    Great Blog!!!!!Nice job Done Joe:)

  31. Madhukar Gunda says:

    Its very nice artice , but please cover the Serialization UID concept indetail.

  32. anji says:

    good knowledge i got on java serialization, but please trasiant varible concept indetails.

  33. sridip says:

    WOW…..SUPERB GOOD JOB DUDE…Continue with super stuff

  34. swathi says:

    Can i serialise any type of data,means i want to serialise print preview.is it possible???????

  35. sha says:

    The explanation is very simple and clear. Thanks.

  36. Anonymous says:

    very nice stuffs :)
    beautiful way of presenting :)
    Thank you very much :)
    Sandeep

  37. Bharath narla says:

    Great Thanks Joseph :-)

  38. Jitendra Gupta says:

    Its very nice artice , but please cover the Serialization whole concept in detail

  39. Mayank Modi says:

    Nice Article. Explained in simple manner.

  40. Gourav says:

    Can you explain the Serialization using Externalizable interface?

    thanks in advance.

  41. Jagadish.K says:

    Serialization Concept has been explained in a simple but easily understandable manner….
    Its really cool…

  42. Sakthi Manoj says:

    Thank u for ur answer….!:-)

  43. Ashok Kumar says:

    Very Knowledge full about Serialization

  44. govardhan says:

    nice one,it is very easy to understand…
    Thanks

  45. Neha T says:

    Very nicely explained.
    Good blog.

    Thanks
    Neha T

  46. sonal says:

    very nice… at last found a good website 4 java learning

  47. sonal says:

    can we implement Serialization on images…
    basically i want image to be converted in binary form..
    pls reply

  48. Ashish jain says:

    easy way to learn from this site……?

  49. Ashish Gokhale says:

    very nice discription
    thamks alit!!!!!!!!!!!!!!!!!

  50. Nagraj says:

    Thanks for providing such tough topic in an easiest way…..

  51. wudeng says:

    very helpful, thanks.

  52. Eman Zaman says:

    Hi
    Thanks for such a great post….

  53. muthu says:

    Very nice. Above contents are helpful to all.

    Thanks for such a great work.

    Could you please add more examples like serializing images or Resultset,It will be more helpful

  54. jnana says:

    i could not understand
    “serialization”

  55. sathish says:

    something good in this………

  56. Basavaraj says:

    Excellent creativity.

  57. RAJ says:

    SIR AWESOME CODE AND EXCELLENT AND STUDENTS ARE EXACTLY IMPROOVING THERE KNOWLEDGE AUTOMATICALLY BY READ THIS CONCEPT

    THANKING YOU SIR ,

  58. santhosh says:

    Hi this is good

  59. sumit says:

    thanks to this site develpers

  60. John says:

    Can you give some explanation about SerialVersionUID in serialization

  61. I appreciated it.It is very nice explanation.

  62. sir I want to some easy example of file handling,java bean,and networking.I need must.
    thank u sir

  63. Ramkrishna says:

    it is a good material for serialization….

    easily understandable

  64. azaz ahmed says:

    Thnks!!!

  65. this is very good nodes

  66. Anonymous says:

    Thanks a lot .I came to know a lot about SERIALIZATION .

  67. [...] Construction in Serialization 11/12/2011My previous article on exploring java serialization is a box office hit. In continuation to that and popular request, I am going to write on how [...]

  68. Guna says:

    Nice job……….
    Thank a lot….

  69. Praveen says:

    Kuddos to ur explanation

  70. karan says:

    awesome yaar………
    got to know something new and real helpful
    and easy to unerstand..

    thnx…

    keep it up…..

  71. biswajit says:

    nice…

  72. [...] have seen enough about using the default protocol to implement serialization and how instances are created during serialization. In this current article we shall see about [...]

  73. Dinesh says:

    Please tell me the difference between serialization, transcient and clonable?.

  74. muthu says:

    This is awesome. I am very much clear about serialization

  75. rajeshwar says:

    Nicely Explained. Good work dude….
    Keep Posting different Topics On java.
    thx

  76. Swaminathan says:

    Really nice explanation……….

  77. abhijit says:

    hey really nice blog… keep it up
    very good explanation
    thank u….

  78. mazhar says:

    please tell how to serialize object in xml

  79. mazhar says:

    thanks to make us understand.
    please tell how we use xml in serialization.
    and how we convert object to xml form.

  80. Harish says:

    Excellent Material.

  81. [...] is an interface that enables you to define custom rules and your own mechanism for serialization. Serializable defines standard protocol and provides out of the box serialization [...]

  82. rahul says:

    Hi Joe , can you explain why strings are immutable in java???

  83. SuresHK says:

    awesome Tutorial for Serialization

  84. Joe says:

    @rahul have a look at java string

  85. Anonymous says:

    Very neat and clear explanation which never read.

  86. Sunil Kumar says:

    its very nice def….

  87. Sunil Kumar Maghar says:

    Hi,
    This is very helpful example….

    Thanks
    Sunil Kumar

  88. prakash says:

    Good

  89. Nice way of presentation.

    I have a question regarding de-serialization.
    First you serialize a object SerializationBox and write it to a file outfile.ser. On a different JVM i take the outfile.ser file and try to deserialize it using readObject() but i get java.lang.ClassNotFoundException as there is no class file sent.

    How does it reconstruct the object and type cast to the SerializationBox object?

    I know the file contains Class information as shown in the hex-format. but how do you write code to use readObject and typecast to the serialized object.

    SerializationBox reconstructedSBX = SerializationBox ois.readObject();

  90. Anonymous says:

    toooooooooooooo good

  91. Anonymous says:

    Excellent work Joe!!
    - Shyam :)

  92. Anonymous says:

    Thanks..Very Helpfull document..

  93. Anonymous says:

    Thank you, it was good and very helpfull…

  94. ganesh says:

    nice blog

  95. ganesh says:

    i have a small doubt:

    1)difference between creating a thread by extending Thread class and by implementing Runnable interface? Which one should prefer?

    please help me

  96. Anonymous says:

    Hi Ganesh,

    I as know we should prefer implementing Runnable always as you don’t need to create multiple abject of your class to create multiple threads when required.

    There may be other uses/advantages of it.

  97. sapan says:

    If we save the object state in a file in one system, then how we will get back the same state in another system to rebuild the object from the same state

    please answer this properly with detail

  98. Anonymous says:

    Good stuff on java .

  99. emmanuel says:

    if we declare a type as transient how it is not serialized ..pls explain..

  100. Anonymous says:

    Hi,
    Thanks n appreciate your efforts…

  101. Anonymous says:

    Hello,
    This is very nice & easy to understand.

    Thanks for your fantastic efforts.

    Regards,

  102. tushar says:

    thanks sir , great use of hexadecimal values !

  103. Anonymous says:

    Thanks joe

  104. Anonymous says:

    thanks sir…i m confused with serializable topic…now i understood a lot by ur explanation……

    Narayan Rao

  105. vinod says:

    Good Explanations
    thanks

  106. srini says:

    Hi Joe,

    Its nice blog. explanation is very good.

    thanks
    srini

  107. pinky says:

    Thnx for easy representation…..

    From:pinky maher
    April 02;2012

  108. Sumit Desai says:

    Thanks
    Very nice explanation!!!

  109. Shazz says:

    Wonderful.. thank you Sir please keep on writing.
    I am waiting for your more blogs.
    thanks a lot!!

  110. shiva panchal says:

    I was little confused before but as per your explaination it is now clear for me.

    Thanks!!!!!

  111. Sakthi says:

    Nice representation of serialized object will look like. Thanks.

  112. Chintan says:

    Hi Joe,
    Awesome Tutorial on Serialization.
    I never see the easiest tutorial like yours.

    Thanks
    Chintan

  113. santhosh d.k says:

    Good Explaination.

  114. sunil says:

    thanks for a deep explanation .it really necessary for all java developers.
    thanks a lot.

  115. Eugene says:

    Thanx for the good article. It helped me a lot. But there are some errors in bytecode:

    42 is `B` which means byte (not a private),
    00 10 73 65 72 69 61 6c 69 7a 61 62 6c 65 50 72 6f 70 – property name `serializableProp` in modified UTF-8
    78 – TC_ENDBLOCKDATA – classAnnotation (empty, no annotations)
    70 – TC_NULL – superClassDesc (superclass is Object)

  116. Pawan Bmr says:

    Content is too good but due to Background picture ,content is not visible effectively.
    please change Background pic or change font color and Keep writing..
    ThankYou.

  117. sudarshan says:

    hey thanks for deep dive in serialization…

  118. chandan kumar gupta says:

    this is very good Example and very helpful
    thanks to make me understood about java serialization…….

  119. pavan_krishna says:

    awesome explanation keep adding more…..
    i dint find such a clear explanation in any other sites

    Regards,
    pavan

  120. Anonymous says:

    Why do we use the serial version UID

  121. Arshad Shaikh says:

    Very Nice Article. Concept is explained in simple manner……….. Thanks a lot Bro

  122. [...] java we have been passing information to compiler for long. For example take serialization, we have the keyword transient to tell that this field is not serializable. Now instead of having [...]

  123. Kapil says:

    Nice example :) Keep it up ….

  124. Lakhan says:

    Well explained :)

  125. Anonymous says:

    THANKS A LOT FOR DEEP EXPLANATION :-)

  126. Anonymous says:

    Well explained

  127. Anonymous says:

    well explained :)
    Vikas
    Deloitte.

  128. Samira says:

    thanks alot.
    very well explained

  129. Dimit says:

    when serialization should be avoided… Is it cost effective?

  130. mani kumar says:

    Very Good to learn in a simple way…
    Thanks Joe…

  131. Kumar Sundaram says:

    The beauty of your writting is that you write in a very simple and clear manner…

    always a pleasure reading you..

    Thankx a ton Joe

  132. aaaaaaa says:

    The beauty of your writting is that you write in a very simple and clear manner…

    always a pleasure reading you..

    Thankx a ton Joe

  133. great articles on java ..thanks

  134. Egyptian Man says:

    Great
    Thanks

  135. deepak says:

    thanks

  136. Anonymous says:

    thanku so much

  137. Anonymous says:

    great…………..

  138. Anonymous says:

    .

  139. Anonymous says:

    insert java values(’1′,’
    Java Interview Questions

    With the notable increase in jobs that involve extensive use of Java it certainly is worth devoting an entire section to this programming language. Of course, this is not a complete and thorough guide to Java, so some basic knowledge of Java is assumed. What’s being presented here are some salient questions that cover a broad range of topics in Java.

    Unless you are interviewing for a position that involves extensive use of Java, you generally won’t be asked Java-related questions. But if you know that the position requires at least some Java skills, you will definitely want to read this section.

    ‘)

  140. Anonymous says:

    sorry joe i was trying to make how to create comment box ..so i have done this non sense

  141. Anonymous says:

    good explaination

  142. Anonymous says:

    Just Superb

  143. Azhagumuthu G says:

    Simple, understandable and clear.
    Thanks

  144. Anonymous says:

    very well explained

  145. Anonymous says:

    can you please add serialVersionUID importance?

  146. Sahaya says:

    Great explanation Joe!kudos:-)

  147. krihsna says:

    thanx its easy way to learn

  148. Uncle I am a Project Manager and you have made very good example. Can I meet you personally?

  149. Sonam says:

    easy to understand.

  150. Udhayakumar G K says:

    Thanks. I was exactly looking for this.

    Thanks,
    http://saijava.blogspot.in/

  151. Mohd Ali says:

    Thanks, it is good explanation ..

  152. Anonymous says:

    simple and superb

  153. Anonymous says:

    Hi Joe,
    I have some doubt…
    suppose I have a class that implements Serializable interface. Inside the class I don’t writes the code to persisting the object state like in your code

    public static void serialize(String outFile, Object serializableObject)
    throws IOException {
    FileOutputStream fos = new FileOutputStream(outFile);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(serializableObject);
    }

    public static Object deSerialize(String serilizedObject)
    throws FileNotFoundException, IOException, ClassNotFoundException {
    FileInputStream fis = new FileInputStream(serilizedObject);
    ObjectInputStream ois = new ObjectInputStream(fis);
    return ois.readObject();
    }

    So, my questions is, with the above scenario, is this a valid implementation of serialization? if Yes, then how JVM persist the state of object?

  154. Anonymous says:

    Thank u.explained in simple words,easy to understand

  155. Udhayakumar G K says:

    nice to understand.

    Thanks,
    Udhayakumar G K
    http://phppapers.blogspot.com

  156. ashwin says:

    from now on i became a fan of you .

  157. anupriya says:

    nice blog…very helpful….thnx..

    will u plz enlighten us on 1 more point..
    y serializable interface is used though it dont hav ny methods?????

  158. Sachin Raghav says:

    Thanks for giving the detail of Serialization.i have better understand the serialization through your tutorial.but what is marker interface?Explain briefly.
    Please reply me………….

  159. Preethi says:

    Thanks for your neat and clean explanation !

  160. Ayan Ray says:

    Thanks for the brief explanation.Can u help me siving some information on Struts 2?

    Thanks ,

    Ayan Ray

  161. Anonymous says:

    this is really useful .way of presentation is so nice.

    Thanks,
    Pavan

  162. sumalatha says:

    This is really useful for me..
    and the explanation is excellent .
    Thanks
    Sumalatha

  163. Anonymous says:

    great work bro….

  164. Neethu says:

    Hi,

    Thanks for good explanation.Has explained in depth.

  165. malli says:

    can you explain where serialization can useful in web application?

  166. abdul arif says:

    first time reading dis block nice expalnation.i have a doubt a class dat implements a serailized and class members are serialized. in the above example ssn is not serialized then how ssn variable sent into stream. plz send the answer to my mail abdularif09@gmail.com

  167. Yesudas S says:

    Very neat and Clearn explanations.
    Good Job.
    Adding other benefits of serialization would be better.

  168. monika says:

    very well explained

  169. Divya says:

    Great!!!!!!! Explanations are clear and simple

  170. twinkle says:

    are all the functions of java implicitly virtual????

  171. Anonymous says:

    wow…now,its very easy for me to explain in my exam.. thanxx Joe……

    -Pramit(9723916656)

  172. Anonymous says:

    very nice explanation so far i have surfed over. Thanks a lot.

    -Rajasekhar

  173. Prasad says:

    simply superb!!!

  174. raju says:

    sir i have one doubt
    which action java platform restrict on applet?

  175. ramya says:

    thankyou!
    feeling easy now..

  176. sivakumar says:

    hi
    without implements Serializable i can able to write and read the object in standalone as well as in network using ObjectOutputStream and ObjectInputStream. Please explain, is it must to implements Serializable interface. waiting for your reply.

  177. sivakumar says:

    hi,
    Sorry to ask previous question.i Serializable the arrayList and vector objects.so i confused, now only saw that the both original class implements Serializable..

  178. Sandeep says:

    Thanks Joe.

  179. Anonymous says:

    Thanks for such a clear understanding of serialization….I am really impressed by the contents of ur website.hats off man…

  180. Jeevan says:

    Hi,

    Thanks & nice to see good work,

    Its very much useful

    Regards,
    Jeevan

  181. Amit says:

    Hi…
    I hav a doubt..can we serialize a object without any property ie A class without any property?
    Ex–
    class A implements Serializable{
    }
    Class Test{
    public static void main(String ag[]){
    —-code for serialzation of class A–
    }}
    Can it will serialize?

  182. Pankaj Sinha says:

    Hi,
    Thanks a lot for providing such good technical stuff.

  183. abdul basith says:

    very very nice example

  184. Srikanth says:

    Wow.. What a presentation JOE.

    Real good work. Hope to see other topics as well..!!

  185. Arti says:

    Amazing explanation.. Thanks

  186. Abhijit R says:

    Hi Joe,

    Nice articles, reading continously from 2 hours,

    Your style of writing article makes it interesting.

    I think ,I am in a new world of java.

    Keep it up .

  187. rupesh says:

    compact and very good artical.

  188. Anonymous says:

    1 Question:
    If we serialize a object in one JDK version and try to deserialize it in different JDK version; it is get deserialized?

  189. kalai says:

    its too good and brief explanation
    thanks

  190. M.ATIF AZIZ says:

    its complete and brief explanation
    THANKS

  191. M.ATIF AZIZ says:

    its complete and brief
    thanks

  192. Lekshmana Perumal says:

    very useful and i’m understand the concepts very clearly…. nice e.g

  193. Rasheed says:

    Thanks for Great work..Very Helpfull.

  194. DK says:

    VERY GD ARTCLE ON SERIALIZATION.

  195. sk says:

    Thanks!!

  196. Hi,
    Excellent things & effort

  197. NIZAM DEN says:

    Today only I have entered this site for the first time and fantastic..
    Thanks a lot for creating such a useful blog!!! please Keep update future….

  198. Anonymous says:

    Hi,
    Really good.

  199. You should also mention that upon deserialization if the compiler finds the class missing/unreachable for the serialized object, it’ll throw an Exception. It becomes the responsibility of the deserializing code to include the appropriately required classes.

  200. Sima raj says:

    Wow sir really dis is very helpful 4 me thanksssss a lot sir…..

  201. Pankaj says:

    It’s very easy to understand and clears detail concepts about serialization.
    Thanx!

  202. suresh says:

    its really good, but what is the exact use of serialization

  203. Ayaskant says:

    All of your posts are very good. They are easy to understand & very clearly explained from a novice point of view. Please keep posting such topics related to Java.

  204. Milind says:

    suppose there are 2 User A and B, if A impliments serialization in one java class(means writting instance variable on socket and passing it to another side) and pass it over the network and User B sends one java class instance variable using socket to another side without serializing its class
    now at recevier side User C is receving data so what ADVANTAGE will get to User C when it recevies data from User A

  205. satish says:

    thankQ for giving nice tutorial

  206. Utpal says:

    Thanks for such a nice explanation about serialization..

  207. kumar says:

    there is no methods and no fields in serializable interface.how can store a state of an object.
    please explain i am confuse.

  208. Samba says:

    Nice explanation on serialization.

  209. Anonymous says:

    Good work joe, we heartily appreciate this. :)

  210. jagan says:

    Nice tutorial., keep doing the good work..,

  211. Anonymous says:

    Very nice tutorial..
    I used to go through your blog before my interview,. Thank you so much for explaining clearly,.. Great Work,.. Keep going

  212. Anonymous says:

    very good to have a site like this to understand the java concepts in very simple and clear way . thanks to blog owner

  213. Jai Andhra says:

    Aree joe anna…mast cheppivanee conceptuu…ne article kiraak unnai anna…gitlanee ee blog continue cheyi…

  214. vinoth says:

    wow..what an explanation about serilalization..u made it easy..

  215. Anonymous says:

    can u plz tell me the exact difference between wildcard and bounded variable in collections….

  216. Anonymous says:

    nice…very usefull

  217. Anonymous says:

    nice…very usefull

  218. Kalyan Roy says:

    Your explanations help me a lot…
    Thanks and keep writing…

  219. Nirmal says:

    Hi,

    The above description and code snippet of Serialization was really helpful to me.

    I had a quick question on this. When we serialize an object, is it creating a new instance of the object or creating a copy of it?

  220. Anuj says:

    Hi,

    very nice.
    I am fighting years to learn serialization. Now I understood.

    I have a question. Serlization makes Object heavy, Why all hibernate entities are considered as Serializable.

  221. Muniraj says:

    Nice tutorial joe..Thanks a lot….

  222. Mangesh Lule says:

    Nice Tutorial. Now got what serialization means.

  223. mayuri says:

    Hey thats really very very nice explaination , plz tell me that in this example why did not we implement marker interface ?

  224. Nice way of representation. Thanks !!!!!!! says:

    Nice way of representation. Thanks !!!!!!!

  225. chaitanya says:

    thank you very much

  226. abhay agarwal says:

    excellent article – liked the usage of hex plugin of Notepad++

  227. deepak sai says:

    hi, when will we use the serialization and the object output stream.. what will be the difference when i use the object output stream instead of the serialization.

  228. Moulika Thirumalasetty says:

    This concept is good..
    But how to serializa and deserialize an image is it the same way as the above..

  229. satheesh says:

    Nice way of presentation.

  230. Anonymous says:

    nice

  231. Siva says:

    Hey,

    I have understood the Serialization and deSerialization how does internally works in java.

    Thanks for explaining the core stuff.

    I have one doubt that is eating my head.

    I am holding an ArrayList . I would not like to serialize the 3 rd element from an my ArrayList. How to do that?

    List li = new ArrayList();

    li.add(“one”);
    li.add(“two”);
    li.add(“three”);

    Could tell me.

    Thanks,
    -Siva

    • Sai says:

      Hi Shiva,
      You can declare some String literal for third element and declare it as transient.

      Ex:
      transient String third_ele = “three”;

      Hope this works :)

  232. Sameer says:

    Nice article Joe

  233. vivek says:

    Thanx for such a nice article.. good luck

  234. Sai says:

    Very good article Joe. I know what exactly serialization is. But, as a programmer, I was always interested to see the serialization file and it’s format and header and stuff. This blog is really good and informative. Keep up the good work :)

  235. Anonymous says:

    very nice….thanx..!!

  236. Anonymous says:

    good explanation fro serialization .Very nice thanx.

  237. Anonymous says:

    Ultimate Explanation

  238. viswanath says:

    Thanks alot for brief explanation.

  239. Gopa says:

    awsome. [One word gives everything]

  240. Java Binary says:

    [...] java class in above format, the same way as we did while understanding the serialized object using java serialization. Ads by [...]

  241. [...] Serialization of non-static inner class has an issue. The outer class will also get serialized. Because the inner class has got a reference to the outer class and it is implicit. Since it is implicit, it cannot be marked as transient. This issue is also applicable for double brace initialization. [...]

  242. Riyaz says:

    nice tutorial….

  243. Swapnil Joshi says:

    It would be nice to have a subtopic on readObject() and writeObject() methods from ObjectInputStream and ObjectOutputStream. Without that the topic can not be complete.

  244. anu says:

    Nicely explained the concept :)

  245. uday says:

    Sir,

    Your concepts are really super.
    I have one doubt about serialization.
    Why we need to serialize object?
    When we use in real time?
    Please answer.

  246. Rohit says:

    Can you please Explain how can we append an objects to a file which already contains some objects… and i want to read all objects
    it gives an StreamCorrupted Exception ..when i try to read an objects i recently appended……

  247. Anurag says:

    WOW…

  248. Anurag says:

    the hex file description at the end was awesome

  249. Anupam says:

    Excellant explanation!

  250. rajan says:

    nicely explained

  251. Vinaya says:

    I had never understood Serilaization this better

  252. Kumar Bhatia says:

    Introduced new blog on java.
    javacodeimpl.blogspot.com

    Keep visiting!!!

  253. abid says:

    thanks sir

  254. Sunitha says:

    Nice explanation. Simple & easy to understand.

  255. Shash says:

    Never came across such detailed explanation of Serialization. Thanks for sharing. Awesome blog.

  256. Nitin Shelke says:

    Only one world for this blog is Excellent..!!!!!!!!!!!!!!!!
    :)
    Keep Writing ….

  257. Anonymous says:

    Coool helped me a lot…

  258. Kumar Bhatia says:

    Hi.ur explanation of java serialization is a copy of http://stackoverflow.com/questions/608647/what-is-serialization-in-java this link.
    M not saying who copied whom…just for your info..if some one copied from your blog…u can make ur blog copy paste free..

  259. Chennu says:

    I have a strange question for you. What is the need for sending the object over the network. Why we need to send. Can you please explain with an example or rough design

  260. Naveen says:

    Super joe, Nice and very very good article

  261. ANBU says:

    very useful explanation sir,

    thanks…

  262. Anonymous says:

    Very good explanation.

    Thanks

  263. Santhosh Urumese says:

    Good explanantion..Thank You

  264. Jeevan Ramamoorthy says:

    Thank you Mr.Joe your explanation was really good!

  265. sandhya Rani kalva says:

    it is really very useful……Thank You

  266. Gopinath says:

    Great work Joe:)very useful..

  267. MrBCut says:

    whoa! mind = blown!

    thanks for this example friend :)

  268. Anonymous says:

    When i compile the code which you have given am getting the output as 10. I thought the object was deserialized. But if i comment the method deserialize and execute the above method , it is returning as 10. please clarify Joe for my below code,i would like to serilaze the object
    SerializationBox serialB = new SerializationBox();
    serialize(“serial.out”, serialB);
    // SerializationBox sb = (SerializationBox) deSerialize(“serial.out”);
    // System.out.println(sb.getSerializableProp());
    System.out.println(serialB.getSerializableProp());

  269. Mini says:

    It is said that static fields cannot be serialized.
    public class SerializableExample implements Serializable{

    private static Integer staticInteger = new Integer(0);

    public static void main(String[] args) {
    SerializableExample example = new SerializableExample();
    example.setStaticInteger(20);
    FileOutputStream fileOutputStream;
    try {
    File file = new File(“/tmp/test.out”);
    fileOutputStream = new FileOutputStream(“/tmp/test.out”);
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
    objectOutputStream.writeObject(example);

    FileInputStream fileInputStream = new FileInputStream(“/tmp/test.out”);

    ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
    SerializableExample serializableExample1 = (SerializableExample) objectInputStream.readObject();
    System.out.println(serializableExample1.getStaticInteger());
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    public static Integer getStaticInteger() {
    return staticInteger;
    }

    public static void setStaticInteger(Integer staticInteger) {
    SerializableExample.staticInteger = staticInteger;
    }
    }

    The above program should have returned 0 . But it returns 20.

    • Pavan says:

      you are performing both serialization and deserialization on same class.As Static variables are class variable the value is still 20.try deserialization in other class

  270. sachin says:

    sir,
    I want to dump for OCJP.

  271. Thanks for the simple tutorial – Java serialization.
    i was searched many sites, but finally i understood what is Java serialization.

  272. Anoop says:

    Great article…got a clear idea..thanx

  273. Kofi says:

    Clear and concise.Thank you.

  274. Sandeep k says:

    Hi Sir,
    Thanks for explaining Java Serialization in such a nice descriptive way. I really admire the way you present the topics in this blog. Thanks again. Awaiting more concepts and tutorials :)

  275. Anonymous says:

    if any sub class implements serializable but super class is not implements then the object will be serialized?

    • Anonymous says:

      if any sub class implements serializable but super class is not implements then the object will be serialized?
      And when it gives error if super class not implements serializable

  276. Sivakumar says:

    Hi Joe,

    In my understanding, an object is an entity which hold the reference of memory.If so, how the object from one JVM to another JVM works?

    Please clarify me on this.

    Regards,
    Sivakumar.

  277. Baskar says:

    you have explained Serialization in depth and it is understandable. Thanks for the information

  278. […] cyclic dependencies. If you don’t want to implement deep copy yourselves then you can go for serialization. It does implements deep copy implicitly and gracefully handling cyclic dependencies. Ads by Google […]

  279. Enjoy says:

    Thanks for the simple tutorial – Java serialization.
    i was searched many sites, but finally i understood what is Java serialization.

    http://www.firstbloggertricks.com

  280. Rajkumar says:

    you explained what and how? can you also explain why we need Serialization? i came across in the internet about to maintain state of the object. what is exactly state?

    • Anonymous says:

      State is nothing but the values stored in member variables of a class. Class has two things state and behavior, State is nothing but member variables and Behavior are the member functions of a class. For example consider a Employee class where states/variables will be name, age, id etc., whereas doWork(), applyLeave() will be behavior of the class.

  281. SRam says:

    This explanation is very good. Simple terms and easy to understand

  282. Aman says:

    Hi sir,

    Can we keep our subclass non-serialized when the super class is serializable ?
    Please let me know.
    Thanks in advance.
    Regards
    Aman :)

  283. Pavan says:

    Is it ok if the class has more fields than the class on deserialization side…?

  284. Karthikeyan says:

    Good teaching sir. But I have a doubt. Can you explain why we need to implement serializable interface as we are not creating any bond? Can you please explain what we achieve by implementing serializable interface.

  285. sabiha says:

    EXCELLENT

Leave a Reply