Welcome Java interview questions

Some miscellaneous top pick.

Q) What is use of serialVersionUID?

Ans) During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type
Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass's computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.

Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:

  • Add fields
  • Change a field from static to non-static
  • Change a field from transient to non-transient
  • Add classes to the object tree

List of incompatible changes:

  • Delete fields
  • Change class hierarchy
  • Change non-static to static
  • Change non-transient to transient
  • Change type of a primitive field

So, if no suid is present, inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used .

The only way to get rid of the exception is to recompile and deploy the application again.

If we explicitly mention the sUid using the statement:
private final static long serialVersionUID = <integer value>

then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.

Q) Why static methods cannot access non static variables or methods?

Ans) A static method cannot access non static variables or methods because static methods doesnt need the object to be accessed. So if a static method has non static variables or non static methods which has instantiated variables they will no be intialized since the object is not created and this could result in an error.

Q) Does the order in which the value of the transient variables and the state of the object using the defaultWriteObject() method are saved during serialization matter?

Ans) Yes, while restoring the object’s state the transient variables and the serializable variables that are stored must be restored in the same order in which they were saved.

Q) What is the difference between final, finally and finalize() in Java?

Ans) final - declaread as constant. A final variable act as constant, a final class is immutable and a final method cannot be ovrriden.

finally - handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block (except System.exit(0) call). Use the finally block to close files or to release other system resources like database connections, statements etc.

finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

Q) What is polymorphism?

Ans)Polymorphism gives us the ultimate flexibility in extensibility. The abiltiy to define more than one function with the same name is called Polymorphism. In java,c++ there are two type of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding). Mehtod overriding Overriding occurs when a class method has the same name and signature as a method in parent class. When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time.

Overloading occurs when several methods have same names with

  • Overloading is determined at the compile time.
  • Different method signature and different number or type of parameters.
  • Same method signature but different number of parameters.
  • Same method signature and same number of parameters but of different type
Example of Overloading
int add(int a,int b)
   float add(float a,int b)
   float add(int a ,float b)
   void add(float a)
   int add(int a)
   void add(int a) //error conflict with the  method int add(int a)
class BookDetails{
  String title;
  setBook(String title){}
}
class ScienceBook extends BookDetails{
  setBook(String title){} //overriding
  setBook(String title, String publisher,float price){} //overloading
}

Q)What is difference between HashMap and HashTable?

Ans) Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are

  1. Hashmap is not synchronized in nature but hashtable is.
  2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
    Fail-safe -if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException?
  3. HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.

Q) What are the classes implementing List interface?

Ans) There are three implementation of List interface:

  1. ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.
  2. Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.
  3. LinkedList: the LinkedList implements Queue interface too and provide FIFO (First In First Out) operation for add operation. It is faster than ArrayList if its mainly used forinsertion and deletion of elements.

Q) >What is difference between abstract class and interface?

Ans)

  • A class is called abstract when it contains at least one abstract method. It can also contain n numbers of concrete method.Interface can contain only abstract( non implemented) methods.
  • The abstract class can have public,private,protect or default variables and also constants. In interface the variable is by default public final. In nutshell the interface doesnt have any variables it only has constants.
  • A class can extend only one abstract class but a class can implement multiple interfaces.
  • If an interface is implemented its compulsory to implement all of its methods but if an abstract class is extended its not compulsory to implement all methods.
  • The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass.

Q) What is the difference between equals() and ==?

Ans) == operator is used to compare the references of the objects.
public bollean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. But since the method can be overriden like for String class. equals() method can be used to compare the values of two objects.

String str1 = "MyName"; 
String str2 = "MyName";
String str3 = str2;

if(str1 == str2){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
if(str1.equals(str2)){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}

Output:
Objects are not equal
Objects are equal
String str2 = "MyName";
String str3 = str2;
if(str2 == str3){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
if(str3.equals(str2)){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}

Output:
Objects are equal
Objects are equal