Wednesday, 26 November 2014

JVM (Java Virtual Machine) Internal Structure

JVM (Java Virtual Machine)


JVMs are available for many hardware and software platforms (i.e.JVM is plateform dependent).JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.


What is JVM?

It is:
  1. A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
  2. An implementation Its implementation is known as JRE (Java Runtime Environment).
  3. Runtime Instance Whenever you write java command on the command prompt to run the java class, and instance of JVM is created.

What it does?

The JVM performs following operation:
  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment
JVM provides definitions for the:
  • Memory area
  • Class file format
  • Register set
  • Garbage-collected heap
  • Fatal error reporting etc.



1) Classloader:

Classloader is a subsystem of JVM that is used to load class files.

2) Class(Method) Area:

Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.

3) Heap:

It is the runtime data area in which objects are allocated.

4) Stack:

Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

5) Program Counter Register:

PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed.

6) Native Method Stack:

It contains all the native methods used in the application.

7) Execution Engine:

It contains:
1) A virtual processor
2) Interpreter:Read bytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term ?compiler? refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.




Wednesday, 19 November 2014

Core Java Basic Quetions

1. What is the base class of all classes?
java.lang.Object
2. Does Java support multiple inheritance?
Java doesn't support multiple inheritance.
3. Is Java a pure object oriented language?
Java uses primitive data types and hence is not a pure object oriented language.
4. Are arrays primitive data types?
In Java, Arrays are objects.
5. What is difference between Path and Classpath?
Path and Classpath are operating system level environment variales. Path is used define where the system can find the executables(.exe) files and classpath is used to specify the location .class files.


6. What are local variables?
Local varaiables are those which are declared within a block of code like methods. Local variables should be initialised before accessing them.


7. Which class is extended by all other classes?
The Object class is extended by all other classes.
8. Which non-Unicode letter characters may be used as the first character of an identifier?
The non-Unicode letter characters $ and _ may appear as the first character of an identifier
9. What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.
10. What is casting?
There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
11. What is the return type of a program's main() method?
void.

12. If a variable is declared as private, where may the variable be accessed?
A private variable may only be accessed within the class in which it is declared.

Friday, 7 November 2014

Java 8 Default Methods Tutorial

Java 8 Default Methods Tutorial

 

Interfaces in Java always contained method declaration not their definitions (method body). There was no way of defining method body / definition in interfaces. This is because historically Java didn’t allow multiple inheritance of classes. It allowed multiple inheritance of interfaces as interface were nothing but method declaration. This solves the problem of ambiguity in multiple inheritance. Since Java 8 it is now possible to add method bodies in interfaces.
Java 8 has a new feature called Default Methods. It is now possible to add method bodies into interfaces!
public interface Math {
    int add(int a, int b);
    default int multiply(int a, int b) {
        return a * b;
    }
}
In above Math interface we added a method multiply with actual method body.

Why we need Default Methods?

Why would one want to add methods into Interfaces? We’ll it is because interfaces are too tightly coupled with their implementation classes. i.e. it is not possible to add a method in interface without breaking the implementor class. Once you add a method in interface, all its implemented classes must declare method body of this new method.
Since Java 8, things started getting ugly. A new feature Lambda was introduce which is cool. However it is not possible to use this feature in existing Java libraries such as java.util package. If you add a single method in interface List, it breaks everything. You need to add its implementation in every class that implements List interface. Imagine in real world how many custom classes would change.
So for backward compatibility, Java 8 cleverly added Default Methods.

Virtual Extension Methods

It added a new concept Virtual extension methods, or as they are often called defender methods, can now be added to interfaces providing a default implementation of the declared behavior. So existing interfaces can be augmented without compromising backward compatibility by adding extension methods to the interface, whose declaration would contain instructions for finding the default implementation in the event that implementors do not provide a method body. A key characteristic of extension methods is that they are virtual methods just like other interface methods, but provide a default implementation in the event that the implementing class does not provide a method body.
Consider following example:
interface Person {
    //adds a java 8 default method
    default void sayHello() {
        System.out.println("Hello there!");
    }
}
class Sam implements Person {
}
public class Main {
     
    public static void main(String [] args) {
         
        Sam sam = new Sam();
         
        //calling sayHello method calls the method
        //defined in interface
        sam.sayHello();
    }
}
Output:
Hello there!
In above code we added a defender method sayHello() in Person interface. So it was ok for class Sam to avoid declaring this methods body.

What about Multiple Inheritance?

Adding method definitions in interfaces can add ambiguity in multiple inheritance. isn’t it? Well, it does. However Java 8 handle this issue at Compile type. Consider below example:
interface Person {
    default void sayHello() {
        System.out.println("Hello");
    }
}
interface Male {
    default void sayHello() {
        System.out.println("Hi");
    }
}
class Sam implements Person, Male {
}
In this example we have same defender method sayHello in both interfaces Person and Male. Class Sam implements these interfaces. So which version of sayHello will be inherited? We’ll if you try to compile this code in Java 8, it will give following error.


class Sam inherits unrelated defaults for sayHello() from types Person and Male class Sam implements Person, Male { ^ 1 error

So that solves multiple inheritance problem. You cannot implement multiple interfaces having same signature of Java 8 default methods (without overriding explicitly in child class).
We can solve the above problem by overriding sayHello method in class Sam.
interface Person {
    default void sayHello() {
        System.out.println("Hello");
    }
}
interface Male {
    default void sayHello() {
        System.out.println("Hi");
    }
}
class Sam implements Person, Male {
     
    //override the sayHello to resolve ambiguity
    void sayHello() {
     
    }
}
It is also possible to explicitly call method from child class to parent interface. Consider in above example you want to call sayHello method from Male interface when Sam.sayHello is called. You can use super keyword to explicitly call the appropriate method.
class Sam implements Person, Male {
     
    //override the sayHello to resolve ambiguity
    void sayHello() {
        Male.super.sayHello();
    }
}

Difference between default methods and abstract class

Ok, so far it looks good. In Java 8 we can have concrete methods within interfaces.. right.. So how it is different from Abstract classes? Remember an abstract class is a class that can not be instantiated (i.e. objects can not be created of) and which may contain method bodies. Default method in Java 8 looks similar to Abstract class isn’t it?
We’ll its different actually. Abstract class can hold state of object. It can have constructors and member variables. Whereas interfaces with Java 8 default methods cannot hold state. It cannot have constructors and member variables. You should still use Abstract class whenever you think your class can have state or you need to do something in constructor. Default method should be used for backward compatibility. Whenever you want to add additional functionality in an existing legacy interface you can use default methods without breaking any existing implementor classes.


Also abstract classes cannot be root classes in Lambda expression. What?… I know that’s confusing, but Lambda expressions are the reason why virtual extension methods were introduced in Java 8. When a lambda expression is evaluated, the compiler can infers it into the interface where default method is added.

Java Collection interview Questions Answers | Java Collection FAQ

Java Collection interview Questions Answers | Java Collection FAQ 




Java Collection Framework interview questions and answers contains questions from popular Java collection classes e.g. HashMap, ArrayList, HashSet, ConcurrentHashMap and legacy collection classes like Vector and Hashtable. Interview questions from Java Collection framework is one of the most asked concept on any Core Java interview or J2EE interview at both beginners, experienced and intermediate level e.g. 2 to 4 years experienced Java programmer. In order to answer interview questions from Java collection framework, You need a good knowledge of various Collection interfaces e.g. Map, List and Set and familiarities with there frequently used implementation e.g. HashMap, Hashtable, TreeMap  from Map, ArrayList, LinkedList and Vector for List interface and HashSet, TreeSet of Set interface. Questions related to Iterating collection , modifying Collection and thread-safety of Collection is also popular area from where Java collection interview Questions asked during interview. In this List of Java collection interview questions and answers, we will see questions from all above area. I have also included some questions from new Concurrent collection classes introduced in Java 5 e.g. ConcurrentHashMap and CopyOnWriteArrayList.

Java Collection interview Questions Answers


Here is list of my favoritefrequently asked Questions from Java collection framework. Almost all of these questions have appeared in Java interview at various level ranging from Junior to Senior software engineer level at different Companies e.g. Capegemini, Tech Mahindra, TCS , Satyam and CTS.

What is Difference between Hashtable and HashMap in Java?
This Java collection interview questions is I guess most popular one. Most of Java programmer who has at least 2 years of experience has seen this question on core Java or J2EE interview. Well there are many difference between them but most important is thread-safety, HashMap is not thread-safe while Hashtable is thread-safe collection. See Hashtable vs HashMap in Java for more differences between HashMap and Hashtable in Java.

What is difference between Hashtable and ConcurrentHashMap in Java?
Another frequently asked Java collection interview question post Java 5 world which introduced Concurrent Collection classes like ConcurrentHashMap and CopyOnWriteArrayList along with Concurrency utilities e.g. CyclicBarrier and CountDownLatch. Well both Hashtable and ConcurrentHashMap are thread-safe here but later provides more scalability than former. See Difference between ConcurrentHashMap and Hashtable in Java for answer of this Java collection interview question.

What is Difference between Iterator and Enumeration in Java?
One of the classic interview Questions asked on Java collection framework, This is pretty old and programmer who has been working in Java for 4 to 6 years must have seen this question before. Well Iterator and ListIterator in Java is a new way to iterator collection in Java and provides ability to remove object while traversing while Enumeration doesn't allow you to remove object. See Iterator vs Enumeration in Java for more differences between both of them.

What is Difference between fail-safe and fail-fast Iterator in Java?
This is relatively new Java collection interview question because concept of fail-safe iterator is come along with ConcurrentHashMap and CopyOnWriteArrayList. See Difference between fail-safe and fail-fast Iterator in Java for answer of this Java collection question.

How HashMap works internally in Java?
One of the most frequently asked Java interview question to experience Java programmer of 4 to 5 years of experience. I have seen this question on big companies like Morgan Stanley, JP Morgan, Nomura and other banks e.g. Barclays capital. See How HashMap works internally in Java for detailed answer of this Java collection interview question.

Can you write code to traverse Map in Java on 4 ways?
Another Java collection question which appear as part of Java Coding interview question and appeared in many interviews. As you know there are multiple ways to traverse or iterate Map in Java e.g. for loop, while loop using Iterator etc. 4 ways to iterator Map in Java has detailed explanation and sample code which is sufficient to answer this Java collection framework interview question.

What is difference between Vector and ArrayList in Java?
Along with Difference between HashMap and hashtable, this Java collection interview question is probably second in the list of frequently asked question on Java collection framework. Both ArrayList and Vector implements List interface from Java 4 but they have differences including synchronization, See difference between Vector and ArrayList in Java for complete answer of this collection interview question in Java.

What is difference between ArrayList and LinkedList in Java?
A follow-up question which is asked in response to previous Java collection interview question. Here also both LinkedList and ArrayList are List implementation but there internal data-structure is different, one is derived from Array while other is derived from LinkedList. See LinkedList vs ArrayList in Java to answer this Java Collection interview question.

What is difference between List and Set in Java ?
List vs Set is one of the most important concept to understand in Java Collection framework and this Java collection interview question focus on that. Most important difference between them is that List allows duplicates and maintain insertion order while Set doesn't allow duplicates and doesn't maintain any order. See Difference between Set and List in Java to see more differences between them

How do you find if ArrayList contains duplicates or not ?
Since List allows duplicates this becomes a followup question of earlier Java collection framework interview question. See How to check if ArrayList contains duplicates or not for answer of this Java collection question.

These were some of the frequently asked Java collection framework interview question you can also call them Java collection FAQ. Collection and Threads are most important part of Java programming language and considered as fundamentals of Java, So always prepare them well before appearing for any Java or J2EE interview. If you have any interesting Java collection interview question or are you looking answer for any Java collection question then please post here.

Top 10 tough core Java interview questions answers programming

tough core Java interview questions and answers
What is tough core java interview question ? Why do people look for tough Java questions before going for interview? well I don't thing I need to answer these tough questions because its pretty natural to prepare for tough questions even if you are not expecting tough questions from core Java. If you are prepare for tough and tricky Java interview question than you feel more confident and answer other Java interview question with confidence. On the other hand if you are not prepare for tough and tricky core Java questions than seeing them on Java interview or written test may surprise you. But definition of tough core Java questions is not universal, same Java question which is easy for one programmer might be tough for other Java programmer. That's why it's best to prepare your own list of tough interview questions before appearing on any Java job interview. In this article I am going to share you with my Top 10 tough core Java interview questions and answers, which may help you in Java interview.

10 tough Java interview question and answer

Here is my list of 10 tough or tricky Java interview questions. These questions are mostly from Core Java and I have not included J2EE questions. As I said you may know answers of these tough Java question or you may not even find it tough enough to challenge your Java knowledge but once upon a time these were asked in various Java interview and many programmer including my friends and colleagues finds them tough to answer.



Why wait and notify is declared in Object class instead of Thread ?
Another tough java question, how can you answer this question if you are not designed Java programming language. anyway some common sense and deep knowledge of Java programming helps to answer such tough core java interview question. See this blog post to learn  Why wait and notify is declared in Object class and not in Thread.


Why multiple inheritance is not supported in Java ?
I found this core Java question really tough to answer because your answer may not satisfy Interviewer, in most cases Interviewer is looking for specific points and if you can bring them, they would be happy. Key to answer this kind of tough question in Java is to prepare topic well to accommodate any follow-ups. See Why multiple inheritance is not supported in Java for answer of this tough Java question.


Why Java does not support operator overloading ?
One more similar category of  tough Java question. C++ supports operator overloading than why not Java? this is the argument Interviewer will give to you and some time even say that + operator is overloaded in Java for String concatenation, Don't be fooled with such arguments. See  Why support operator overloading is not supported in Java for detailed answer of this tricky Java question.

Why String is immutable in Java?
My favorite Java interview question, this is tough, tricky but same time very useful as well. Some interviewer also ask this question as Why String is final in Java. look at this post for some points which make sense on Why String is final or immutable in Java

Why char array is preferred to store password than String in Java?
Another tricky Java question which is based on String and believe me there are only few Java programmer which can answer this question correctly. This is a real tough core Java interview question and again solid knowledge of String is required to answer this. see Why char array is better than String for storing password in Java to find out answer of this tough Java question. 

How to create thread-safe singleton in Java using double checked locking?
This Java question is also asked as What is thread-safe singleton  and how to do you write it. Well Singleton created with double checked locking before Java 5 was broker and its possible to have multiple instance of Singleton if multiple thread try to create instance of Singleton at same time. from Java 5 its easy to create thread safe Singleton using Enum. but if interviewer persist with double checked locking then you have to write that code for them. remember to use volatile variable.  See 10 Java singleton interview question for more details on this topic.

Write Java program to create deadlock in Java and fix it ?
One of the classical but tough core Java interview question and you are likely to fail if you have not involved in coding of multi-threaded concurrent Java application. See  how to create and prevent deadlock in Java for complete answer of  this tough core Java interview question 

What happens if your Serializable class contains a member which is not  serializable? How do you fix it?
Any attempt to Serialize that class will fail with NotSerializableException, but this can be easily solved by making that variable transient for static in Java. See Top 10 Serialization interview question answers in Java for more details.



Why wait and notify  called from synchronized method in Java?
Another tough core Java question for wait and notify. They are called from synchronized method or synchronized block because wait and modify need monitor on Object on which wait or notify get called. See  Why wait and notify require synchronized context for complete answer of this tough and tricky Java multi-threading question.

Can you override static method in Java? if I create same method in subclass is it compile time error?

 
No you can not override static method in Java but its not a compile time error to declare exactly same method in sub class, That is called method hiding in Java. See  Can you override static method in Java for complete answer of this tough Java interview question.

These were my list of tough core Java interview question and answers. Some of the Java question doesn't look that tough for experience programmer but they are really tricky to answer for intermediate and beginners in Java. by the way if you have faced any tough Java question in interview then please share with us.


Top 12 Java Thread, Concurrency and Multithreading Interview Questions and How to Answers them

Java concurrency and thread interview questions answers
Multithreading is an important feature of Java programming language, which means threads are also important part of any Java interview, in fact at beginner and fresher level Thread interview questions in Java are most difficult to answer. One reason for interview question related to multithreading and concurrency being difficult is confusion around how multiple thread works together and second is threads are genuinely a complicated topic to understand and use correctly. Mostly thread interview questions checks Java programmers knowledge on Java Thread API, Java concurrency API, issues related to multi-threading like Race Conditionthread-safety and deadlock. Some time multithreading and concurrency interview question also focus on parallel design pattern related stuff like solving producer consumer problem, implementing work steal pattern or solving dining philosopher problem in Java. In this article, we will take a look at different kinds of multithreading and concurrency questions asked in various interviews e.g. on telephonic or face to face interview, on written test, to both experienced and senior Java developers, and some tips to answer them correctly. Questions asked on telephonic or first round of interviews are tend to be easier and you must answer them to the point with keyword, which interviewer is expecting. On face to face interview, be prepare for different kinds of follow-up questions. 

Java Interview questions on Concurrency and multithreading


As I said, in this Java article, not only,  I will share some of the most commonly asked thread interview question at freshers and beginners level, like upto 2 to 4 years of experience, and some tips and tricks to answer them correctly. By the way these thread interview questions are equally useful for senior Java developers or guys with some Java experience in hand. I tried to share answers of these interview questions on thread as well but I suggest you do some research and learn the topic well to answer any followup questions, which comes due to your response of these thread questions in Java. Anyway here are my collection of Java thread interview question and how to answers them in Java :

1) What is difference between start and run method in Java Thread?
This thread interview question is also ask as if start() method eventually call run() method than why do you need to call start() method, why not call run() method directly. well reason is that because start method creates a new thread and call the code written inside run method on new thread while calling run method executes that code on same thread. see start vs run method in Java for more details.

2) Write code to avoid deadlock in Java where n threads are accessing n shared resources?
This is a classic Java multithreading interview questions, which appears on almost every list of Java thread questions. This question is based on risk and issues faced by parallel programs without proper synchronization or incorrect synchronization. This question explores concept of looking and best practices on acquiring and releasing lock on shared resource. By the way it's been covered on many places as well and I suggest reading  How to prevent deadlock in Java, not only for detail answer of this Java multithreading question but also to learn how to prevent deadlock in Java.

3) Which one is better to implement thread in Java ? extending Thread class or implementing Runnable?
Well this is another frequently asked questions on any Java thread interview. Essentially these are two way to implement Thread in Java and by extending class you are using your chance to extend one any only one class as Java does not support multiple inheritance, by implementing Runnable interface you can still extend another class. So extending Runnable or even Callable is better choice. see Runnable vs Thread class in Java for more answers on this questions. Given it's simplicity and fact based nature, this question mostly appear on either telephonic round or initial screening rounds. Key points to mention, while answering this question includes, multiple inheritance at class level and separation of defining a task and execution of task. Runnable only represent a task, while Thread represent both task and it's execution.

4) What is Busy Spinning? Why you will use Busy Spinning as wait strategy?
This is really an advanced concurrency interview questions in Java and only asked to experienced and senior Java developers, with lots of concurrent coding experience under belt. By the way concept of busy spinning is not new, but it's usage with multi core processor has risen recently. It's a wait strategy, where one thread wait for a condition to become true, but instead of calling wait or sleep method and releasing CPU, it just spin. This is particularly useful if condition is going to be true quite quickly i.e. in millisecond or micro second. Advantage of not releasing CPU is that, all cached data and instruction are remained unaffected, which may be lost, had this thread is suspended on one core and brought back to another thread. If you can answer this question, that rest assure of a good impression.

5) What is difference between CountDownLatch and CyclicBarrier in Java?
CountDownLatch and CyclicBarrier in Java are two important concurrency utility which is added on Java 5 Concurrency API. Both are used to implement scenario, where one thread has to wait for other thread before starting processing but there is difference between them. Key point to mention, while answering this question is that CountDownLatch is not reusable once count reaches to zero, while CyclicBarrier can be reused even after barrier is broken. You can also see my previous article difference between CyclicBarrier and CountDownLatch in Java for more detailed answer of this concurrency interview question and a real life example of where to use these concurrency utilities.

6) Difference between wait and sleep in Java?
One more classic Java multithreading question from telephonic round of interviews. Key point to mention while answering this question is to mention that wait will release lock and must be called from synchronized context, while sleep will only pause thread for some time and keep the lock. By the way, both throws IntrupptedException and can be interrupted, which can lead to some followup questions like, can we awake a sleeping or waiting thread in Java? You can also read detailed answer on my post of same title here.

7) How do you solve producer consumer problem in Java?
One of my favorite questions during any Java multithreading interview, Almost half of the concurrency problems can be categorized in producer consumer pattern. There are basically two ways to solve this problem in Java, One by using wait and notify method and other by using BlockingQueue in Java. later is easy to implement and good choice if you are coding in Java 5. Key points to mention, while answering this question is threadsafety and blocking nature of BlockingQueue and how that helps, while writing concurrent code. You can also expect lots of followup questions including, what happen if you have multiple producer or multiple consumer, what will happen if producer is faster than consumer thread or vice-versa. You can also see this link for example of how to code producer consumer design in Java using blocking queue


8) Why ConcurrentHashMap is faster than Hashtable in Java?
ConcurrentHashMap is introduced as alternative of Hashtable in Java 5, it is faster because of it's design. ConcurrentHashMap divides whole map into different segments and only lock a particular segment during update operation, instead of Hashtable, which locks whole Map. ConcurrentHashMap also provides lock free read, which is not possible in Hashtable, because of this and lock striping, ConcurrentHashMap is faster than Hashtable, especially when number of reader is more than number of writers. In order to better answer this popular Java concurrency interview questions, I suggest reading my post about internal working of ConcurrentHashMap in Java.

9) What is difference between submit() and execute() method of Executor and ExecutorService in Java?
Main difference between submit and execute method from ExecutorService interface is that former return a result in form of Future object, while later doesn't return result. By the way both are used to submit task to thread pool in Java but one is defined in Executor interface,while other is added into ExecutorService interface. This multithreading interview question is also asked at first round of Java interviews.

10) How do you share data between two threads in Java?
One more Java multithreading question from telephonic round of interview. You can share data between thread by using shared object or shared data structures like Queue. Depending upon, what you are using, you need to provide thread-safety guarantee, and one way of providing thread-safety is using synchronized keyword. If you use concurrent collection classes from Java 5 e.g. BlockingQueue, you can easily share data without being bothered about thread safety and inter thread communication. I like this thread question, because of it's simplicity and effectiveness. This also leads further follow-up questions on issues which arises due to sharing data between threads e.g. race conditions. 

11) What is ReentrantLock in Java? Have you used it before?
ReentrantLock is an alternative of synchronized keyword in Java, it is introduced to handle some of the limitations of synchronized keywords. Many concurrency utility classes and concurrent collection classes from Java 5, including ConcurrentHashMap uses ReentrantLock, to leverage optimization. ReentrantLock mostly uses atomic variable and faster CAS operation to provides better performance. Key points to mention is difference between ReentrantLock and synchronized keyword in Java, which includes ability to acquire lock interruptibly, timeout feature while waiting for lock etc. ReentrantLock also gives option to create fair lock in Java.Once again a very good Java concurrency interview question for experienced Java programmers.

12) What is ReadWriteLock in Java? What is benefit of using ReadWriteLock in Java?
This is usually a followup question of previous Java concurrency questions. ReadWriteLock is again based upon lock striping by providing separate lock for reading and writing operations. If you have noticed before, reading operation can be done without locking if there is no writer and that can hugely improve performance of any application. ReadWriteLock leverage this idea and provide policies to allow maximum concurrency level. Java Concurrency API also provides an implementation of this concept as ReentrantReadWriteLock. Depending upon Interviewer and experience of candidate, you can even expect to provide your own implementation of ReadWriteLock, so be prepare for that as well.

These were some of my favorite interview questions based on multithreading and concurrent in Java. Threading and Concurrency is a big topic in Java and has lots of interesting, tricky and tough question but for starters and freshers these questions certainly help to clear any thread interview in Java. As I said, mentioning key points are very important while answering questions on multithreading and concurrency. I also suggest further reading on locking, synchronization, concurrent collections and concurrency utilities classes to do well in core Java and multithreading interviews.


Difference between Comparator and Comparable in Java - Interview Question

Comparator and Comparable are two interfaces in Java API, which is used to compare two objects in Java. Though both are used for comparison there are some difference between them, major difference between Comparable and Comparator is that former is used to define natural ordering of object e.g. lexicographic order for java.lang.String, while later is used to define any alternative ordering for an object.  Main usage of java.lang.Comparable and java.util.Comparator interface is for sorting list of objects in Java. For example to sort a list of Employee by there Id, we can use Comparable interface and to provide additional sorting capability, we can define multiple comparators e.g. AgeComparator to compare age of employee, SalaryComparator to compare salary of employees etc.  This brings another important difference between Comparator and Comparable interface in Java, you can have only one ordering via Comparable e.g. natural ordering, while you can define multiple Comparator for alternative ordering as discussed above. Coming to Interviews, this question is very common on 2 to 3 years experience Java interviews, and you just can't afford to not prepare this. It's definitely possible to achieve years of experience in Java, without writing your own Comparator or Comparable, especially if you are not doing active development or coding, but even though, you must know basics e.g. equals and hashcodecompareTo and compare. In this article, we will see some notable difference between Comparator vs Comparable in Java from interview perspective.

Comparator vs Comparable in Java


During interviews, you can face this question differently, if you are giving telephonic round than it's mostly fact based i.e. you need to mention key points about both interfaces, while in face to face interviews or during written test, you might be ask to write code to sort objects using Comparator and Comparable e.g. sorting employee by name or branch. I have already discussed second part of this question here and we will only see fact based differences in this post.

1. Comparator interface is in java.util package, which implies it's a utility class, while Comparable interface is kept on java.lang package, which means it's essential for Java objects.

2. Based on syntax, one difference between Comparable and Comparator in Java is that former gives us compareTo(Object toCompare), which accepts an object, which now uses Generics from Java 1.5 onwards, while Comparator defines compare(Object obj1, Object obj2) method for comparing two object.

3. Continuing from previous difference between Comparator vs Comparable, former is used to compare current object, represented by this keyword, with another object, while Comparator compares two arbitrary object passed to compare() method in Java.

4. One of the key difference between Comparator and Comparable interface in Java is that, You can only have one compareTo() implementation for an object, while you can define multiple Comparator for comparing objects on different parameters e.g. for an Employee object, you can use compareTo() method to compare Employees on id,  known as natural ordering, while multiple compare() method to order employee on age, salary, name and city. It's also a best practice to declare Comparator as nested static classes in Java, because they are closely associated with objects they compare. 

5. Many Java classes, which make uses of Comparator and Comparable defaults to Comparable and provided overloaded method to work with arbitrary Comparator instance e.g. Collections.sort() method, which is used to sort Collection in Java has two implementation, one which sort object based on natural order i.e. by using java.lang.Comparable and other which accepts an implementation of java.util.Comparator interface.

6. One more key thing, which is not a difference but worth remembering is that both compareTo() and compare() method in Java must be consistent with equals() implementation i.e. if two methods are equal by equals() method than compareTo() and compare() must return zero. Failing to adhere this guideline, your object may break invariants of Java collection classes which rely on compare() or compareTo() e.g. TreeSet and TreeMap.

That's all on difference between Comparator and Comparable in Java. Always remember that java.lang.Comparable is used to define natural ordering of an object, while java.util.Comparator can be used to define any ordering based upon your requirements. You can define only one ordering with Comparable but can have multiple Comparators. I strongly suggest to look my example of comparator vs comparable to gain more insight on how to use really use it in code. From Java interview point of view, I think, you are good to go if you know this much details.


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

Here 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 not guaranteed id is positive or negative. If id is 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 thing tricky and some consider very easy. StringBuilder in Java is introduced in Java 5 and only difference between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized. 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 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.



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.