Core java interview questions and Answers for 5 - 7 Years Experience.

 Part 4

Core java interview questions and Answers for 5-7 Years Experience covered in this post:

    Core java interview questions and Answers for 5 - 7 Years Experience.

        What will be the impact if hashcode() method return constant value every-time? What will be the size of hashmap, In Employee class I have overridden equals and hashcode method and hashcode method always return 1. I have 5 employee objects in hashmap. What will be the size?

    -          You would lose any performance given by a hashmap, that can retrieve items from a collection in O(1) time for objects with different hashes, which is what we want to achieve when using HashMaps.

    -          If the equals method is implemented as per the contract and the hashcode method returns a constant value, then we will still be able to retrieve the value for the key from a hashMap, but the performance will be slow compared to the method returning a unique hashcode.

    -          The size would be 5.


        What will be the impact if I don't override equals() method?

    -          Only Override HashCode, Use the default Equals: Only the references to the same object will return true. In other words, those objects you expected to be equal will not be equal by calling the equals method.

    -          Only Override Equals, Use the default HashCode: There might be duplicates in the HashMap or HashSet. We write the equals method and expect {"xyz", "XYZ"} to be equals. However, when using a HashMap, they might appear in different buckets, thus the contains() method will not detect each other.


        Why String and wrapper classes are considered good keys?

    -          Strings and wrapper classes are immutable so immutable objects are really a good option for keys because once you insert the key’s hashcode never change throughout life.

    -          String and wrapper classes also overrides the equals() and hashcode() methods.

    -        Immutable objects are thread-safe this is an advantage as well.


        What is LinkedHashMap? Can you explain internal working of LinkedHashMap?

    -          LinkedHashMap is a data structure that preserves the insertion order and stores the objects in the form of key/value pair like a Hashmap.

    -          LinkedHashMap is a child class of Hashmap and implements a Map interface.

    -          LinkedHashMap is not a thread-safe.

    -          It can contain only one null key and multiple null values.

    -          It contains only unique elements.

    -          Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    import java.util.LinkedHashMap; 

    public class LinkedHashMapDemo { 

          public static void main(String[] args) {           

    LinkedHashMap<Integer, String> linkHm = new LinkedHashMap<Integer, String>();

                linkHm.put(100, "One Hundred");

                linkHm.put(200, "Two Hundred");

                linkHm.put(300, "Three Hundred");

                linkHm.put(500, "Five Hundred");

                linkHm.put(200, "Two Hundred");

                linkHm.put(100, "One Hundred");

                linkHm.put(null, "NULL Key");

                linkHm.put(600, null);

                linkHm.put(700, null);

                System.out.println(linkHm);

          }

    }

    Output: {100=One Hundred, 200=Two Hundred, 300=Three Hundred, 500=Five Hundred, null=NULL Key, 600=null, 700=null}


        Why map doesn't extends Collection interface?

    -          Map doesn’t extend the Collection interface because they are not compatible.

    -          Internal data structure of Collection implementations are like a list of objects and the internal data structure of the map is key-value pair.

    -          Collection implementations are index-based collections.

    -          Map is not an indexed based collection but it is key-value based collection.

    -          For adding objects to the collection we use add(Object o) method.

    -          For adding objects to the map we use the put(key, value) method.

    -          In the case of iterator, we directly put the iterator on the collection implementation class.

    -        But, In the case map, we have to put the iterator on the entry set.


        What is hash-collision in Hashtable and how will you handled in Collection API?

    -          Two different keys with the same hash value are known as hash-collision.

    -          Two separate entries will be kept in a single hash bucket to avoid the collision.

    -          There are two ways to avoid hash-collision. Separate Chaining and Open Addressing.

    1.       Separate Chaining:

    §  Keys are stored inside and outside the hashtable.

    §  Extra space is required for the pointers to store the keys outside the hashtable.

    §  Some buckets of the hash table are never used which leads to wastage of space.

    §  Cache performance is poor. This is because of linked lists which store the keys outside the hash table.

    2.       Open Addressing:

    §  All the keys are stored inside only in the hash table. No key is present outside the Hashtable.

    §  No extra space is required.

    §  Buckets may be used even if non-mapped keys to those particular buckets.

    §  Cache performance is better. This is because there is no linked lists are used.


        Which data structure has implemented for HashMap?

    -          Hashtable data structure has been implemented for HashMap.

     

        Which data structure has implemented for TreeMap?

    -          RED-BLACK Tree data structure has been implemented for TreeMap.


        Can I convert Map into List?

    -          We can convert the map into a List.

    -          But we have to create a different list for the key set and value set.

    -          Please refer to the below examples.

     

    package simplifiedjava.crackedInterview; 

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.List; 

    public class ConvertMapToList { 

          public static void main(String[] args) {

                HashMap<Integer, String> hMap = new HashMap<Integer, String>();

                hMap.put(1, "One");

                hMap.put(10, "Ten");

                hMap.put(100, "Hundred");

                hMap.put(1000, "Thousand");           

                List<Integer> keyList = new ArrayList<Integer>(hMap.keySet());

                List<String> valueList = new ArrayList<String>(hMap.values());           

                System.out.println("Key List "+ keyList);

                System.out.println("Value List "+ valueList);

          }

    }

    Output:

    Key List [1, 100, 1000, 10]

    Value List [One, Hundred, Thousand, Ten]

     


        Can you write a code to iterate a hashMap object?

    -          We can iterate Hashmap couple of ways.

    1.       The first way is we can collect keyset and iterate the map and print the vales.

    2.       The second way is we can collect the entry set and iterate map and print the values.

    package simplifiedjava.crackedInterview; 

    import java.util.HashMap;

    import java.util.Iterator;

    import java.util.Map; 

    public class HashMapIteratorDemo { 

          public static void main(String[] args) {

             HashMap<Integer, String> hMap = new HashMap<Integer, String>();

                hMap.put(1, "One");

                hMap.put(10, "Ten");

                hMap.put(100, "Hundred");

                hMap.put(1000, "Thousand");          

             System.out.println("========== Using eySet===========");           

                Iterator itr1 = hMap.keySet().iterator();

                while(itr1.hasNext()) {

                      Integer key = (Integer) itr1.next();

              System.out.println("Key : "+ key + "\t Value : "+ hMap.get(key));

                }           

                System.out.println("========== Using EntrySet===========");

                Iterator itr2 = hMap.entrySet().iterator();

                while(itr2.hasNext()) {

                      Map.Entry<Integer, String> pair = (Map.Entry<Integer, String>)itr2.next();

                      System.out.println("Key : " + pair.getKey()+ "\tValue : "+ pair.getValue());

                }

          }

    }

    Output:

    =============== Using KeySet===============

    Key : 1       Value : One

    Key : 100     Value : Hundred

    Key : 1000    Value : Thousand

    Key : 10      Value : Ten

    =============== Using EntrySet===============

    Key : 1       Value : One

    Key : 100     Value : Hundred

    Key : 1000    Value : Thousand

    Key : 10       Value : Ten




    • Java interview questions and answers all MNC - Click here
    • Basic core java interview questions and answers for freshers - Click here
    • Core java interview questions for 3 years experience - Click here
    • Core java interview questions and answers for 3-5 years exp - Click here
    • Core java interview questions and Answers for 5 - 7 Years exp - Click here
    • Basic Java Interview Questions and Answers - Click here
    • Java interview questions and answers on oops - Click here
    • Java interview questions and answers on Strings - Click here
    • Java interview questions on exception handling - Click here
    • Interview questions on multithreading in java for experienced - Click here
    • Interview questions on serialization in java for experienced - Click here

    • Interview questions on inner class in java for experienced - Click here
    • Interview questions on Collections in java for experienced - Click here



    Upcoming questions in next post:

    41. What is the difference between Iterator and Enumarator.

    42. What is the ListIterators and why do we require ListIterators in Collection framework.

    43. What is the Enumarator and why do we require Enumarator in Collection framework.

    44. Can I perform remove operation while iterating CopyOnWriteArrayList object.

    45. What will happen if I am trying to perform remove operation while iterating CopyOnWriteArrayList.

    46. What the the new methods introduced in CopyOnWriteArrayList to performing read and write operation.

    47. What is the difference between ArrayList and ArrayList<?> in Java?

    48. Can I add other object than String in following snippet. ArrayList<String> list = new ArrayList<String>();

    49. WAP to break singleton using Deserialization? How to prevent Singleton to break with Deserialization?

    50. WAP to break singleton using Cloning? How to prevent Singleton to break with Cloning?

    51. What is the difference between Web Application and Enterprise Application?

    52. What are SOLID Principle?



    Previous Post                                                                    Next Post



    Thank you techies for visiting this blog. I hope you enjoyed this blog and got more technical knowledge. I have tried to cover all types of questions and provided examples tested on eclipse as much as I can. Guys, please don’t just mug up the questions and answers. Try to clear your concepts with examples. Try to write a code on eclipse once you read the concepts. It will help you to memorize the concepts for a very long time. Simultaneously you will be prepared for interview programs as well. It will help you to survive in the IT sector for a long time. It may be easy to crack an interview but it's really tough to survive in the IT industry with inadequate knowledge and skills. 

    I have collected all the questions from actual interviews attended by my friends, colleagues, college mate and classmate. I have covered frequently asked questions as well as challenging questions. I have included many programs to understand the concept thoroughly. I will try to explain the concept with the help of a real-time program in eclipse. 

    You can share more questions which are not covered in this blog or post. Always welcome your suggestions and queries. I will definitely try to resolve it. 

    Please comment your queries and new set of questions under the comment sections. I will create a new post for those questions. 

    My total experience is 10. Initially I had worked on some support projects and then I moved to java projects. I had worked with many multi-national companies like R-Systems, Tata Consultancy Services, Cybage Softwares.  Fortunately, TCS and Cybage has given me an opportunity to take interviews for experienced candidates. I have conducted more than 1000 interviews by now.

    Mock sessions will be conducted for minimal charges. I will guide you personally on how to crack interviews. All sessions will be online sessions only. My interview book will be provided free of cost if you enroll for personal training. Once you have done practice then I assured you will definitely crack almost all java interviews. 

    I have published my book named with "All MNC Java Interview" which is available on amazon. You can go through it or you can directly contact to me if you are interested to read the book. I will give you special discount. I have covered near about 550 questions and answers with program tested on eclipse and necessary diagram. 

    I have covered interview questions asked in all reputed MNC like TCS, Infosys, Capgemini, Tech Mahindra, Cognizant, City Bank, Barclays, Amdocs, Mindtree etc. My purpose behind this book is, help you to get a job in your dream company. I can understand this is a struggling period for job seekers and freshers. Everybody must have gone from this phase. so never give up. Keep upgrading yourself. I am sure you will get a job in your dream company. All the best!!! 

    Please reach out to me for personal training for interview preparation. 

    You can reach out to me at mncjavainterview@gmail.com.

     


    Post a Comment

    0 Comments