What is a transient keyword?

transient is a keyword which is use in serialization.at the time of serialization if we declare any variable as transient then it will not be save. deserialization time it gives default value of that data type.

				
					import java.io.Serializable;

//create model Test class
class Test implements Serializable {
	transient int i;
	int j;

	public Test(int i, int j) {
		this.i = i;
		this.j = j;
	}
}
				
			
				
					import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

//implement Serializable Test class
public class HelloSerial {
	public static void main(String[] args) throws Exception {
		
		Test t1 = new Test(20, 30);
		FileOutputStream fs = new FileOutputStream("abc.ser");
		ObjectOutputStream os = new ObjectOutputStream(fs);
		os.writeObject(t1);
		os.flush();
		System.out.println("object is written inside file");
	}
}
				
			
				
					import java.io.FileInputStream;
import java.io.ObjectInputStream;

//deserialize Test class
public class HelloDeserialize {
	public static void main(String[] args) throws Exception {
		
		FileInputStream fis = new FileInputStream("abc.ser");
		ObjectInputStream os = new ObjectInputStream(fis);
		Test t = (Test) os.readObject();
		System.out.println("I value is:- " + t.i + ",j value is:- " + t.j);
		os.close();
	}
}
				
			

Output :-
I value is:- 0,j value is:- 30

What is a transient keyword? Read More »