Serialization in Java

Serialization can be defined as a process to write the object state to the byte stream.
  • Byte stream can be transferred over the network or saved into the database.
  • A Java object can be serialized only if it implements the Serializable interface.
In this post, we are going to write a simple example to understand the Serialization process in Java.

Student.java
JavaInstance
package com.javainstance;

import java.io.Serializable;

/**
 * @author javainstance
 *
 */
public class Student implements Serializable {

private int StudentId;

private String StudentName;

private int studentAge;

public Student(int studentId, String studentName, int studentAge) {
super();
StudentId = studentId;
StudentName = studentName;
this.studentAge = studentAge;
}

public int getStudentId() {
return StudentId;
}

public void setStudentId(int studentId) {
StudentId = studentId;
}

public String getStudentName() {
return StudentName;
}

public void setStudentName(String studentName) {
StudentName = studentName;
}

public int getStudentAge() {
return studentAge;
}

public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}

@Override
public String toString() {
return "Student [StudentId=" + StudentId + ", StudentName=" + StudentName + ", studentAge=" + studentAge + "]";
}

}

SerializationInJava

package com.javainstance;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * @author javainstance
 *
 */
public class SerializationInJava {

public static void main(String[] args) {
Student student = new Student(1, "James", 21);

try {
FileOutputStream fileOutStream = new FileOutputStream("D:\\Student.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutStream);
objectOutputStream.writeObject(student);
objectOutputStream.close();
fileOutStream.close();
System.out.println("Serialization in Successful!");

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

Output:

Student.txt

¬í sr com.javainstance.Studentù ‚R(L I StudentIdI 
studentAgeL StudentNamet Ljava/lang/String;xp     t James

Deserialization In Java


References:
https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html


Give you suggestion in comments.If you like the post Share with your friends on social network.














Serialization in Java Serialization in Java Reviewed by JavaInstance on 10:03:00 AM Rating: 5

No comments:

Powered by Blogger.