Java Interview Questions


Some of the most common interview questions I generally ask Java programmers. For more comprehensive list, check Java Interview Questions

Q) What is polymorphism?

Ans) The ability to define a function in multiple forms is called Polymorphism. In java,c++ there are two types of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding). Method overriding Overriding occurs when a child class implements the method with the same signature as a method in a 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 but different number or type of parameters.

  • Overloading is determined at the compile time.
  • Different method signature and different number or type of parameters.
  • Same method signature but the 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 the difference between final, finally and finalize() in Java?

Ans) final – A final variable acts as a constant, a final class is immutable and a final method cannot be overridden while doing inheritance.

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 belongs to Object class. The method that is invoked while doing the garbage collection of the object. It could be used for allowing it to clean up its state. Good use cases will be to free connection pools, deallocate resources etc.

Q)What is the difference between HashMap and HashTable?

Ans) Both collections implement 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 is the 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. An 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 doesn’t 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 it’s not compulsory to implement all methods.
  • The issue with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement the new 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 boolean 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 overridden like for String class. equals() method can be used to compare the values of two objects.

String str1 = "MyName"; 
String str2 = "MyName";
String str3 = new String(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

Q) What is the difference between an ArrayList and a Vector?

Ans)

  • Synchronization – ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block, thus making Vector class thread-safe.
  • Data growth – Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of capacity. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
  • Performance the Since vector is thread-safe, the performance is slower than ArrayList.

Q) Which all classes implement Set interface ?

Ans) A Set is a collection that contains no duplicate elements. More formally, a set contains no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet, SortedSet and TreeSet are the commonly used class which implements Set interface.

  • SortedSet – It is an interface which extends Set. A the name suggest, the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
  • TreeSet – It is the implementation of SortedSet interface. This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized. The class uses Red-Black tree data structure.
  • HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets

Q) Describe the exception hierarchy in Java?

Ans) The hierarchy is as follows:

java exception hierarchy

Throwable is a parent class of all Exception classes. There are two types of Exceptions: Checked exceptions and UncheckedExceptions or RunTimeExceptions. Both type of exceptions extends Exception class.