You are here: Home / Topics / Program to Serialize Student object in Java

Program to Serialize Student object in Java

Filed under: Java on 2024-03-01 06:47:34

// Program to Serialize Student object student object.

import java.io.*;

class Student implements Serializable
{
int rno;
String sname;
double marks;
 
// Constructor
Student( int r, String nm, double m )
{
 rno = r;
 sname = nm;
 marks = m;
}

void display()
{
 System.out.println(" Roll No. : " + rno );
 System.out.println(" Name : " + sname );
 System.out.println(" Marks : " + marks );
}

public static Student getData() throws IOException
{  
 int r;
 String nm;
 double m;
 
 BufferedReader br = new BufferedReader( new InputStreamReader( System.in ));
 
 System.out.print(" Enter roll number : ");
 r = Integer.parseInt(br.readLine());
 
 System.out.print(" Enter name : ");
 nm = br.readLine();
 
 System.out.print(" Enter total marks : ");
 m = Double.parseDouble(br.readLine());
 
 // Creating Student object and initializing
 Student s = new Student(r, nm, m);
 return s;
}
}

class StudentSerialization
{
public static void main( String args[ ] ) throws IOException
{
 // attach FileOutputStream to file.
 FileOutputStream fos = new FileOutputStream( "StuFile" );
 
 // attach ObjectOutputStream to FileOutputStream.
 ObjectOutputStream oos = new ObjectOutputStream( fos );
 
 // Creating Student object and reading data from KB.
 Student s = Student.getData();
 
 // write object (s) to 'oos'
 oos.writeObject( s );
 
 oos.close();
}
}


Output:

Enter roll number : 290
Enter name : Nils Patel
Enter total marks : 99

About Author:
G
Geetam     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.