{"id":5147,"date":"2024-12-17T22:56:01","date_gmt":"2024-12-17T17:56:01","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=5147"},"modified":"2024-12-18T08:30:25","modified_gmt":"2024-12-18T03:30:25","slug":"understanding-serialization-in-java-a-beginners-guide","status":"publish","type":"post","link":"https:\/\/afzalbadshah.com\/index.php\/2024\/12\/17\/understanding-serialization-in-java-a-beginners-guide\/","title":{"rendered":"Understanding Serialization in Java: A Beginner&#8217;s Guide"},"content":{"rendered":"\n<p>Serialization is an important concept in Java, especially when you need to save the state of objects or transfer them over a network. In this tutorial, we&#8217;ll discuss how serialization and deserialization work in Java using a simple <code>Car<\/code> class. The process of serialization allows you to save the state of an object to a file, while deserialization allows you to read that object back into memory.  Here, we will explore the steps of serializing and deserializing an <code>Car<\/code> object.<\/p>\n\n\n\n<p>We begin with a <code>Car<\/code> class, which implements the <code>Serializable<\/code> interface. This is essential because Java needs to know that the objects of this class can be converted to a byte stream and saved to a file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.*;\n\n\/\/ Simple Car class implementing Serializable\nclass Car implements Serializable {\n    String make;\n    int year;\n\n    Car(String make, int year) {\n        this.make = make;\n        this.year = year;\n    }\n}\n\npublic class CarSerializableExample {\n    public static void main(String&#91;] args) throws Exception {\n        \/\/ Writing the object (Serialization)\n        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(\"car.txt\"));\n        Car car1 = new Car(\"Toyota\", 2021);\n        out.writeObject(car1);\n        out.close();\n        \n        \/\/ Reading the object (Deserialization)\n        ObjectInputStream in = new ObjectInputStream(new FileInputStream(\"car.txt\"));\n        Car readCar = (Car) in.readObject();\n        in.close();\n\n        System.out.println(\"Car Make: \" + readCar.make);\n        System.out.println(\"Car Year: \" + readCar.year);\n    }\n}\n<\/code><\/pre>\n\n\n\n<p>In this example, the <code>Car<\/code> class implements <code>Serializable<\/code>, indicating that its objects can be serialized. The <code>Car<\/code> class has two attributes: <code>make<\/code> (the car&#8217;s make) and <code>year<\/code> (the car&#8217;s manufacturing year). We provide a constructor to initialize these values.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"640\" height=\"254\" src=\"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/12\/image-1.png?resize=640%2C254&#038;ssl=1\" alt=\"\" class=\"wp-image-5150\" srcset=\"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/12\/image-1.png?w=800&amp;ssl=1 800w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/12\/image-1.png?resize=300%2C119&amp;ssl=1 300w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/12\/image-1.png?resize=768%2C305&amp;ssl=1 768w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/12\/image-1.png?resize=604%2C240&amp;ssl=1 604w\" sizes=\"(max-width: 640px) 100vw, 640px\" \/><figcaption class=\"wp-element-caption\">Serialization process<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Serialization Process<\/h3>\n\n\n\n<p>Serialization is the process of converting an object into a stream of bytes so that it can be saved to a file or transferred. In this example, we use the <code>ObjectOutputStream<\/code> to serialize the object and write it to a file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(\"car.txt\"));\nCar car1 = new Car(\"Toyota\", 2021);\nout.writeObject(car1);\nout.close();\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>ObjectOutputStream<\/strong> is used to write the object to a file. We create an instance of <code>ObjectOutputStream<\/code> and pass a <code>FileOutputStream<\/code> that points to the file <code>car.txt<\/code>.<\/li>\n\n\n\n<li>We create a <code>Car<\/code> object (<code>car1<\/code>) and initialize it with <code>\"Toyota\"<\/code> as the make and <code>2021<\/code> as the year.<\/li>\n\n\n\n<li>The <code>writeObject(car1)<\/code> method is called to serialize the <code>car1<\/code> object and save it to the file.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Deserialization Process<\/h3>\n\n\n\n<p>Deserialization is the opposite of serialization. It reads the byte stream from the file and converts it back into an object. In our example, we use <code>ObjectInputStream<\/code> to deserialize the object.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ObjectInputStream in = new ObjectInputStream(new FileInputStream(\"car.txt\"));\nCar readCar = (Car) in.readObject();\nin.close();\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>ObjectInputStream<\/strong> is used to read the object from the file. We create an instance of <code>ObjectInputStream<\/code> and pass a <code>FileInputStream<\/code> that points to the file <code>car.txt<\/code>.<\/li>\n\n\n\n<li>We use the <code>readObject()<\/code> method to read the object and cast it back to the <code>Car<\/code> class.<\/li>\n\n\n\n<li>Finally, we close the <code>ObjectInputStream<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Output<\/h3>\n\n\n\n<p>After deserialization, we can access the attributes of the <code>Car<\/code> object and print them to the console:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>System.out.println(\"Car Make: \" + readCar.make);\nSystem.out.println(\"Car Year: \" + readCar.year);\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>We access the <code>make<\/code> and <code>year<\/code> attributes of the <code>readCar<\/code> object and print them. This will display the make and year of the car that was read from the file.<\/li>\n<\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Serialization is an important concept in Java, especially when you need to save the state of objects or transfer them over a network. In this tutorial, we&#8217;ll discuss how serialization and deserialization work in Java using a simple Car class. The process of serialization allows you to save the state of an object to a file, while deserialization allows you to read that object back into memory. Here, we will explore the steps of serializing and deserializing an Car object&#8230;.<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/afzalbadshah.com\/index.php\/2024\/12\/17\/understanding-serialization-in-java-a-beginners-guide\/\"> Read More<span class=\"screen-reader-text\">  Read More<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":5148,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false}}},"categories":[602],"tags":[612,603,647],"class_list":["post-5147","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-object-oriented-programing-oop","tag-java","tag-oop","tag-serialization"],"aioseo_notices":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/12\/Abstract-Classes-in-Java-1.webp?fit=1920%2C1080&ssl=1","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pf3emP-1l1","jetpack-related-posts":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/5147","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/comments?post=5147"}],"version-history":[{"count":2,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/5147\/revisions"}],"predecessor-version":[{"id":5151,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/5147\/revisions\/5151"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media\/5148"}],"wp:attachment":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media?parent=5147"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/categories?post=5147"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/tags?post=5147"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}