You are on page 1of 4

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

WORKSHEET 3

Student Name: Chinmay Rathore UID: 22BCS12304


Branch: CSE Section/Group: 702/B
Semester: 3rd Date of Performance: 20/10/23
Subject Name: Java Programming Subject Code: 22CSH-201

1. Aim: Define a person class that implement serializable the person


class has a name, age and contact attributes in main create a person
object cast the object back to person family, deserialized person
information.

2. Source Code:

import java.io.*;
class Person implements Serializable {
private String name;
private int age;
private String contact;

public Person(String name, int age, String contact) {


this.name = name;
this.age = age;
this.contact = contact;
}

public String getName() {


return name;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

public int getAge() {


return age;
}

public String getContact() {


return contact;
}
}

public class Main {


public static void main(String[] args) {

Person person = new Person("Avinash", 20,


"avinash@gmail.com");

try {

FileOutputStream fileOut = new


FileOutputStream("person.ser");
ObjectOutputStream out = new
ObjectOutputStream(fileOut);
out.writeObject(person);
out.close();
fileOut.close();
System.out.println("Person object serialized and
saved to person.ser");
} catch (IOException e) {
e.printStackTrace();
}

Person deserializedPerson = null;

try {
FileInputStream fileIn = new
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

FileInputStream("person.ser");
ObjectInputStream in = new
ObjectInputStream(fileIn);
deserializedPerson = (Person) in.readObject();
in.close();
fileIn.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}

if (deserializedPerson != null) {
System.out.println("Deserialized" +
" Person Information:");
System.out.println("Name: " +
deserializedPerson.getName());
System.out.println("Age: " +
deserializedPerson.getAge());
System.out.println("Contact: " +
deserializedPerson.getContact());
}
}
}

3. Screenshot of Outputs:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

4. Learning Outcomes
(i) Understand the concept of Java programming.
(ii) Developed problem-solving skills.

You might also like