You need to serialize a long primitive value, and you have been given the following code:
Which statement is true? Choose one.
* The code must box the primitive using oos.writeObject(Long.valueOf(l)).
* The primitive must be included in the outer Java class as an instance variable to be serialized.
* The serialization should be implemented as oos.writeObject(l).
* The serialization should be implemented as oos.writeLong(l).
* The serialization must delegate to the DataOutput class for writing primitives.
#java #certificationquestion #ocp
Java serialization provides a way to represent a graph of objects as a byte sequence.
This mechanism also supports primitive data directly, as part of objects.
Primitive wrapper classes also implement the Serializable interface and can be serialized too.
In most cases, you will use the class ObjectOutputStream to create the serialized byte stream.
Note, however, that the argument to the writeObject method is an object, not a primitive.
It turns out that ObjectOutputStream implements the java.io.DataOutput interface.
That interface defines writeXXX methods for all primitives.
It will allow you to use the oos object to serialize the primitive directly.
So 'The serialization should be implemented as oos.writeLong(l).' is the correct answer,
better than 'The serialization should be implemented as oos.writeObject(l).'.
'The code must box the primitive using oos.writeObject(Long.valueOf(l)).' is wrong
because the ObjectOutputStream is able to serialize primitives directly,
which means that boxing is not necessary.
'The primitive must be included in the outer Java class as an instance variable to be serialized.' is wrong
because it’s not necessary to wrap a primitive in such an object just to get it out into the byte sequence.
'The serialization must delegate to the DataOutput class for writing primitives.' is wrong because DataOutput is an interface, not a class.