Core Java Interview Question Page 11
Question: What is serialization ?
Answer: Serialization is the process of writing complete state of java object into output stream, that stream can be file or byte array or stream associated with TCP/IP socket.
Question: What does the Serializable interface do ?
Answer: Serializable is a tagging interface; it prescribes no methods. It serves to assign the Serializable data type to the tagged class and to identify the class as one which the developer has designed for persistence. ObjectOutputStream serializes only those objects which implement this interface.
Question: How do I serialize an object to a file ?
Answer: To serialize an object into a stream perform the following actions:
- Open one of the output streams, for exxample FileOutputStream
- Chain it with the ObjectOutputStream <
- Call the method writeObject() providinng the instance of a Serializable object as an argument.
- Close the streams
Question: How do I deserilaize an Object?
Answer: To deserialize an object, perform the following steps:
- Open an input stream
- Chain it with the ObjectInputStream - Call the method readObject() and cast the returned object to the class that is being deserialized.
- Close the streams
Java Code try{ fIn= new FileInputStream("c:\\emp.ser"); in = new ObjectInputStream(fIn); //de-serializing employee Employee emp = (Employee) in.readObject(); System.out.println("Deserialized " + emp.fName + " " + emp.lName + " from emp.ser "); }catch(IOException e){ e.printStackTrace(); }catch(ClassNotFoundException e){
e.printStackTrace(); }
Question: What is Externalizable Interface ?
Answer: Externalizable interface is a subclass of Serializable. Java provides Externalizable interface that gives you more control over what is being serialized and it can produce smaller object footprint. ( You can serialize whatever field values you want to serialize)
This interface defines 2 methods: readExternal() and writeExternal() and you have to implement these methods in the class that will be serialized. In these methods you'll have to write code that reads/writes only the values of the attributes you are interested in. Programs that perform serialization and deserialization have to write and read these attributes in the same sequence.