Wednesday, 21 October 2015

Java interview questions - level intermediate

This is the second in a series of articles on Java interview questions. These questions start to go into the details and differences of various parts of the language. Knowledge of them demonstrates a greater level of knowledge or experience than with the basics.
  1. Are static variables inherited by subclasses?
    Static variables are inherited by sub classes. However are at class level instead of object level and there is just one.
  2. Are static methods overridden by subclasses?
    That depends. If the reference used to store the object is of the super type, the super types static method is invoked. This is because static is at class level.
  3. What is the difference between a Set and a List?
    In a set an object can only exist once. In a List the same object can be added many times.
  4. Why should we use the @Override annotation?
    We should use this to ensure compile time checking that the contract of a subclass is not broken by changes to the superclass.
  5. What is the main difference between Callable interface and Runnable interface?
    The main difference is that the call method on callable can return a typed result, that can be queried in the future. Callable also throws an exception.
  6. Whats a covariant return?
    A covariant return is allowed since Java 1.5 and means that a method can return a sub classed object of the return type. In Java 1.4 and earlier the return type had to match exactly.
  7. What is an instance initialisation block? An instance initialisation block is run once after a new object is created. There can be as many of them in the class as you like, but they run in order declared from top to bottom in the class.
  8. Does an instance initialisation block run before or after the constructor?
    They run after the call to super, but before the rest of the constructor.
  9. What is auto boxing?
    It's the ability in Java to automatically switch between the primitive type and the object, without a call to a converter method.
  10. What is widening?
    It's the ability of Java to find a method with the smallest, closest java type. For example if one method takes a long and another takes an int, if I pass a short - java will automatically "widen" the short and select the method that taken an int.
  11. What is the difference between "&&" and "&"?
    && is a short circuit logical AND, this means that if the LHS evaluates to false, the RHS will not be evaluated. In & both the left and right sides are evaluate every time. For || only if the LHS equates to false, then the RHS side evaluated. When | is used, both the LHS and RHS are always evaluated.
  12. Dzone 20 things you should know about strings
  13. What’s the difference between shallow and deep cloning