nawazish-stackoverflow
nawazish-stackoverflow

Reputation: 283

What factors govern file size when Java Object is Serialized

I was trying out very basic Java Serialization of two instances of different type. Here is the class structure of first Java type:

class Ancestor {
    int ai = 1;
    String as = "abc"; 
}

class DescendentSer extends Ancestor implements java.io.Serializable{
    int diser = 2;
    String dsser = "xyz";

    @Override
    public String toString (){
        return diser + " " + dsser + " " +ai+" "+as ;
    }
}

I try to Serialize "DescendentSer" via the following code fragment:

FileOutputStream fos = new FileOutputStream("C:\\CoreCod\\serial.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(new DescendentSer());
oos.flush();
oos.close();

When serialization is completed the size of the "serial.dat" file happens to be 117 bytes. Then I try to serialize another instance whose class structure is as follows:

class IndDescendentSer implements java.io.Serializable{
    int diser = 2;
    String dsser = "xyz";

    @Override
    public String toString (){
        return diser + " " + dsser ;
    }
}

The serialization code for serializing "IndDescendentSer" is exactly the same as above (except that the name of the file into which the object instance would be serialized and the instance to be serialized has changed from before). However, the size of the serialized file this time happens to be 120 bytes.

How is it possible that this time the bytes contained in this serialized file is more than the older one especially when the instance of "IndDescendentSer" is a direct descendent of Object class whereas "DescendentSer" had its super type - the "Ancestor" class. And thus, it was expected that "DescendentSer" would be serialized with more data and meta-data.

Upvotes: 0

Views: 643

Answers (1)

engineercoding
engineercoding

Reputation: 832

I think it is in the name. A character is stored in a byte, and the last class has a name with 3 letters more and 3 bytes more. Note that it might be a coincidence in that, since I'm not super familiar with serialization.

Serialization is about storings an instance, which only have to do with variables of that class because those determine the state of the class. When the variables are loaded in, the instance is the same because it acts the same with the current variables, which is what we want.

Upvotes: 1

Related Questions