Sunday, April 15, 2012

Core Java Interview Questions [Part 2]

You can check part one here. The previous post covered basic questions. This one covers some intermediate level questions. And YES all Comments/feedbacks are weclomed :)

Question: What are various Collections in Java?
Answer: In Java we have the following core interfaces: Collection, List, Set, Queue, Map, SortedSet, SortedMap, NavigableSet, NavigableMap. We can use the following to remember:

CLQ SM(Sorted,Navigable)

Now we can select proper collection based on the following:
Image source:

Question: What is the difference between collection, Collection and Collections?
Answer: collection: It represents any of the data structures in which objects are stored and iterated over.
Collection: It represents the java.util.Collection interface.
Collections: It is java.util.Collections class that holds a pile of static utility methods for use with collections.

Question: What are the various implementation classes for collections?
Answer: The three list implementations are: ArrayList, Vector and LinkedList. ArrayList implements the new RandomAccess interface (marker interface) and good for fast iteration but not good for frequent insertion/deletion. Vectors are thread safe but slow. In linked list elements are ordered by index position and elements are doubly linked.
The three set implementation are HashSet, LinkedHashSet and TreeSet. HashSet is unordered, unsorted set and uses the hashcode of the object being inserted. A LinkedHashSet is an ordered version that maintains a doubly linked list of elements. Both of them need hashCode() to be overridden else default method from Object class will be called. TreeSet is sorted collection and uses red-black tree ad implements NavigableSet.
The four implementations of Map are HashMap, Hashtable, LinkedHashMap and TreeMap. HashMap allows one null key and many null values. Hashtable is synchronized counterpart to HashMap (like vector). Hashtable does not have anything null. LinkedHashMap maintains insertion order but slower than HashMap for adding/removing elements. TreeMap is sorted by natural order of elements by default but can be customized to use Comparable/Comparator.
The priority class implements Queue interface to create a "priority-in, priority out" opposed to typical FIFO. The elements are ordered according to either natural ordering or according to comparator.

Question: What are comparable and comparator interfaces.
Answer: Both the interfaces are used to compare. If our class implements comparable then it defines natural ordering of that Object. If it implements Comparator then it defines its own way to compare two objects and may not align with the natural ordering. For sorting we have Arrays.sort() which is overridden like Collections.sort() and both of its variants are static.
Arrays.sort(arrayToSort, Comparator)

Using Comparable
public class Person implements Comparable {
    private int person_id;
    private String name;

     * Compare current person with specified person
     * return zero if person_id for both person is same
     * return negative if current person_id is less than specified one
     * return positive if specified person_id is greater than specified one
    public int compareTo(Person o) {
        return this.person_id - o.person_id ;

Using Comparator
public class PersonSortByPerson_ID implements Comparator{

    public int compare(Person o1, Person o2) {
        return o1.getPersonId() - o2.getPersonId();
[examples taken from  the following link.]

Read more: 

Question: How does HashMap work in java?

Question: What is the difference when String is created using literal or new operator()
Answer:When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.

Question: How can we convert a HashMap to Array?
Answer: We can use the following code:
hashMap.keySet().toArray(); // returns an array of keys
hashMap.values().toArray(); // returns an array of values

Question: What are the various ways to access HashMap?
Answer: If we want to access both keys and values then using entry set is the best option. We can use for-each loop or iterator.
Using for-each loop

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

Using Iterator

public static void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry);
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
        it.remove(); // avoids a ConcurrentModificationException

We can also get both separately as:

for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...

But if we want to remove the items in between then using iterator is better option, but simply changing values is OK with this approach. If we want to access only keys/values then we can use:

Map<String, Object> map = ...;
for (String key : map.keySet()) {
    // ...

for (Object value : map.values()) {
    // ...


If we want to save few lines of code then one smart way is:

for (String key : hashMap.keySet()) {
    System.out.println("Key: " + key + ", Value: " + map.get(key));

Adapted from:

More Questions:


emi_me said...

hey check this new website It's a social network made for programmers, where you can download,share or upload source codes, where you can count your own code lines for free. You have access to the web forum and the web chatroom. we are happy to have you joined to our community!

Smith said...

Good Questions and great work.

sarabjeet said...

i really like that you are giving information on core and advance java concepts. Being enrolled at i found your information very helpful indeed.thanks for it.

Path Infotech said...

Thanks for sharing the information

Ocp Certification

Sujitkumar said...

Nice blog. Really helpful information about Java …. Please keep update some more…………

venu puram said...

Thank you for providing the java interview questions, As I have done my PMP Course in Kuwait I was well examined in Java oriented Projects with in effective to many other specific programming languages.