You are on page 1of 3

DEPRTMENT OF

COMPUTER SCIENCE & ENGINEERING

WORKSHEET 3

Student Name: Aakarsh Srivastava UID: 22BCS50096

Branch: CSE Section/Group: 902 -B

Semester: 3rd Date of Performance: 17-10-2023

Subject Name: Java Programming Subject Code: 22CSH-201

1. Aim: Write a program to define a class product with attributes name price and quality.
Create method for serialization and deserialization also demonstrate saving the product object
to a file and then loading it back?

2. Source Code:

import java.io.*;

class product implements Serializable{

String name;

int price;

String quality;

public class Main {

public static void main(String[] args) {

product p1= new product();

p1.name ="Bottle";

p1.price=200;

p1.quality="good";

String filename="C:\\Users\\dell\\Desktop\\conduct.txt";

try{
DEPRTMENT OF
COMPUTER SCIENCE & ENGINEERING
FileOutputStream fos = new FileOutputStream(filename);

ObjectOutputStream oos= new ObjectOutputStream(fos);

oos.writeObject(p1);

oos.close();

fos.close();

System.out.println("Object saved in file");

catch(Exception e){

System.out.println("Exception:"+ e);

try{

FileInputStream fis = new FileInputStream(filename);

ObjectInputStream ois= new ObjectInputStream(fis);

product obj = (product)ois.readObject();

ois.close();

fis.close();

System.out.println("Object is here and its name and price and quality is: "+obj.name +"
"+ obj.price +" "+ obj.quality);

catch(Exception e){

System.out.println("Exception:"+ e);

}
DEPRTMENT OF
COMPUTER SCIENCE & ENGINEERING

3. Screenshot of Outputs:

4. Learning Outcomes
I. How to use Java serialization to save and load objects from a file.
II. I learnt how to use try and catch blocks in a code.
III. Exception Handling which is a good practice to ensure that your program can
handle unexpected errors gracefully.
IV. Understanding file paths and how to work with files in Java.

You might also like