Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

i have a question on whether the use of using primitive data type as opposed to their wrapper counter parts have any due effects on their serialization?

For example, i have a class Person

public class Person implements Serializable{
private int age;
}

as opposed to

public class Person implements Serializable{
private Integer age;
}

What are their differences?

like image 403
Oh Chin Boon Avatar asked Jun 13 '11 06:06

Oh Chin Boon


People also ask

Can primitive data types be serialized?

Yes, primitive types are part of serialization process.

What will happen if we try to serialize primitive types in Java?

Ans- If you try to serialize an object of a class which implements serializable, but the object includes a reference to an non-serializable class then a 'NotSerializableException' will be thrown at runtime.

What happens if the object to be serialized?

To serialize an object means to convert its state to a byte stream so way that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java.

Which kind of data fields of an object is guaranteed to be Serializable?

The serializable fields of a class can be defined two different ways. Default serializable fields of a class are defined to be the non-transient and non-static fields. This default computation can be overridden by declaring a special field in the Serializable class, serialPersistentFields .


1 Answers

I'm speaking in terms of Java's Serialization:

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

Yes, serialization not only stores the object, but also the states of the object, so if you store,

private Integer value = 5;

The value is "wrapped" (lack of better word) inside Integer and the whole object is stored.

Added note: In order not to store an object/variable, mark the field with a transient, .e.g

transient private Integer value = 5;

Related Resources:

  • Discover the secrets of the Java Serialization API
like image 196
Buhake Sindi Avatar answered Sep 28 '22 14:09

Buhake Sindi