Monday, September 10, 2012

Top 10 Tricky Java interview questions and Answers

Top 10 tricky Java interview questions and answers
Tricky Java interview questions are those question which has some surprise element on it and if you answer tricky Java question with common sense, you are likely to fail because they are tricky, they require something special to know. Most of the tricky Java questions comes from method overloading and overriding,  Checked and Unchecked Exception and subtle Java programming details like Integer overflow. Most important thing to answer tricky Java question is attitude and analytical thinking , which helps even if you don't know the answer. Anyway in this Java article we will see 10 Java questions which is real tricky and requires more than average knowledge of Java programming language to answer. As per my experience there are always one or two tricky or tough Java interview question on any core Java or J2EE interviews, so its good to prepare tricky questions from Java in advance.

10 Tricky Java interview question - Answered

Tricky Java interview question and answer for experienced programmerHere is my list of 10 tricky Java interview questions, Though I have prepared and shared lot of difficult core java interview question and answers, But I have chosen them as Top 10 tricky questions because you can not guess answers of this tricky java questions easily, you need some subtle details of Java programming language to answer these questions.

What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?
This is a very popular tricky Java question and its tricky because many programmer think that finally block always executed. This question challenge that concept by putting return statement in try or catch block or calling System.exit from try or catch block. Answer of this tricky question in Java is that finally block will execute even if you put return statement in try block or catch block but finally block won't run if you call System.exit form try or catch.

Can you override private or static method in Java ?
Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in Java.  Anyway, you can not override private or static method in Java, if you create similar method with same return type and same method arguments that's called method hiding. See Can you override private method in Java or more details.

Does Java support multiple inheritance ?
This is the trickiest question in Java, if C++ can support direct multiple inheritance than why not Java is the argument Interviewer often give. See Why multiple inheritance is not supported in Java to answer this tricky Java question.

What will happen if we put a key object in a HashMap which is already there ?
This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create confusing and tricky question in Java. well if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys. See How HashMap works in Java for more tricky Java questions from HashMap.

If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?
One more tricky Java questions from overloading and overriding concept. Answer is you can very well throw super class of RuntimeException in overridden method but you can not do same if its checked Exception. See Rules of method overriding in Java for more details.

What is the issue with following implementation of compareTo() method in Java

public int compareTo(Object o){
   Employee emp = (Employee) emp;
   return this.id - o.id;
}

where id is an integer number ?
Well three is nothing wrong in this Java question until you guarantee that id is always positive. This Java question becomes tricky when you can't guaranteed that id is positive or negative. tricky part is, If id becomes negative than subtraction may overflow and produce incorrect result. See How to override compareTo method in Java for complete answer of this Java tricky question for experienced programmer.

How do you ensure that N thread can access N resources without deadlock
If you are not well versed in writing multi-threading code then this is real tricky question for you. This Java question can be tricky even for experienced and senior programmer, who are not really exposed to deadlock and race conditions. Key point here is order, if you acquire resources in a particular order and release resources in reverse order you can prevent deadlock. See how to avoid deadlock in Java for a sample code example.

What is difference between CyclicBarrier and CountDownLatch in Java
Relatively newer Java tricky question, only been introduced form Java 5. Main difference between both of them is that you can reuse CyclicBarrier even if Barrier is broken but you can not reuse CountDownLatch in Java. See CyclicBarrier vs CountDownLatch in Java for more differences.

What is difference between StringBuffer and StringBuilder in Java ?
Classic Java questions which some people think tricky and some consider very easy. StringBuilder in Java was introduced in JDK 1.5 and only difference between both of them is that StringBuffer methods e.g. length(), capacity() or append() are synchronized while corresponding methods in StringBuilder are not-synchronized. Because of this fundamental difference, concatenation of String using StringBuilder is faster than StringBuffer. Actually its considered bad practice to use StringBuffer any more, because in almost 99% scenario, you perform string concatenation on same thread. See StringBuilder vs StringBuffer for more differences.

Can you access non static variable in static context?
Another tricky Java question from Java fundamentals. No you can not access non-static variable from static context in Java. If you try, it will give compile time error. This is actually a common problem beginners in Java face, when they try to access instance variable inside main method. Because main is static in Java, and instance variables are non-static, you can not access instance variable inside main. Read why you can not access non-static variable from static method to learn more about this tricky Java questions.

This was my list of 10 most common tricky question in Java . It's not a bad idea to prepare tricky Java question before appearing for any core Java or J2EE interview. One or two open ended or tricky question is quite common in Java interviews.

Other Java question and answer post
10 Java singleton design pattern interview question and answer
10 Java Generics interview questions for experienced programmer
15 multi-threading and concurrency interview question and answers for experienced developer
10 Java design pattern question asked in interviews
10 Java coding interview question answer for 2  to 4 years experience

32 comments:

  1. Great questions, How about adding tricky questions related to programming exercise ?

    ReplyDelete
    Replies
    1. One of the most tricky questions, I have face in a Java interview was, Does two object will always be equal, when there compareTo() method returns zero? I said, Yes, but that was not true. Though most of the classes will be equal if there compareTo() return true e.g. java.lang.String, but it's not mandatory. compareTo() may be inconsistent to equals(), which means compareTo() may return zero, but object will not be equal by equals() method. One of the prime example of this is java.math.BigDecimal class, whose equals() method return true if two BigDecimal object is equal in both value and scale e.g. 6.0 and 6.00 will not be equal, but compareTo() will return zero if both objects are compared. This was really tricky, until you had faced similar question previously. In another interview, my friend was asked this question little differently, Can we store BigDecimal class in TreeSet? obviously No, because of above reason, BigDecimal class can produce unexpected behavior when stored in SortedSet or SortedMap.

      Delete
  2. Good work done! It will definitely help me in my interviews... :)
    thanks .. :)

    ReplyDelete
  3. Hi ,

    I am able to override public static method declared in base class in its subclass.
    It didn't throw any compilation or runtime exception

    ReplyDelete
    Replies
    1. It won't because compiler will treat it as different method. This is called method hiding and its indeed one of the tricky Java question. Remember that this method is not overriding super class method as static method bonded using type information. That's the reason this Java question is tricky.

      Delete
  4. One of the tricky Java question I faced is "What is difference between Collection and Generics in Java", its not tricky because I don't know either collection or Generics but How can you compare Generics with Collection ?

    ReplyDelete
  5. Hi
    Is the line in codes correct.
    It's one of ur question.

    Can you access non static variable in static context?
    Another tricky Java question from Java fundamentals. "No you can not access static variable in non static context in Java". Read why you can not access non-static variable from static method to learn more about this tricky Java questions.

    ReplyDelete
    Replies
    1. Hi Ankur, Thanks for pointing out, you should read opposite i.e non static variable can not accessible from static context. This always confuse if you don't remember it and that's why its one of the tricky question.

      Delete
    2. Hi
      This line is not correct.
      "No you can not access static variable in non static context in Java".

      Delete
  6. all are tricky questions?

    ReplyDelete
  7. its really nice tricky question to read to face interview.

    ReplyDelete
  8. these are not tricky rather easy questions ...

    ReplyDelete
  9. i agree nice question to prepare before appearing for interview

    ReplyDelete
  10. These are definitely a good set of tricky questions that a candidate may face during an interview. I certainly enjoyed going through them but I have a different opinion regarding the last question: Can you access non static variable in static context?

    I think the answer to that question is a YES albeit one should note that you need an object reference of the associated class to access the variable (I assume this variable is an instance variable). And likewise you can directly access a static variable in non static context too. Please refer to this link for more information http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

    ReplyDelete
  11. Is the compareTo code correct ? the references look to be wrong.

    ReplyDelete
  12. The explanation of the last question is little bit confusing. Actually static variables are always accessible in non static context however the reverse is not true.

    ReplyDelete
    Replies
    1. In static context, you can access non-static variables - by creating a new instance of the object. Hence the reverse is partly true.

      Delete
  13. public int compareTo(Object o){
    Employee emp = (Employee) emp;
    return this.id - o.id;
    }

    I think this is what it should be...

    public int compareTo(Object o){
    Employee emp = (Employee) o;
    return this.id - o.id;
    }

    ReplyDelete
    Replies
    1. Wrong, it should be:

      public int compareTo(Object o){
      Employee emp = (Employee) o;
      return this.id - emp.id;
      }

      Delete
    2. I should also mention that you shouldn't cast to Employee without knowing it's an Employee via instanceof, or just using Comparable generic interface.

      Delete
  14. Q 1. about try and catch block
    class Main
    {
    public static void main(String args[])
    {

    try
    {
    int a=2/0;
    System.exit(0);
    }


    catch(Exception e)
    {

    System.out.println("i am in catch block");

    }

    finally
    {

    System.out.println("finally");
    }


    }
    }
    /*OUTPUT
    i am in catch block
    finally*/

    finally block get executed if we place System.exit(0) in try block

    ReplyDelete
    Replies
    1. Before calling System.exit(0) you raised excetion "int a=2/0".
      Onces system.exit(0) is called finally will never called.
      plz Don't confused others :)

      Delete
    2. 2/0 is arithmetic exception so before going to system.exit it will jump to catch block and then finally but once system.exit(0) executes ...finally will not execute then .. try it with
      class Main
      {
      public static void main(String args[])
      {

      try
      {
      int a=2/1;
      System.exit(0);
      }


      catch(Exception e)
      {

      System.out.println("i am in catch block");

      }

      finally
      {

      System.out.println("finally");
      }


      }
      }

      Delete
    3. as per my java knowledge,try,finally blocks will execute parallely,because if single statement(inside try block first line or empty block) is executed corresponding catch may or may not execute but finally block will execute automatically,otherwise it wont execute,so without try&catch blocks we cant write finally block in java.

      Delete
  15. I was asked during an interview the difference between "arraylist" and "linkedlist" and when I should use them
    Also, found a site where you can give online Java mock interviews. Its www.preparestreet.com

    ReplyDelete
  16. What is so tricky about these question, to me they look most simplest question, which doesn't even qualify for Interviews. Tricky questions are those, who challenge your notion e.g.

    When Singleton doesn't remain Singleton in Java?
    is it possible to load a class by two ClassLoader?
    is it possible for equals() to return false, even if contents of two Objects are same?
    Why compareTo() should be consistent to equals() method in Java?
    is Following code legal in Java? is it example of method overloading or overriding?

    public String getDescription(Object obj){
    return obj.toString;
    }

    public String getDescription(String obj){
    return obj;
    }

    and

    public void getDescription(String obj){
    return obj;
    }

    Anyone disagree with my questions not being tricky?

    ReplyDelete
    Replies
    1. Actually your questions are better than Javin's Questions...

      Delete
    2. Trickier) When do Double and BigDecimal give different answers for equals() and compareTo() == 0.

      Delete
  17. Hi,
    Good collection of tricky questions, However I feel that the questions in the interview becomes tricky because we need to answer the same as what interviewer in thinking is correct, this is the most tricky part. It is always better to clarify the question correctly by rephrasing it.

    ReplyDelete
  18. Some trickier questions.

    1a) how do you prevent a return statement from calling finally.
    1b) how do you make a System.exit() call the finally block.

    3) Not sure multiple inheritance is the trickest question in Java. How about;
    3a) how does "has before" apply to volatile work?
    3b) why is 0.1 * 3 != 0.3,
    3c) why is (Integer) 1 == (Integer) 1 but (Integer) 222 != (Integer) 222 and which command arguments change this.

    7) how can you release synchronized locks in an order which is not the reverse order? (You can do this BTW)

    Good answers to some common questions, I look forward to some trickier questions. ;)

    ReplyDelete
    Replies
    1. I would add :
      What happens when exception is thrown in a Thread?
      Difference between notify and notifyAll call?
      Difference between System.exit() and System.halt() method?

      do you agree these are much trickier question for an average Java programmers?

      Delete

Java67 Headline Animator