Serialization Java Interview Questions – Set 01

Can you write a simple program that compares two objects to return if they are equal or not? This method will be handy in defining your own equals( ) method.

This is usefull in domain or value object class to compare different object fields in an equals method

public class DomainObject {

//protected because only inheriting domain classes can use it

protected boolean isPropertyEqual(Object compare1, Object compare2) {

// go here if compare1 is null, i.e. test cases 1 & 3

if (compare1 == null) {

if (compare2 != null) {

return false;

}

//go here if compare1 is not null, i.e. test cases 2 & 5

} else if (!compare1.equals(compare2)) {

return false;

}

return true;      //test cases 1 & 4

}

public static void main(String[] args) {

DomainObject d =  new DomainObject();

Print(d.isPropertyEqual(null, null));  //test case 1

Print(d.isPropertyEqual(“abc”, null)); //test case 2

Print(d.isPropertyEqual(null, “abc”)); //test case 3

Print(d.isPropertyEqual(“abc”, “abc”));//test case 4

Print(d.isPropertyEqual(“abc”, “cba”));//test case 5

}

public static void Print(boolean bol){

System.out.println(bol);

}

}

The above class must be abstract. It was not tagged abstract to demo via the main() method by creating a new DomainObject().

The above method can be used in an extending class like

public class Security extends DomainObject implements Serializable {

private String id;

//skipping other methods like getter/setter, toString, etc

public boolean equals(Object obj) {

if (this == obj) {

return true;

}

if (!(obj instanceof Security)) {

return false;

}

//calling super class handy method we just created

return isPropertyEqual(this.id, ((Security) obj).getId());

}

public int hashCode() {

return id.hashCode();

}

}

cmd/designated folder/ jar cf name.jar *.* Create a file: META-INF/MANIFEST.MF Add a line: Main-Class: com.myco.calc.CalculatorDemo Include META-INF/MANIFEST.MF in calculator.jar Run with java -jar calculator.jar

This is usefull in domain or value object class to compare different object fields in an equals method

public class DomainObject {

//protected because only inheriting domain classes can use it

protected boolean isPropertyEqual(Object compare1, Object compare2) {

// go here if compare1 is null, i.e. test cases 1 & 3

if (compare1 == null) {

if (compare2 != null) {

return false;

}

//go here if compare1 is not null, i.e. test cases 2 & 5

} else if (!compare1.equals(compare2)) {

return false;

}

return true;      //test cases 1 & 4

}

public static void main(String[] args) {

DomainObject d =  new DomainObject();

Print(d.isPropertyEqual(null, null));  //test case 1

Print(d.isPropertyEqual(“abc”, null)); //test case 2

Print(d.isPropertyEqual(null, “abc”)); //test case 3

Print(d.isPropertyEqual(“abc”, “abc”));//test case 4

Print(d.isPropertyEqual(“abc”, “cba”));//test case 5

}

public static void Print(boolean bol){

System.out.println(bol);

}

}

The above class must be abstract. It was not tagged abstract to demo via the main() method by creating a new DomainObject().

The above method can be used in an extending class like

public class Security extends DomainObject implements Serializable {

private String id;

//skipping other methods like getter/setter, toString, etc

public boolean equals(Object obj) {

if (this == obj) {

return true;

}

if (!(obj instanceof Security)) {

return false;

}

//calling super class handy method we just created

return isPropertyEqual(this.id, ((Security) obj).getId());

}

public int hashCode() {

return id.hashCode();

}

}

Why is explicit object casting needed?

In order to assign a superclass object in a variable to a subclass,one needs to do explicit casting.

For example:Person person=null;

Man man = (Man)person;

An automatic casting takes place when we typecast a object in subclass as parent class object.

Define Externalizable.

Externalizable is coined as an Interface

It extends the Serializable Interface.

It also sends data into the Streams.

Externalizable sends data in a Compressed Format.

Externalizable is having two methods,for e.g. writeExternal(ObjectOuput out) & readExternal(ObjectInput in)

What is the purpose of serialization?

Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link. The byte stream can then be deserialised – converted into a replica of the original object.

What is serialization and deserialization?-

Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

What is a transient variable?

A transient variable is a variable that may not be serialized.

What are Transient and Volatile Modifiers?-

Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

What is Marker interface? How is it used in Java?

The marker interface is a design pattern, used with languages that provide run-time type information about objects. It provides a way to associate metadata with a class where the language does not have explicit support for such metadata. To use this pattern, a class implements a marker interface, and code that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies methods that an implementing class must support, a marker interface does not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. There can be some hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used. Java utilizes this pattern very well and the example interfaces are:

  • io.Serializable – Serializability of a class is enabled by the class implementing the java.io.Serializable interface. The Java Classes that do not implement Serializable interface will not be able to serialize or deserializ their state. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
  • rmi.Remote – The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. Only those methods specified in a “remote interface”, an interface that extends java.rmi.Remote are available remotely.
  • lang.Cloneable – A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. Invoking Object’s clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.
  • servlet.SingleThreadModel – Ensures that servlets handle only one request at a time. This interface has no methods.
  • util.EvenListener – A tagging interface that all event listener interfaces must extend.
  • The “instanceof” keyword in java can be used to test if an object is of a specified type. So this keyword in combination with Marker interface can be used to take different actions based on type of interface an object implements.

What interface must an object implement before it can be written to a stream as an object

An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

How can a sub-class of Serializable super class avoid serialization? If serializable interface is implemented by the super class of a class, how can the serialization of the class be avoided

In Java, if the super class of a class is implementing Serializable interface, it means that it is already serializable. Since, an interface cannot be unimplemented, it is not possible to make a class non-serializable. However, the serialization of a new class can be avoided. For this, writeObject () and readObject() methods should be implemented in your class so that a Not Serializable Exception can be thrown by these methods. And, this can be done by customizing the Java Serialization process. Below the code that demonstrates it

class MySubClass extends SomeSerializableSuperClass {

private void writeObject(java.io.ObjectOutputStream out)

throws IOException {

throw new NotSerializableException(“Can not serialize this class”);

}

private void readObject(java.io.ObjectInputStream in)

throws IOException, ClassNotFoundException {

throw new NotSerializableException(“Can not serialize this class”);

}

private void readObjectNoData()

throws ObjectStreamException; {

throw new NotSerializableException(“Can not serialize this class”);

}

}