MainMenu

Home Core Java Overview Maven Tutorials

Thursday, 11 April 2019

Dictionary and serialization in Java

Dictionary and serialization in Java




Dictionary:- Dictionary is an obstract class that represents a key/value storage repository and operates much like Map.
With dictionaries, we can
1). INSERT
2). FIND
3). DELETE
public class DisctionaryPractice
{
public static void main(Striing[] args)
{
Map stardictionary = new HashMap();
stardictionary.put("Julia", "America");
stardictionary.put("Nicole", "USA");
stardictionary.put("Kiera", "UK");
stardictionary.put("Anne", "new york");
}
System.out.println(stardictionary.get("Julia"));
System.out.println(stardictionary.toString());
System.out.println(stardictionary.keySet());
System.out.println(stardictionary.values());
}

Serialization in Java

Serialization in java is a mechanism of writing the state of an object into a byte stream.
In other Word
Serialization is a mechanism of convertion the state of an object into a byte stream.
The reverse operation of serialization is called deserialization.
In other Word
Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory.
The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform.
To make a Java object serializable we implement the java.io.Serializable interface.
The ObjectOutputStream class contains writeObject() method for serializing an Object.

Advantage of Java Serialization


It is mainly used to travel object's state on the network(known as marshaling).

Example of Serialization:-

class Employee implements Serializable
{
int empid;
String empname;
public Employee(int empid, String empname)
{
this.empid = empid;
this.empname = empname;
}
}
public class Persist
{
public static void main(String[] args)
{
Employee emp = new Employee(308, "Chandan");
FileOutputStream fout = new FileOutputStream("file.text");
ObjectOutputStream Oout = new ObjectOutputStream(fout);
Oout.writeObject(emp);
Oout.flush();
System.out.println("Serialization Completed");
}
}

Example of Deserialization:-


class Employee implements Serializable
{
int empid;
String empname;
public Employee(int empid, String empname)
{
this.empid = empid;
this.empname = empname;
}
}
public class Depersist
{
public static void main(String[] args) throws Exception
{
FileInputStream fin = new FileInputStream("file.txt");
ObjectInputStream Oin = new ObjectInputStream(fin);
Employee emp = (Employee)Oin.readObject();
System.out.println(emp.empid+ " " + emp.empname);
Oin.close();
System.out.println("DeSerialization Completed");
}
}

No comments:

Post a Comment