What is transient keyword in Java?

What is serialization?

Serialization in java is a mechanism of writing the state of an object into a byte stream and deserialization is the process of converting a stream of bytes back into a copy of the original object. More about... Java Serialization

transient keyword

The transient keyword in Java is used to indicate that a field should not be serialized. In Java , by default, all of object's variables get converted into a persistent state . In rare cases, you may want to avoid persisting some variables because you don't have the need to persist those variables. So you can declare those variables as transient . That means, when JVM comes across transient keyword, it ignores original value of the variable and save default value of that variable data type. That is the main purpose of the transient keyword. It is good habit to use transient keyword with private confidential fields of a class during serialization. Probably the best example is a Thread field. There's normally no reason to serialize a Thread, as its state is very 'flow specific'. Example
import java.io.*; class Student implements Serializable { int id; String name; transient int age; Student(int id, String name,int age) { this.id = id; this.name = name; this.age = age; } }
Serializing an Object
public class TestClass{ public static void main(String[] args) { try{ Student st = new Student(101,"John",10); FileOutputStream fos = new FileOutputStream("student.info"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(st); oos.close(); fos.close(); }catch(Exception e){ System.out.println(e); } } }
Deserialization of Object
public class TestClass{ public static void main(String[] args) { Student st = null; try{ FileInputStream fis = new FileInputStream("student.info"); ObjectInputStream ois = new ObjectInputStream(fis); st = (Student)ois.readObject(); }catch(Exception e){ System.out.println(e); } System.out.println(st.id); System.out. println(st.name); } }

When you try to deserialize, you wont get back the transient field "age" because its not serialized.