If declaring element data as primitive data types, will the values ​​be serialized if the object is declared serializable?

My question is, does using the use of the primitive data type, unlike their parts of the wrapper counter, have any consequences for serializing them?

For example, I have a class Person

public class Person implements Serializable{ private int age; } 

Unlike

 public class Person implements Serializable{ private Integer age; } 

What are their differences?

+4
source share
2 answers

I say in terms of Java Serialization:

Although int is a primitive type that only stores the value of the variable (in binary), the Integer object (using ObjectOutputStream ) will store some "metadata" that the Integer object will see when deserialized.

Yes, serialization not only saves the object, but also the state of the object, so if you store it,

 private Integer value = 5; 

Meaning (lack of a better word) inside Integer and the whole object is saved.

Note added: in order not to store the object / variable, mark the transient , .eg field

 transient private Integer value = 5; 

Related Resources:

+4
source

Well, the exact serialization format will be slightly different (only 32 bits versus a serialized Integer object containing 32 bits and a header), but both will be serialized and deserialized just fine.

If declaring element data as primitive data types, will the values ​​be serialized if the object is declared serializable?

Yes, everything that is not marked transient will be serialized, including primitives.

What are you trying to do?

+4
source

All Articles