Interview Questions

Code Sample: Shows how to read a serialized object and print its information

An Introduction to Socket Programming


(Continued from previous question...)

Code Sample: Shows how to read a serialized object and print its information

Code Sample: ReadDate.java

import java.io.*;
import java.util.Date;

public class ReadDate {

public static void main
(String argv[]) throws Exception

 {
    FileInputStream fis = 
     new FileInputStream("date.out");
     
    ObjectInputStream ois =
     new ObjectInputStream(fis);
     
    Date date = (Date) ois.readObject();
    
System.out.println("The date is: "+date);

    ois.close();
    fis.close();
  }
}

In the example above we have worked with an instance of the Date class, which is an existing serialized Java class. The question that may come to mind is: are all existing Java class serialized? The answer is: No. Either because they don't need to be, or it doesn't make sense to serialize some classes. To find out if a class is serializable, use the tool serialver that comes with the JDK. You can either use it from the command line as follows:

c:\> serialver java.util.Date
java.util.Date: static final long serialVersionUID = 7523967970034938905L;

(In this example, we are testing if the Date class is serializable. The output here means that the Date class is serializable and it print its version unique identifier.)

Or, alternatively, you can use the GUI-based serialver tool using the command:

c:\> serialver -show

This command pops up a window, where you can write the name of the class (including its path) that you want to check.

(Continued on next question...)

Other Interview Questions