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)




http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
http://www.coderfriendly.com/wp-content/uploads/2009/05/java_collections_v2.pdf


Now we can select proper collection based on the following:
Image source:http://www.sergiy.ca/guide-to-selecting-appropriate-map-collection-in-java/


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(arrayToStort)
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: http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html#ixzz1s6uz8EHW 


Question: How does HashMap work in java?
Answer: http://javarevisited.blogspot.in/2011/02/how-hashmap-works-in-java.html


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.
Approach1
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)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
        it.remove(); // avoids a ConcurrentModificationException
    }
}

We can also get both separately as:
Approach2

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()) {
    // ...
}

Approach3

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: http://stackoverflow.com/questions/1066589/java-iterate-through-hashmaphttp://www.sergiy.ca/how-to-iterate-over-a-map-in-java


More Questions:
http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html#ixzz1s6wwFuVh
http://www.fromdev.com/2008/05/java-collections-questions.html

12 comments:

emi_me said...

hey check this new website www.countcode.com. 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 http://www.wiziq.com/course/1779-core-and-advance-java-concepts 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.

hariprasad p said...

Hi,
Thanks for sharing the info about CORE JAVA Plz keep sharing on...
Thank you...

Ganesh Ponna said...

OlĂ ,


Smokin hot stuff! You’ve trimmed my dim. I feel as bright and fresh as your prolific website and blogs!


I am building a request using URL connection. Before making a connection to the server I need to check if the URL requested server is same server. If it is same then I need to call locally Instead of making URL connection.Anyways great write up, your efforts are
Much
appreciated.


Shukran,

Ganesh Ponna said...

Hola,


What a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this.

I have two methods and they do almost same thing, but at some most inner nested level one of method have additional command.

Java Code:
method2(){
... same code ...
for {
... same code ...
if{
... same code ...
}
}
}






Follow my new blog if you interested in just tag along me


in any
social media platforms!


Shukran,

Riya karakoti said...

Really a good post, thanks for sharing .keep it up.

Best Web Design Training Institutes in Noida

Best Hadoop Training Institutes In Noida

Best Digital Marketing Training Institute in Noida

Sap Training Institute in Noida

Best Java Training Institute in Noida

SAP SD Training Institute in Noida

Best Auto CAD Training Institute In Noida

aashutosh webtrackker said...

Salesforce Training Institute in Noida

Salesforce Training in noida

Best Salesforce Training Institutes in Noida

Best Aws Training Institutes in Noida

best aws training in noida

aws training institute in noida

best data science training institute in delhi

python Training Institute in noida

sas Training Institute in noida

linux Training Institute in noida




Arvind Rawat said...

Each department of CAD have specific programmes which, while completed could provide you with a recognisable qualification that could assist you get a job in anything design enterprise which you would really like.

AutoCAD training in Noida

AutoCAD training institute in Noida


Best AutoCAD training institute in Noida