Sunday, February 7, 2016

Java interview questions


1. What is re-entrant lock? Difference between re-entrant lock and synchronized keyword?

2. Use of CountDownLatch, CyclicBarrier, Semaphore, Re-entrant Lock?

3. Difference between Iterator and for loop

Source: https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

for-each loop really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, below example,
--------------------
void exampleMethod(Collection<String> c) {

for (Iterator<String> i = c.iterator();

i.hasNext();

if (i.next().length() == 40)

i.remove();

}
--------------------
The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.

3. Order of execution of static class level blocks, class level block and constructor.
4. Which is better interface or 100% Abstract Class and why? 
5. Return statement in try, catch and finally. 
6. Abstract class constructor.
7. Cloneable Interface.
8. How to write immutable class? What about having data object? why the class is made final?
9. What constructs JVM?
10. What happens when Thread1 is running locking obj1 and Thread2 is wating for obj1. And Thread1 throws exception?
11. Serialization? How to de-serialize a singleton object? How to make subclass not serializable though its super is serializable?
12. What implements Decorator pattern? One example?
13. What changes between Java 1.5 vs Java 1.6?
14 What is Concurrent HashMap?  How it is improving performance than synchronizedMap?
What is the method to increment segment size?
15. What is the difference between wait and sleep method in Java?
Ans:
a. wait call should be made  from synchronized context but not mandatory for sleep.
b. If wait acquires any lock say obj1 then it will release the lock(monitor) temporarily so that notifying thread continue. It will acquire the lock again once the other threads notifies the thread(calling wait method). but sleep will hold the lock(until interrupted).



Will update more questions soon. Please feel free to make comments on the answer.

No comments:

Post a Comment