Interface Java Interview Questions – Set 06

When can an object reference be cast to an interface reference

An object reference be cast to an interface reference when the object implements the referenced interface.

What is a cloneable interface and how many methods does it contain

?– It is not having any method because it is a TAGGED or MARKER interface.

What is casting?

There are two types of casting, casting between primitive numeric types and casting between object references.

Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values.

Casting between object references is used to refer to an object by a compatible class, interface, or arraytype reference.

What are packages ?

Packages group related classes and interfaces together and thus avoiding any name conflicts. From OOP’s point of view packages are useful for grouping related classes together. Classes are group together in a package using “package” keyword.

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”);

}

}

Why is Serialization required? What is the need to Serialize

Serialization is required for a variety of reasons. It is required to send across the state of an object over a network by means of a socket. One can also store an object’s state in a file. Additionally, manipulation of the state of an object as streams of bytes is required. The core of Java Serialization is the Serializable interface. When Serializable interface is implemented by your class it provides an indication to the compiler that java Serialization mechanism needs to be used to serialize the object.

What is the difference between ArrayList and LinkedList? (ArrayList vs LinkedList.

when the internal array fills up. The arrayList has to create a new array and copy all the elements there. The ArrayList has a growth algorithm of (n*3)/2+1, meaning that each time the buffer is too small it will create a new one of size (n*3)/2+1 where n is the number of elements of the current buffer. Hence if we can guess the number of elements that we are going to have, then it java.util.ArrayList and java.util.LinkedList are two Collections classes used for storing lists of object references Here are some key differences:

  • ArrayList uses primitive object array for storing objects whereas LinkedList is made up of a chain of nodes. Each node stores an element and the pointer to the next node. A singly linked list only has pointers to next. A doubly linked list has a pointer to the next and the previous element. This makes walking the list backward easier.
  • ArrayList implements the RandomAccess interface, and LinkedList does not. The commonly used ArrayList implementation uses primitive Object array for internal storage. Therefore an ArrayList is much faster than a LinkedList for random access, that is, when accessing arbitrary list elements using the get method. Note that the get method is implemented for LinkedLists, but it requires a sequential scan from the front or back of the list. This scan is very slow. For a LinkedList, there’s no fast way to access the Nth element of the list.
  • Adding and deleting at the start and middle of the ArrayList is slow, because all the later elements have to be copied forward or backward. (Using System.arrayCopy()) Whereas Linked lists are faster for inserts and deletes anywhere in the list, since all you do is update a few next and previous pointers of a node.
  • Each element of a linked list (especially a doubly linked list) uses a bit more memory than its equivalent in array list, due to the need for next and previous pointers.
  • ArrayList may also have a performance issue makes sense to create a arraylist with that capacity during object creation (using construtor new ArrayList(capacity)). Whereas LinkedLists should not have such capacity issues.

What is HashMap and Map

Map is Interface which is part of Java collections framework. This is to store Key Value pair, and Hashmap is class that implements that using hashing technique.

What is the difference between Map and Hashmap

Map is Interface and Hashmap is class that implements that

What are some of the best practices relating to the Java Collection framework

Best practices relating to Java Collection framework are as follow:

  • Choose the right type of data structure based on usage patterns like fixed size or required to grow, duplicates allowed or not, ordering is required to be maintained or not, traversal is forward only or bi-directional, inserts at the end only or any arbitrary position, more inserts or more reads, concurrently accessed or not, modification is allowed or not, homogeneous or heterogeneous collection, etc. Also, keep multi-threading, atomicity, memory usage and performance considerations discussed earlier in mind.
  • Don’t assume that your collection is always going to be small as it can potentially grow bigger with time. So your collection should scale well.
  • Program in terms of interface not implementation: For example, you might decide a LinkedList is the best choice for some application, but then later decide ArrayList might be a better choice for performance reason.
    • Bad:
      • ArrayList list = new ArrayList(100);
    • Good:

// program to interface so that the implementation can change

  • List list = new ArrayList(100);
  • List list2 = new LinkedList(100);
  • Return zero length collections or arrays as opposed to returning a null in the context of the fetched list is actually empty. Returning a null instead of a zero length collection is more error prone, since the programmer writing the calling method might forget to handle a return value of null.
    • List emptyList = Collections.emptyList( );
    • Set emptySet = Collections.emptySet( );
  • Use generics for type safety, readability, and robustness.
  • Encapsulate collections: In general, collections are not immutable objects. So care should be taken not to unintentionally expose the collection fields to the caller. The caller may not perform any necessary validation.