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

27 comments:

Smith said...

Good Questions and great work.

Sujitkumar said...

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

Unknown 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.

Unknown 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,

Unknown 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,

manisha said...


Thank you for sharing such great information very useful to us.
Java Training in Noida

geniusit said...



Nice blog..! I really loved reading through this article... Thanks for sharing such an amazing post with us and keep blogging...
msbi training in Hyderabad
msbi training in Pune
msbi training in Bangolore
msbi training in Hyderabad

Seetha said...

Such a wonderful blog




Which of the Following Numbers is not Divisible by 14
Error the Specified Value for Setting Medialoyout is Invalid While Installing SSMS From Command Line
BRAC Interview Questions and Answers Part1
Write the Test Cases on Prime Number With Result
Pointing Out to a Photograph Swathi said he is the Uncle of My Brothers Sister
How to Merger Two ar Static Libraries into One
Java Sample Resume 7 Years Experience
Find the Value of Log a2 bc
Hungarian Clothing
What is Javascripts Highest Interger Value that a Number can go to Without Losing Precision

jay it Solutions said...

Thanks for sharing such an amazing post with us and keep blogging...
Amazing web journal I visit this blog it's extremely marvelous. Interestingly,
in this blog content composed plainly and reasonable. The substance of data is educational.

ajay said...
This comment has been removed by the author.
ajay said...

amazing web journal I visit this blog it's extremely marvelous.
Interestingly, in this blog content composed plainly and reasonable.
For latest and Best Institute for IT software's i recommend
Tosca Training in Hyderabad

Raj Sharma said...

Good Post. I like your blog. Thanks for Sharing
Core Java Training Course in Noida

globalcoach academy said...

Thanks for sharing this post with us and keep blogging,

python training in hyderabad
SAP training in hyderabad

mind q said...

Usually, I never comment on blogs but your article is so convincing that I never stop myself to say something about it. I really like this post and Enjoyed reading the article above, really explains everything in detail, the article is very interesting and effective. I am also providing coaching on angular js Angular training in Hyderabad just go through the link

MindQ Systems provides Training on Angular js, Angular2, Angular4, Angular5, Angular6, Angular7, Angular8. Mind Q provides Classroom Training, Online Training and video course for Angular Training. Mindq provides Training with an expert Trainer. Enroll now and schedule a demo session with the trainer.
angular js

Unknown said...

Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
workday studio online training

Aruna said...

Excellent Information's are shared...The persistence of This Blogs about JAVA give's a successful Result in feature...keep sharing
Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

Aruna said...
This comment has been removed by the author.
shankarjaya said...

Thank you for the time to publish this information very useful! I've been looking for books of this nature for a way too long. I'm just glad that I found yours. Looking forward for your next post. Thanks
Salesforce Training in Chennai | Certification | Online Course | Salesforce Training in Bangalore | Certification | Online Course | Salesforce Training in Hyderabad | Certification | Online Course | Salesforce Training in Pune | Certification | Online Course | Salesforce Online Training | Salesforce Training

Best Training Institute said...

This concept is a good way to enhance the knowledge.thanks for sharing. please keep it up
Java Microservices training in bangalore
Java Microservices class in bangalore

Anonymous said...

Very informative. Thanks for sharing.
Best Bike Taxi Service in Hyderabad
Best Software Service in Hyderabad
Electric Vehicle Charging Stations

Jon Hendo said...

tools that automate and scale events personalize attendee experiences and deliver positive ROI. event marketing and thank you letter for hosting an event

Kaparthicynixit said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
Core Java Online Training Hyderabad
http://ruchi-myseleniumblog.blogspot.com/2013/12/basic-core-java-interview-questions.html

Hi Every One said...

Avast SecureLine VPN License Key software is unconscious of the sites the user accesses. Each application is freely used without any fear of recording. Avast VPN Crack

syedhaseeb said...

Windows Vista Ultimate Activation Key's Backup and Restore Utility, Windows Desktop Gadgets, Microsoft's Mail Application, .https://cyberspc.com/windows-vista-product-key/

vcube said...
This comment has been removed by the author.
vcube said...

I appreciate you providing this useful post...
devOps training in hyd

Ankit said...

In the realms of technology, the past few decades have been marked by an unprecedented surge of innovation. From the advent of the internet to the proliferation of smartphones, each advancement has reshaped the way we live, work, and interact with the world around us. However, as we stand on the brink of a new era, it is artificial intelligence (AI) that holds the key to unlocking the full potential of future technologies.
Ai In Future Technology