Sunteți pe pagina 1din 19

1)What do you mean by serialization and

deserialization?
Ans:- Serialization is the process of converting
an object's state (including its entire graph) to
a sequence of bytes which can be persisted
into disk or sent over network to any other
running machine. The process of rebuilding
those bytes into a live object at some future
time is known as deserialization.
2)What is the need of serialization?
Ans:- When u create an object, it exists for as
long as u need it, but under no circumstances
does it exist when the program terminates.
While this makes sense at first, there are
situations in which it would be incredibly useful
if an object could exist and hold its information
even while the program wasn’t running. Then
the next time u started the program, the object
would be there and it would have the same
information it had, the previous time the
program was running.

3)Object serialization was added to java in


order to support which two features?
Ans:- Object serialization was added to the
language to support two major features. Java’s
RMI and Java Beans.
When JavaBean is used , it’s state information is
generally configured at design time. This state
information must be stored and later recovered
when the program is started. Object serialization
performs this task.
In case of RMI , when object is sent over a
network , its copy is sent through serialization
mechanism.
4)What are the requirements we need to meet
in order to serialize an object?
Ans:-a) class should implement either
Serializable or Externalizable interface
b) class non-static members should be of
serialized nature.
5) what is the difference between
Serializable and Externalizable?
Ans:- In case of Serializable, default serialization
process is used. while in case of Externalizable
custom Serialization process is used which is
implemented by application.
Serialization is a recursive algorithm. i.e. apart
from the fields that are required, starting from a
single object, until all the objects that can be
reached from that object by following instance
variables, are also serialized. This includes the
super class of the object until it reaches the
"Object" class and the same way the super class
of the instance variables until it reaches the
"Object" class of those variables. Basically all the
objects that it can read. This leads to lot of
overheads. 

Both serializing and deserializing require the


serialization mechanism to discover information
about the instance it is serializing. Using the
default serialization mechanism, will use reflection
to discover all the field values. Also the information
about class description is added to the stream
which includes the description of all the
serializable superclasses, the description of the
class and the instance data associated with the
specific instance of the class. Lots of data and
metadata and again performance issue. 
Externalization efficiency comes at a price. The
default serialization mechanism adapts to
application changes due to the fact that metadata
is automatically extracted from the class.
Externalization on the other hand isn't very flexible
and requires you to rewrite your marshalling and
unmarshalling code whenever you change your
class definitions.

As you know a default public no-arg constructor


will be called when serializing the objects that
implements Externalizable interface. Hence,
Externalizable interface can't be implemented by
Inner Classes in Java as all the constructors of an
inner class in Java will always accept the instance
of the enclosing class as a prepended parameter
and therefore you can't have a no-arg constructor
for an inner class ( exception to this is static inner
class ). Inner classes can achieve object
serialization by only implementing Serializable
interface.

If you are subclassing your externalizable class,


you have to invoke your superclass’s
implementation. So this causes overhead while
you subclass your externalizable class.
By implementating java.io.Serializable, you get
"automatic" serialization capability for objects of
your class. No need to implement any other logic,
it'll just work. The Java runtime will use reflection
to figure out how to marshal and unmarshal your
objects.

In earlier version of Java, reflection was very slow,


and so serializaing large object graphs (e.g. in
client-server RMI applications) was a bit of a
performance problem. To handle this situation, the
java.io.Externalizable interface was provided,
which is like java.io.Serializable but with custom-
written mechanisms to perform the marshalling
and unmarshalling functions (you need to
implement readExternal and writeExternal
methods on your class).

6)What is SerialVersionUID in case of


Serialization?
Ans:- during serialization, runtime associates with
each serializable class a version number, called a
serialVersionUID, which is used during de-
serialization to verify that the sender and receiver
of a serialized object have loaded classes for that
object that are compatible with respect to
serialization. If the receiver has loaded a class for
the object that has a different serialVersionUID
than that of the corresponding sender’s class, then
de-serialization will result in an
InvalidClassException. A serializable class can
declare its own serialVersionUID explicitly by
declaring a field named “serialVersionUID” that
must be static, final, and of type long:

private static final long serialVersionUID = 4L;


Here, the serialVersionUID represents your class
version.

If a serializable class does not explicitly


declare a serialVersionUID, then the
serialization runtime will calculate a default
serialVersionUID value for that class based on
various aspects of the class.
Basically, automatically-generated UID is
generated based on a class name,
implemented interfaces, and all public and
protected members. Changing any of these
in any way will change the serialVersionUID.
However, it is strongly recommended that all
serializable classes explicitly declare
serialVersionUID values, since the default
serialVersionUID computation is highly sensitive to
class details that may vary depending on compiler
implementations and can produce different
serialVersionUID in different environments.
This can result in
unexpected InvalidClassException during de-
serialization.
Therefore, to guarantee a consistent
serialVersionUID value across different java
compiler implementations, a serializable class
must declare an explicit serialVersionUID value. It
is also strongly advised that explicit
serialVersionUID declarations use the private
modifier in serialVersionUID where possible,
since such declarations apply only to the
immediately declaring class. SerialVersionUID
field is not useful as inherited member.

7)What happens when we deserialize an


object?
Ans:- 1) The object is read from the stream.
2) The JVM determines (through info stored
with the serialized object ) the object’s class
type.
3) The JVM attempts to find and load the
object’s class. If the JVM can’t find and / or
load the class, the JVM throws an exception
and deserialization fails.
4) the serialVersionUID of the class
representing the deserialized object is
extracted and compared with the
serialVersionUID of the loaded class.
If the numbers do not match then,
InvalidClassException is thrown.

5)A new object is given space on the heap.

6) if class implements Serializable,

(i) serialized object’s constructor does not


run ! obviously , if the constructor ran, it would
restore the state of the object back to its
original ‘new’ state and that’s not what we
want. We want the object to be restored to the
state it had when it was serialized, not when it
was first created.
(ii) If the object has a non-serializable class
somewhere up its inheritance tree, the
constructor for that non-serializable class will
run along with any constructors above that.
Once the constructor chaining begins, you
can’t stop it , which means all superclasses,
beginning with the first non-serializable one,
will reinitialize their state.
(iii) if the class has overridden
"readObject()" method in which we are trying
to initialize instance member/s with the help of
serialized state, it is invoked.
if not, The object’s instance variables
are given the values from the serialized state.
Transient variables are given a value of null for
object references and defaults (0, false, etc. )
for primitives.

7) if the class implements Externalizable.

(i) serialized object’s no-arg constructor


gets invoked.
(ii) readExternal() method is invoked which
we have defined.
8) What is transient variable in Java?
Ans:- If you don't need to save and restore any
member variable (e.g., the password kept in a
String object), the private modifier will not help
you. Serialized information can be read in a file or
in a captured network packet. You may implement
the Externalizable interface, which is
demonstrated in the previous paragraph. In this
case, nothing is written automatically, and you can
control the entire process.
However, serializable objects are much more
convenient because everything is serialized there
automatically. You can forbid serialization of any
member variable object with the transient modifier.
It tells the JVM: "Do not save and restore this field,
please; somebody else will take care of this field." 
9) When should we use transient keyword
in java?
Ans:- a) First and very logical case would be
where you may have fields that are
derived/calculated from other fields within
instance of class. They should be calculated
programmatically everytime rather than having the
state be persisted via serialization. An example
could be time-stamp based value; such as age of
a person OR duration between a timestamp and
current timestamp. In both cases, you would be
calculating value of variable based on current
system time rather than when the instance was
serialized.
b)Second logical example can be any secure
information which should not leak outside the
JVM in any form (either in database OR byte
stream).
c)Another example could be fields which are not
marked as “Serializable” inside JDK or
application code. Classes which do not
implement Serializable interface and are
referenced within any serializable class, cannot
be serialized; and will throw
“java.io.NotSerializableException” exception.
These non-serializable references should be
marked “transient” before serializing the main
class.
d)And lastly, there are times when it simply
doesn’t make sense to serialize some
fields. Period. For example, In any class if you
have added a logger reference, then what’s
use of serializing that logger instance.
Absolutely no use. You serialize the
information which represent the state of
instance, logically.Loggers never share the
state of an instance. They are just utilities for
programming/debugging purpose. Similar
example can be reference of a Thread class.
Threads represent a state of a process at any
given point of time, and there is no use to store
thread state with your instance; simply
because they do not constitute the state of
your class’s instance.

10) what are the things get written when u


serialize an object ?
 Ans: it writes out the metadata (description)

of the class associated with an instance such


as length of the class, the name of the class,
serialVersionUID (or serial version), the
number of fields in this class.
 Then it recursively writes out the metadata of
the superclass until it finds java.lang.object.

 Once it finishes writing the metadata


information, it then starts with the actual data
associated with the instance. But this time, it
starts from the top most superclass.

 Finally it writes the data of objects associated


with the instance starting from metadata to
actual content recursively.

11) If a class is Serializable but its super class


in not, what will be the state of the instance
variables inherited from super class after
deserialization?
ans:- Java serialization process  only continues in
object hierarchy till the class is Serializable i.e.
implements Serializable interface in java  and
values of the instance variables inherited from
super class will be initialized by calling constructor
of Non-Serializable Super class
during deserialization process.

12) Suppose super class of a new class


implement Serializable interface, how can you
avoid new class to being serialized?

ans:- If Super Class of a Class already


implements Serializable interface in Java then its
already Serializable in Java, since you can not
unimplemented an interface its not really possible
to make it Non Serializable class but yes there is a
way to avoid serialization of new class. To avoid
java serialization you need to
implement writeObject() and readObject()method
in your Class and need to
throw NotSerializableException from those
method. This is another benefit of customizing
java serialization process

13) Suppose you have a class which you


serialized it and stored in persistence and later
modified that class to add a new field. What
will happen if you deserialize the object already
serialized?
ans:- It depends on whether class has its
own SerialVersionUID or not. If we don't
provide serialVersionUID in our code java compiler
will generate it. By adding any new field there is
chance that new serialVersionUID generated for
that class version is not the same of already
serialized object and in this case JVM will raise
java.io.InvalidClassException and this is the
reason its recommended to have your
own serialVersionUID in code and make sure to
keep it same always for a single class.

14) Which kind of variables is not serialized


during Java Serialization?
ans:- Since static variables belong to the class and
not to an object they are not the part of the state of
object so they are not saved during Java
Serialization process. Transient variables are also
not included in java serialization process and are
not the part of the object’s serialized state.

15) Does “java.lang.Object” class implement


“Serializable” ? explain with reason.

Ans:- No.

Because in that case each and every class


would have become “Serializable”.
So what ? What’s a problem ? Can’t all the classes
in java become “Serializable” ?
They can. But it does not make any sense in
case of some classes , to become serializable.
there are some classes that don't have an obvious
serialization. Consider, for
example, an instance of FileInputStream. An
instance of FileInputStream represents a file.
Suppose, for example, it was created using the
following line of code:
FileInputStream file = new FileInputStream
("c:\\temp\\foo");
It's not at all clear what should be written out when
this is serialized. The problem is that the file itself
has a different lifecyle than the serialized data.
The file might be edited, or deleted entirely, while
the serialized information remains unchanged. Or
the serialized information might be used to restart
the application on another machine, where
"C:\\temp\\foo" is the name of an entirely different
file.
Another example is provided by the Thread class.
A thread represents a flow of execution within a
particular JVM. You would not only have to store
the stack, and all the local variables, but also all
the related locks and threads, and restart all the
threads properly when the instance is deserialized.
TIP:   Things get worse when you consider
platform dependencies. In general, any class that
involves native code is not really a good candidate
for serialization.

16) what happens when one of the members in


the class doesn't implement Serializable
interface?
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.

17) what happens when base class doesn't


implement Serializable interface but sub class
implements?
Ans:- If you try to serialize an object of a class
which implements Serializable but its base class
does not , at the most what will happen is base
class members won’t get serialized. Java
serialization process only continues in object
hierarchy till the class is Serializable i.e.
implements Serializable interface in Java and
values of the instance variables inherited from
super class will be initialized by calling constructor
of Non-Serializable Super class during
deserialization process.

18) Can you Customize Serialization process or


can you override default Serialization process
in Java?
ans:- The answer is yes you can. We all know that
for serializing an
object ObjectOutputStream.writeObject
(saveThisobject) is invoked and for reading
object ObjectInputStream.readObject() is invoked
but there is one more thing which Java Virtual
Machine provides you is to define two methods
“private void writeObject(ObjectOutputStream out)”
and “private void readObject(ObjectInputStream
in)” in your class. If you define these two methods
in your class then JVM will invoke these two
methods instead of applying default serialization
mechanism. You can customize behavior of object
serialization and deserialization here by doing any
kind of pre or post processing task. Important point
to note is making these methods private to avoid
being inherited, overridden or overloaded. Since
only Java Virtual Machine can call private method,
integrity of your class will remain and Java
Serialization will work as normal.
19) while customizing serialization process, if
we define “readObject()” and “writeObject()”
with the accessibility modifiers other than
“private” what will happen?
Ans:- If these methods are not private, they will be
ignored by JVM.

20) Can we transfer a Serialized object via


network?
Ans:-Yes you can transfer a Serialized object via
network because Java serialized object remains in
form of bytes which can be transmitted via
network. You can also store serialized object in
Disk or database as Blob.

21) What is the difference between Standard IO


and NIO?
Ans:- First main difference between the standard
IO and NIO is, standard IO is based on streams and
NIO is buffer oriented. Buffer oriented operations
provide flexibility in handling data. In buffer
oriented NIO, data is first read into a buffer and
then it is made available for processing. So we can
move back and forth in the buffer. But in the case
of streams it is not possible.
Second main difference is, blocking and non-
blocking IO operations. In case of streams, a
thread will be blocked until it completes the IO
operation. Wherein the NIO allows for non-
blocking operations. If the data is not available for
IO operations, then the thread can do something
else and need not stay in blocked mode.

S-ar putea să vă placă și