Transient Field Serialization Example
This program demonstrates using transient fields in serialization.
Problem Statement
Write a Java program that shows transient fields are not serialized.
Source Code
| 1 | import java.io.*; |
| 2 | class Student implements Serializable { |
| 3 | int id; transient String password; |
| 4 | Student(int id,String password){ this.id=id; this.password=password; } |
| 5 | } |
| 6 | public class TransientExample { |
| 7 | public static void main(String[] args) throws Exception { |
| 8 | System.out.println("Eduinq Transient Example"); |
| 9 | ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("student.ser")); |
| 10 | Student s=new Student(1,"secret"); |
| 11 | oos.writeObject(s); oos.close(); |
| 12 | ObjectInputStream ois=new ObjectInputStream(new FileInputStream("student.ser")); |
| 13 | Student s2=(Student)ois.readObject(); |
| 14 | System.out.println("Eduinq Student Password: "+s2.password); |
| 15 | } |
| 16 | } |
Program Output
Eduinq Transient Example Eduinq Student Password: null
Explanation
Transient fields are skipped during serialization. - Password not persisted. - Exception handling ensures safe operations. - In enterprise systems, transient secures sensitive fields. Conclusion: Shows transient fields in serialization.