Serialize Object Example
This program demonstrates serializing a Java object to a file.
Problem Statement
Write a Java program that serializes a Student object into a file using ObjectOutputStream.
Source Code
| 1 | import java.io.*; |
| 2 | class Student implements Serializable { |
| 3 | int id; String name; |
| 4 | Student(int id,String name){ this.id=id; this.name=name; } |
| 5 | } |
| 6 | public class SerializeExample { |
| 7 | public static void main(String[] args) { |
| 8 | System.out.println("Eduinq Serialize Example"); |
| 9 | try(ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("student.ser"))) { |
| 10 | Student s=new Student(1,"Arun"); |
| 11 | oos.writeObject(s); |
| 12 | System.out.println("Eduinq Object Serialized Successfully"); |
| 13 | } catch(Exception e){ System.out.println("Eduinq Exception: "+e.getMessage()); } |
| 14 | } |
| 15 | } |
Program Output
Eduinq Serialize Example Eduinq Object Serialized Successfully
Explanation
Uses ObjectOutputStream to serialize object. - Stores object state in file. - Exception handling ensures safe operations. - In enterprise systems, serialization persists objects. Conclusion: Shows serializing objects.