Monday, September 26, 2011

transient variable example


//A transient variable is a variable that may not be serialized
package Serialization;

import java.io.Serializable;

public class serializableClass implements Serializable
{

/**
*
*/
private static final long serialVersionUID = 1L;

String name;
int DOB;
int DOM;
/*If we don't want to pass the Year Of Birth of any one, then we simply make that variable as "transient"*/
transient int year;
public serializableClass(String name,int dob,int year)
{
this.name = name;
this.DOB = dob;
this.year = year;
}
public void showWish()
{
System.out.print("Good Morning!");
}
public String toString()
{
showWish();
return "Mr."+name+". Your date of birth is "+DOB+"/"+DOM+"/"+year;
}
}

package Serialization;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class mainClass {
public static void main(String args[]) {
try {
System.out
.println("Start of serialization ******************************");
serializableClass srl = new serializableClass("Arun", 14, 1984);
srl.DOM = 02;

System.out.println(srl);
FileOutputStream fos = new FileOutputStream("serial");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(srl);

oos.close();
fos.close();
System.out
.println("End of serialization *************************");

} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
try {
System.out.println("\n");
System.out
.println("Start of deserialization ************************");
serializableClass srl2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
srl2 = (serializableClass) ois.readObject();

System.out.println(srl2);
ois.close();
System.out
.println("End of deserialization ************************");

} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
}
}


Output =>
Start of serialization ******************************
Good Morning!Mr.Arun. Your date of birth is 14/2/1984
End of serialization *************************


Start of deserialization ************************
Good Morning!Mr.Arun. Your date of birth is 14/2/0
End of deserialization ************************

No comments:

Post a Comment