{"id":1468,"date":"2017-03-21T17:18:27","date_gmt":"2017-03-21T11:48:27","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=1468"},"modified":"2017-03-29T11:01:31","modified_gmt":"2017-03-29T05:31:31","slug":"java-serialversionuid-use","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-serialversionuid-use\/","title":{"rendered":"JAVA &#8211; What is a serialVersionUID and why should I use it"},"content":{"rendered":"<p><span style=\"color: #ff6600;\"><b>SERIALIZATION:<\/b><\/span><\/p>\n<ul>\n<li>To\u00a0<b>serialize<\/b>an object means to convert its state to a byte stream so that the byte stream can be returned back into a copy of the object.<\/li>\n<li>A\u00a0<b>Java<\/b>object is\u00a0<b>serializable <\/b>if its class or any of its super classes implements either the\u00a0<b>java<\/b>.io.<b>Serializable<\/b> interface or its subinterface,\u00a0<b>java<\/b>.io.Externalizable.<\/li>\n<\/ul>\n<p><span style=\"color: #008000;\"><b>DESERIALIZATION:<\/b><\/span><\/p>\n<ul>\n<li>The reverse process of creating object from sequence of bytes is called\u00a0<b>deserialization<\/b>.<\/li>\n<li>A class must implement Serializable interface present in\u00a0<b>java<\/b>.io package in order to serialize its object successfully.<\/li>\n<li>Serializable is a marker interface that adds serializable behavior to the class implementing it.<\/li>\n<\/ul>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\" wp-image-1469 aligncenter\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/03\/ol-300x139.png\" alt=\"\" width=\"509\" height=\"236\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/03\/ol-300x139.png 300w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/03\/ol.png 620w\" sizes=\"(max-width: 509px) 100vw, 509px\" \/><\/p>\n<h4 id=\"uses-of-serialization-and-deserialization-in-java\"><span style=\"color: #000000;\"><b>Uses of serialization and Deserialization in Java<\/b><b>:<\/b><\/span><\/h4>\n<h4 id=\"serialization-and-deserialization-in-java\"><span style=\"color: #000000;\"><strong>Serialization and Deserialization in Java.\u00a0<\/strong><\/span><\/h4>\n<ul>\n<li><b>Serialization<\/b>is a process of converting an object into a sequence of bytes which can be persisted to a disk or database or can be sent through streams.<\/li>\n<li>The reverse process of creating object from sequence of bytes is called\u00a0<b>deserialization<\/b>.<\/li>\n<\/ul>\n[ad type=&#8221;banner&#8221;]\n<h4 id=\"serialversionuid\"><span style=\"color: #000000;\"><b>serialVersionUID:\u00a0<\/b><\/span><\/h4>\n<ul>\n<li>The serialization runtime associates with each serializable class a version number, called a\u00a0serialVersionUID, which is\u00a0used\u00a0during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.<\/li>\n<li>The serialVersionUID is used as a version control in a Serializable class.<\/li>\n<li>If we do not explicitly declare a serialVersionUID, JVM will do it automatically, based on various aspects of our Serializable class.<\/li>\n<li>Defining a\u00a0serialVersionUID\u00a0field\u00a0in serializable class is\u00a0not mandatory.<\/li>\n<li>If a serializable class has an explicit\u00a0serialVersionUID\u00a0then this field should be of type\u00a0long\u00a0and must be static and final. If there is no\u00a0serialVersionUID\u00a0field\u00a0defined explicitly then serialization runtime will calculate default value for that class. The value can vary based on compiler implementation.<\/li>\n<li>It is advised to use private access modifier for\u00a0serialVersionUID.<\/li>\n<li>Different class can have same\u00a0serialVersionUID.<\/li>\n<li>Array classes cannot declare an explicit serialVersionUID, so they always have the default computed value, but the requirement for matching serialVersionUID values is ignored for array classes.<\/li>\n<li>If there is a difference between serialVersionUID of loaded receiver class and corresponding sender class then\u00a0InvalidClassException\u00a0will be thrown.<\/li>\n<li>we should use different\u00a0serialVersionUID\u00a0for different version of \u00a0same class if we want to forbid serialization of new class with old version of same class.<\/li>\n<\/ul>\n<h4 id=\"serialversionuid-example\"><span style=\"color: #000000;\"><b>SerialVersionUID Example<\/b><\/span><\/h4>\n<ul>\n<li>\u00a0Let start an example to understand how Serializable class use SerialVersionUID to implement version control.<\/li>\n<\/ul>\n<h4 id=\"employee-java\"><span style=\"color: #000000;\"><b>Employee.java<\/b><\/span><\/h4>\n<ul>\n<li>A serializable class with a serialVersionUID of 1L.<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">import java.io.Serializable;<br\/><br\/>public class Employee implements Serializable<br\/>{<br\/><br\/>\t   private static final long serialVersionUID = 1L;<br\/><br\/>\t   String name;<br\/>\t   String age;<br\/><br\/>\t   public void setName(String name)<br\/>{<br\/>\t\t   this.name = name;<br\/>}<br\/>public void setAge(String age)<br\/>{<br\/>\t\t   this.age = age;<br\/> }<br\/><br\/>\t   public String getName()<br\/>{<br\/>\t\t   return this.name;<br\/> }<br\/><br\/>\t   public String getAge()<br\/>{<br\/>\t\t   return this.age;<br\/> }<br\/><br\/>\t   @Override<br\/>\t   public String toString() <br\/>{<br\/>    \t   return new StringBuffer(&quot; Name : &quot;)<br\/>    \t   .append(this.name)<br\/>    \t   .append(&quot; Age : &quot;)<br\/>    \t   .append(this.age).toString();<br\/> }<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<h4 id=\"writeobject-java\"><span style=\"color: #000000;\"><b>WriteObject.java<\/b><\/span><\/h4>\n<ul>\n<li>A simple class to write \/ serialize the Employee object into a file \u2013 \u201cc:\\\\employee.ser\u201d<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">import java.io.FileOutputStream;<br\/>import java.io.ObjectOutputStream;<br\/><br\/>public class WriteObject<br\/>{<br\/><br\/>\tpublic static void main (String args[]) <br\/>{<br\/><br\/>\t   Employee employee = new Employee();<br\/>\t   employee.setName(\u201cWikitechy&quot;);<br\/>\t   employee.setAge(\u201c25&quot;);<br\/><br\/>\t   try<br\/>{<br\/>FileOutputStream fout = new FileOutputStream(&quot;c:\\\\employee.ser&quot;);<br\/>ObjectOutputStream oos = new ObjectOutputStream(fout);<br\/>oos.writeObject(employee);<br\/>\t\toos.close();<br\/>\t\tSystem.out.println(&quot;Done&quot;);<br\/><br\/>}catch(Exception ex)<br\/>{<br\/>\t\t   ex.printStackTrace();<br\/> }<br\/>}<br\/>}<\/code><\/pre> <\/div>\n<h4 id=\"readobject-java\"><span style=\"color: #000000;\"><b>ReadObject.java<\/b><\/span><\/h4>\n<ul>\n<li>A simple class to read \/ deserialize the Employee object from file \u2013 \u201cc:\\\\employee.ser\u201d.<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">import java.io.FileInputStream;<br\/>import java.io.ObjectInputStream;<br\/><br\/>public class ReadObject<br\/>{<br\/>public static void main (String args[]) {<br\/><br\/>\t   Employee employee;<br\/><br\/> try<br\/>{<br\/><br\/>\t\t   FileInputStream fin = new FileInputStream(&quot;c:\\\\employee.ser&quot;);<br\/>\t\t   ObjectInputStream ois = new ObjectInputStream(fin);<br\/>\t\t   employee = (Employee) ois.readObject();<br\/>\t\t   ois.close();<br\/><br\/>\t\t   System.out.println(employee);<br\/><br\/> }catch(Exception ex)<br\/>{<br\/>\t\t   ex.printStackTrace();<br\/>}<br\/>}<br\/>}<\/code><\/pre> <\/div>\n<h4 id=\"output\"><span style=\"color: #000000;\"><b>Output:<\/b><\/span><\/h4>\n<p><strong>Name : Wikitechy Age : 25<\/strong><\/p>\n<h4 id=\"default-serialversionuid\"><span style=\"color: #000000;\"><b>D<\/b><b>efault serialVersionUID<\/b><\/span><\/h4>\n<ul>\n<li>\u00a0If no serialVersionUID is declared, JVM will use its own algorithm to generate a default SerialVersionUID.<\/li>\n<li>The default serialVersionUID computation is highly sensitive to class details and may vary from different JVM implementation, and result in an unexpected InvalidClassExceptions during the deserialization process.<\/li>\n<\/ul>\n<h4 id=\"how-to-generate-serialversionuid\"><span style=\"color: #000000;\"><b>How to generate serialVersionUID<\/b><\/span><\/h4>\n<ul>\n<li>we can use JDK \u201cserialver\u201d or Eclipse IDE to generate serialVersionUID automatically<\/li>\n<\/ul>\n<h4 id=\"example\">Example:<\/h4>\n<ul>\n<li>It is easy to understand the exact use of the variable.<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">package com.jbt;<br\/> <br\/>import java.io.Serializable;<br\/> <br\/>public class Employee implements Serializable<br\/>{<br\/>   public String firstName;<br\/>   public String lastName;<br\/>   private static final long serialVersionUID = 5462223600l;<br\/>}<br\/> <\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<h4 id=\"serializaitonclass-java-this-class-will-be-used-to-serialize\"><span style=\"color: #000000;\"><b>SerializaitonClass.java (This class will be used to serialize)<\/b><\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">package com.jbt;<br\/> <br\/>import java.io.FileOutputStream;<br\/>import java.io.IOException;<br\/>import java.io.ObjectOutputStream;<br\/>public class SerializaitonClass {<br\/> <br\/> public static void main(String[] args) {<br\/> Employee emp = new Employee();<br\/> emp.firstName = &quot;wiki&quot;;<br\/> emp.lastName = &quot;techy&quot;;<br\/> <br\/> try {<br\/> FileOutputStream fileOut = new FileOutputStream(&quot;.\/employee.txt&quot;);<br\/> ObjectOutputStream out = new ObjectOutputStream(fileOut);<br\/> out.writeObject(emp);<br\/> out.close();<br\/> fileOut.close();<br\/> System.out.printf(&quot;Serialized data is saved in .\/employee.txt file&quot;);<br\/> } catch (IOException i) {<br\/> i.printStackTrace();<br\/> }<br\/> }<br\/>}<\/code><\/pre> <\/div>\n<h4 id=\"deserializationclass-java-this-class-will-be-used-to-deserialize\"><span style=\"color: #000000;\"><b>DeserializationClass.java (This class will be used to <\/b><b>deserialize<\/b><b> )<\/b><\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">package com.jbt;<br\/> <br\/>import java.io.*;<br\/> <br\/>public class DeserializationClass <br\/>{<br\/> public static void main(String[] args) <br\/>{<br\/> Employee emp = null;<br\/> try <br\/>{<br\/> FileInputStream fileIn = new FileInputStream(&quot;.\/employee.txt&quot;);<br\/> ObjectInputStream in = new ObjectInputStream(fileIn);<br\/> emp = (Employee) in.readObject();<br\/> in.close();<br\/> fileIn.close();<br\/> } catch (IOException i) <br\/>{<br\/> i.printStackTrace();<br\/> return;<br\/> } catch (ClassNotFoundException c) <br\/>{<br\/>System.out.println(&quot;Employee class not found&quot;);<br\/> c.printStackTrace();<br\/> return;<br\/> }<br\/> System.out.println(&quot;Deserializing Employee...&quot;);<br\/> System.out.println(&quot;First Name of Employee: &quot; + emp.firstName);<br\/> System.out.println(&quot;Last Name of Employee: &quot; + emp.lastName);<br\/> }<br\/>}<br\/> <\/code><\/pre> <\/div>\n<ul>\n<li>Now execute \u201cSerializationClass.java\u201d and then \u201cDeserializationClass.java\u201d. It will first create a file with Employee object\u2019s state and then while de-serialization it creates object from the same file.<\/li>\n<\/ul>\n<h4 id=\"output-2\"><span style=\"color: #000000;\"><b>Output:<\/b><\/span><\/h4>\n<blockquote><p><strong>Serialized data is saved in .\/employee.txt file<\/strong><\/p>\n<p><strong>Deserializing Employee&#8230;<\/strong><\/p>\n<p><strong>First Name of Employee: wiki<\/strong><\/p>\n<p><strong>Last Name of Employee: techy<\/strong><\/p><\/blockquote>\n<ul>\n<li>Remove \u201cserialVersionUID\u201d variable from Employee.java file and again run \u201cSerializationClass.java\u201d\u00a0 file.<\/li>\n<li>It will create \u201cemployee.txt\u201d\u00a0 file again with\u00a0 the object\u2019s state .<\/li>\n<li>Now let\u2019s add a new variable in Employee class\u00a0 suppose\u00a0 String Address.<\/li>\n<\/ul>\n<h4 id=\"employee-java-2\"><span style=\"color: #000000;\"><b>Employee.java<\/b><\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">package com.jbt;<br\/> <br\/>import java.io.Serializable;<br\/> <br\/>public class Employee implements Serializable<br\/>{<br\/>   public String firstName;<br\/>   public String lastName;<br\/>   public String Address;<br\/>   \/\/Variable is commented <br\/>\/\/   private static final long serialVersionUID = 5462223600l;<br\/>}<br\/> <\/code><\/pre> <\/div>\n<p>Now run \u201cDeserializationClass.java\u201d<\/p>\n[ad type=&#8221;banner&#8221;]\n<h4 id=\"output-3\"><span style=\"color: #000000;\">Output:<\/span><\/h4>\n<blockquote><p><strong>java.io.InvalidClassException: com.jbt.Employee; local class incompatible: stream classdesc serialVersionUID = 5462223600, local class serialVersionUID = -3607530122250644586<\/strong><\/p>\n<p><strong>at java.io.ObjectStreamClass.initNonProxy(Unknown Source)<\/strong><\/p>\n<p><strong>at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)<\/strong><\/p>\n<p><strong>at java.io.ObjectInputStream.readClassDesc(Unknown Source)<\/strong><\/p>\n<p><strong>at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)<\/strong><\/p>\n<p><strong>at java.io.ObjectInputStream.readObject0(Unknown Source)<\/strong><\/p>\n<p><strong>at java.io.ObjectInputStream.readObject(Unknown Source)<\/strong><\/p>\n<p><strong>at com.jbt.DeserializationClass.main(DeserializationClass.java:11)<\/strong><\/p><\/blockquote>\n<ul>\n<li>It will throw an incompatible exception.<\/li>\n<li>Because the given class Employee.java was changed in between serialization and de-serialization process.<\/li>\n<li>Hence the system failed to identify that it is still the same class.<\/li>\n<li>To make our system understand that it is the same class we have to make use of\u00a0<b><i>serialVersionUID<\/i><\/b> variable inside class.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>SERIALIZATION: To\u00a0serializean object means to convert its state to a byte stream so that the byte stream can be returned back into a copy of the object. A\u00a0Javaobject is\u00a0serializable if its class or any of its super classes implements either the\u00a0java.io.Serializable interface or its subinterface,\u00a0java.io.Externalizable. DESERIALIZATION: The reverse process of creating object from sequence of [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2139],"tags":[2920,2919,2917,2902,2911,2913,2915,2906,2905,2907,2912,2903,2904,2908,2910,2177,2916,2918,2909,2914],"class_list":["post-1468","post","type-post","status-publish","format-standard","hentry","category-java","tag-and-of-type-long","tag-final","tag-how-serialversionuid-is-helpful-in-serialization-java","tag-how-to-generate-serialversionuid","tag-isnt-suppressing-warnings-better-option-than-adding-serialversionuid-in-this-scenario","tag-java-why-does-my-object-instance-have-two-serialversionuids","tag-serialized-lambda-and-no-serialversionuid","tag-serialversionuid-1l-means","tag-serialversionuid-eclipse","tag-serialversionuid-exception","tag-serialversionuid-field-warning-in-eclipse","tag-serialversionuid-intellij","tag-what-is-used-to-associate-the-serialized-output-with-the-class-used-in-the-serialization-process","tag-which-method-is-used-to-combine-two-paths-in-java","tag-why-generate-long-serialversionuid-instead-of-a-simple-1l","tag-why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array","tag-why-java-declared-serialversionuid-in-exception-and-throwable-class","tag-why-serialversionuid-in-java-must-be-static","tag-why-serialversionuid-is-static-in-java","tag-why-user-defined-serialversionuid-is-not-used-while-desialization"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/1468","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=1468"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/1468\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=1468"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=1468"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=1468"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}