Table of Contents
Transient variable is the variable whose value is not serialized during serialization. You will get default value for these variable when you deserialize it.
Lets say you have Country class and you don’t want to Serialize population attribute as it will change with time, so you can declare population attribute as transient and it won’t serialized any more.
Java Serialization Tutorial:
Transient keyword example:
Create a classed called Country.java as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package org.arpit.java2blog; import java.io.Serializable; public class Country implements Serializable { String name; transient long population; public Country() { super(); } public Country(String name, long population) { super(); this.name = name; this.population = population; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getPopulation() { return population; } public void setPopulation(long population) { this.population = population; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package org.arpit.java2blog; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class SerializeMain { /** * @author Arpit Mandliya */ public static void main(String[] args) { Country india = new Country(); india.setName("India"); india.setPopulation(100000); try { FileOutputStream fileOut = new FileOutputStream("country.ser"); ObjectOutputStream outStream = new ObjectOutputStream(fileOut); outStream.writeObject(india); outStream.close(); fileOut.close(); }catch(IOException i) { i.printStackTrace(); } System.out.println("serialized"); } } |
1 2 3 |
serialized |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package org.arpit.java2blog; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class DeserializeMain { /** * @author Arpit Mandliya */ public static void main(String[] args) { Country india = null; try { FileInputStream fileIn =new FileInputStream("country.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); india = (Country) in.readObject(); in.close(); fileIn.close(); }catch(IOException i) { i.printStackTrace(); return; }catch(ClassNotFoundException c) { System.out.println("Country class not found"); c.printStackTrace(); return; } System.out.println("Deserialized Country..."); System.out.println("Country Name : " + india.getName()); System.out.println("Population : " + india.getPopulation()); } } |
1 2 3 4 5 |
Deserialized Country... Country Name : India Population : 0 |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.