Top 20 collection framework interview questions and answers in java

Java collections interview questions:
collections interview questions

1.Why Map interface doesn’t extend Collection interface?

  • Set is unordered collection and does not allows duplicate elements.
  • List is ordered collection allows duplicate elements.
  • Where as Map is key-value pair.
  • It is viewed as set of keys and collection of values.
  • Map is a collection of key value pairs so by design they separated from collection interface.


2.What is difference between HashMap and Hashtable?

  • Synchronization or Thread Safe 
  • Null keys and null values 
  • Iterating the values 
  •  Default Capacity 
hashmap vs hashtable

    Click here for the
    Differences between HashMap and Hash-table

    3.Differences between comparable and comparator?

    • Comparable Interface is actually from java.lang package.
    • It will have a method compareTo(Object obj)to sort objects
    • Comparator Interface is actually from java.util package.
    • It will have a method compare(Object obj1, Object obj2)to sort objects
    Read more :  comparable vs comparator

    4.How can we sort a list of Objects?

    •  To sort the array of objects we will use  Arrays.sort() method.
    • If we need to sort collection of object we will use Collections.sort().

    5.What is difference between fail-fast and fail-safe?

    • Fail fast is nothing but immediately report any failure. whenever a problem occurs fail fast system fails. 
    • in java Fail fast iterator while iterating through collection of objects sometimes concurrent modification exception will come there are two reasons for this.
    • If one thread is iterating a collection and another thread trying to modify the collection.
    • And after remove() method call if we try to modify collection object



    6. What is difference between Iterator ,ListIterator and Enumeration?

    • Enumeration interface implemented in java 1.2 version.So Enumeration is legacy interface.
    • Enumeration uses elements() method.
    • Iterator is implemented on all Java collection classes.
    • Iterator uses iterator() method.
    • Iterator can traverse in forward direction only.
    • ListIterator is implemented only for List type classes
    • ListIterator uses listIterator() method.
    Read more :  

    What is difference between Iterator ,ListIterator and Enumeration?

    7.What is difference between Set and List in Java?

    • A set is a collection that allows unique elements.
    • Set does not allow duplicate elements
    • Set allows only one null value.
    • Set having classes like :
    • HashSet
    • LinkedHashSet
    • TreeSet
    • List having index. and ordered  collection
    • List allows n number of null values.
    • List will display Insertion order with index.
    • List having classes like :
    • Vector
    • ArrayList
    • LinkedList

    8.Differences between arraylist and vector?

    • Vector was introduced in  first version of java . that's the reason only vector is legacy class.
    • ArrayList was introduced in java version1.2, as part of java collections framework.
    • Vector is  synchronized. 
    • ArrayList is not synchronized.

    9.What are the classes implementing List interface?

    • ArrayList     
    • LinkedList     
    • Vector

    10. Which all classes implement Set interface ?

    • HashSet
    • LinkedHashSet
    • TreeSet

    11.How to make a collection thread safe?

    • Vector, Hashtable, Properties and Stack are synchronized classes, so they are thread-safe and can be used in multi-threaded environment.
    • By using Collections.synchronizedList(list)) we can make list classes thread safe.
    • By using 
      java.util.Collections.synchronizedSet()  we can make set classes thread safe.

    12.Can a null element added to a TreeSet or HashSet?

    • One null element can be added to hashset.
    • TreeSet does not allow null values

    13. Explain Collection’s interface hierarchy?


    Collections interview Questions and answers java

    14.Which design pattern Iterator follows?

    • Iterator design pattern

    15.Which data structure HashSet implements

    • Hashset implements hashmap internally.

    16.Why doesn't Collection extend Cloneable and Serializable?

    • List and Set and queue extends Collection interface.
    • SortedMap extends Map interface.

    17.What is the importance of hashCode() and equals() methods? How they are used in Java?

    • equals() and hashcode() methods defined in "object" class. 
    • If equals() method return true on comparing two objects then hashcode() of those two objects must be same.

    18.What is difference between array & arraylist?

    • Array is collection of similar type of objects and fixed in size.
    • Arraylist is collection of homogeneous and heterogeneous elements.

    19.What is the Properties class?

    • Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key and the value is String.

    20.How to convert a string array to arraylist?

    • ArrayList al=new ArrayList( Arrays.asList( new String[]{"java", "collection"} ) ); 
    •  arrayList.toArray(); from list to array


    22.Java Collection framework programming interview questions 



    1. Print prime numbers? 
    2. Java Program Find Second highest number in an integer array 
    3. Java Interview Program to find smallest and second smallest number in an array 
    4. Java Coding Interview programming Questions : Java Test on HashMap  
    5. Constructor chaining in java with example programs 
    6. Swap two numbers without using third variable in java 
    7. Find sum of digits in java 
    8. How to create immutable class in java 
    9. AtomicInteger in java 
    10. Check Even or Odd without using modulus and division  
    11. String Reverse Without using String API 
    12. Find Biggest substring in between specified character
    13. Check string is palindrome or not?
    14. Reverse a number in java? 
    15. Collections interview questions and programs
     For more interview programs: Top 40 java interview programs


    Final static string vs Static string in java

    Static final variable java example:

    • If we declare any variable as static means it is class level variable.
    • If we declare any variable as static final its class level variable and its value can not be changed 
    • final static variables are constants in java.
    • We can access these final static variables directly without using object or class name.
    • We can not change the value of final static variables in any object.

    java example program on final static variable 

    1. Class A{
    2.  
    3. public static final String str="Learn Java Online";
    4.  
    5.  public static void main(String[]  args){ 

    6. System.out.println(str); 
    7.  //str="j2ee Interview Questions"; gives error

    8. }
    9. }

    Output:
    1. Learn Java Online

    Static String:

    • static Strings are class level strings.
    • we can access these static Strings using class name.


    1. Class A{
    2.  
    3. public static String str="Learn Java Online";
    4.  
    5.  public static void main(String[]  args){ 

    6. System.out.println(A.str); 
    7. System.out.println(str);
    8.  

    9. }
    10. }



    Output:
    1. Learn Java Online
    2. Learn Java Online

    Essential Classes of Java

    • Lets discuss about what are the common functionalities everyone needs when developing a application and what are the classes we require mostly to rectify common problems.

    Exceptions:

    •  Exception classes are very important in every java project,
    • Finding the places where the chances of occurring exception and placing in try and in catch block assigning to corresponding exception class or super class of all exceptions Exception.
    1. Checked Exceptions
    2. Unchecked Exceptions
    3. Errors

    Basic IO:

    •  Basic input and output operations covered by java platform classes focuses on IO streams and serialization.
    I/O Streams:
    1.     Byte Streams are provided to handle I/O of raw binary data.
    2.     Character Streams handles I/O of character data
    3.     Buffered Streams optimize input and output by reducing the number of calls to the native API.
    4.     Scanning and Formatting allows a program to read and write the formatted text.
    5.     I/O from the Command Line describes the Standard Streams and the Console object.
    6.     Data Streams will handle the binary I/O Strings and primitive data types
    7.     Object Streams provided to handle binary I/O of all objects.

     Concurrency:

    • Will Explains how to build applications which perform multiple tasks simultaneously.
    • Java Platform having full support to concurrent programming 
    • In JDK 5 Java introduces high level concurrent programming APIs.
    • Like java.util.concurrent packages. 

      The Platform Environment 

    • To examine and configure java environment java provides classes and libraries.
    • JVM and Java class libraries
    • Configuration Utilities describes APIs used to access configuration data supplied when the application is deployed, or by the application's user.
    • System Utilities describes miscellaneous APIs defined in the System and Runtime classes.
    • PATH and CLASSPATH describes environment variables used to configure JDK development tools and other applications.
    • Here the List of  commonly used java classes

    1. java.lang.Exception
    2. java.lang.System
    3. java.lang.String
    4. java.util.ArrayList
    5. java.util.HashMap
    6. java.lang.Object
    7. java.lang.Thread
    8. java.lang.Class
    9. java.util.Date
    10. java.util.Iterator



    Can we override private method in java

    • We can not override private methods in java.
    • The basic inheritance principle is when we are extending a class we can access all non private members of a class so private members are private to that class only we can not access anywhere outside the class if we declare anything as private.
    • Know more information about access specifiers here

    1. Class A{
    2.  
    3.   int a;
    4.  private int b;
    5.  
    6. public void print(){
    7.  
    8. System.out.println("print method of super class A"); 

    9. }
    10.  
    11. private void add(){
    12.  
    13. System.out.println("add method of super class A"); 

    14. }
    15. }
    16. Class B extends A{
    17.  
    18. public void show(){
    19.  
    20.  System.out.println("show method of sub class B"); 

    21. }
    22. public static void main(String[] args){
    23.   
    24. B obj= new B();
    25. obj.a=30;
    26.  
    27. obj.print();
    28. obj.show();

    29.  System.out.println("a="obj.a); 
    30. //obj.b=20;  compile time error. The field Super.a is not visible
    31. //obj.add(); compile time error : The method show() from the type Super is not visible

    32. }
    33. }



    Output:
    1. print method of super class  A
    2. show method of sub class B
    3. 30


    • From the above program we can say super class private members are not accessible to sub class.
    • lets see what will happen if we try to override a method of super class?
    • Sorry if we are unable to access super class private methods then there should not be a questions of overriding that method right?
    • Yes private methods of super class can not be overridden in sub class.
    • Even if we try to override same method of super class that will became a sub class own method not overridden method.


    1. Class A{
    2.  
    3.   int a;
    4.  private int b;
    5.  
    6. private void add(){
    7.  
    8. System.out.println("add method of super class A"); 

    9. }
    10. }
    11. Class B extends A{
    12.  
    13. private void add(){
    14.  
    15.  System.out.println("add method of sub class B"); 

    16. }
    17. public static void main(String[] args){
    18.   
    19. B obj= new B();
    20. obj.a=30;
    21.  
    22. obj.add();


    23.  System.out.println("a="obj.a); 

    24. }
    25. }

    Output:
    1. add method of sub class B
    2. 30

    • We can prove this by providing @override annotation in sub class method 

    1. Class A{
    2.  
    3.   int a;
    4.  private int b;
    5.  
    6. private void add(){
    7.  
    8. System.out.println("add method of super class A"); 

    9. }
    10. }
    11. Class B extends A{
    12.  //@override
    13. private void add(){// if we place @override annotation compile time error will come here
    14.  
    15.  System.out.println("add method of sub class B"); 

    16. }
    17. public static void main(String[] args){
    18.   
    19. B obj= new B();
    20. obj.a=30;
    21.  
    22. obj.add();


    23.  System.out.println("a="obj.a); 

    24. }
    25. }

    Output:
    1. add method of sub class B
    2. 30

    Can we call sub class methods using super class object

    • Common coding interview question everybody facing in interviews is can we call sub class method using super class object? or can we call child class method using parent class? or can a super class call a subclass' method.
    • The answer is No. but still we can say yes. so we need to what are all those scenarios of calling sub class method from super class and lets discuss about which is the actual possible case to call sub class method using super class object.
    • Before that let me explain what is inheritance and how the super and sub classes related each other.
    Can we call sub class methods using super class object.png

    Inheritance:

    •  Getting the properties from one class object to another class object is known as inheritance.
    • Two types of inheritance
    • Getting the properties from one class object to another with level wise and with some priorities is known as multilevel inheritance.
    • Getting the properties from one class object to another class object with same priority is known as multiple inheritance
    • Java does not supports multiple inheritance
    Read this:

    Why Java does not supports multiple inheritance

    Creating super class object and calling methods

    1. //Multilevel inheritance program
    2. Class A{
    3.  
    4. int a;
    5.  
    6. public void print(){
    7.  
    8. System.out.println("print method of super class A"); 

    9. }
    10.  
    11. }
    12. Class B extends A{
    13.  
    14. public void show(){
    15.  
    16.  System.out.println("show method of sub class B"); 

    17. }
    18. public static void main(String[] args){
    19.   
    20. A obj= new A();
    21. obj.a=10;
    22.  
    23. obj.print();
    24.  //obj.show(); // compile time error

    25.  System.out.println("a="obj.a); 

    26. }
    27. }



    Output:
    1. print method of super class  A
    2. 10

    • In above program super class and sub class is there and sub class extending super class.
    • But we created object for super class so we can call only super class methods on that object.
    • If we create sub class object we can call super class and sub class methods on that object now we can able to access super class A methods only.
    • So by creating super class object we can call only super class methods

    Creating super class object and calling methods

    1. //Multilevel inheritance program
    2. Class A{
    3.  
    4. int a;
    5.  
    6. public void print(){
    7.  
    8. System.out.println("print method of super class A"); 

    9. }
    10.  
    11. }
    12. Class B extends A{
    13.  
    14. public void show(){
    15.  
    16.  System.out.println("show method of sub class B"); 

    17. }
    18. public static void main(String[] args){
    19.   
    20. B obj= new B();
    21. obj.a=10;
    22.  
    23. obj.print();
    24. obj.show();

    25.  System.out.println("a="obj.a); 

    26. }
    27. }

    Output:
    1. print method of super class  A
    2. show method of sub class B
    3. 10


    • Above program shows sub class object using super class methods and variables as we said in inheritance concept all super class members can accessed by the sub class means all super class members are available to sub class if sub class extending super class.
    • So whenever we create object of sub class it will call sub class constructor and from sub class constructor super class constructor will be called so memory will be allocated to all super class non static member and sub class non static members.
    • So we can call super class methods using sub class.
    • B obj= new B();
    • obj.print();
    • So by creating sub class object we can call both super class methods and sub class methods.


     Assigning sub class reference to super class object.

    1. //Multilevel inheritance program
    2. Class A{
    3.  
    4. int a;
    5.  
    6. public void print(){
    7.  
    8. System.out.println("print method of super class A"); 

    9. }
    10.  
    11. }
    12. Class B extends A{
    13.  
    14. public void show(){
    15.  
    16.  System.out.println("show method of sub class B"); 

    17. }
    18. public static void main(String[] args){
    19.   
    20. A obj= new B();
    21. obj.a=10;
    22.  
    23. obj.print();
    24. //obj.show(); // compile time error

    25.  System.out.println("a="obj.a); 

    26. }
    27. }

    Output:
    1. print method of super class  A
    2. 10


    • Yes we can assign sub class object to super class reference.
    • So here Sub class object is created so memory allocated to all super class members
    • so can we call all methods ?  No eventhough sub class object is created we can not call sub class methods because we assigned sub class object to super class reference.
    • Then how its possible to call sub class methods?
    • Yes its possible to call sub class methods using super class by type casting to sub class object .
    • By type casting super class object to sub class object we can access all corresponding sub class and all super class methods on that reference.


     Assigning sub class reference to super class object.

    1. //Multilevel inheritance program
    2. Class A{
    3.  
    4. int a;
    5.  
    6. public void print(){
    7.  
    8. System.out.println("print method of super class A"); 

    9. }
    10.  
    11. }
    12. Class B extends A{
    13.  
    14. public void show(){
    15.  
    16.  System.out.println("show method of sub class B"); 

    17. }
    18. public static void main(String[] args){
    19.   
    20. A obj= new B();
    21. obj.a=10;
    22.  
    23. obj.print();
    24. //obj.show();   compile time error
    25. ((B)obj).show(); // works fine


    26.  System.out.println("a="obj.a); 

    27. }
    28. }

    Output:
    1. print method of super class  A
    2. show method of sub class B
    3. 10

     Assigning sub class reference to super class object. We can call sub class methods if overridden

    Otherwise we need to typecast to call sub class methods

    1. //Multilevel inheritance program
    2. Class A{
    3.  
    4. int a;
    5.  
    6. public void print(){
    7.  
    8. System.out.println("print method of super class A"); 

    9. }
    10.  
    11. }
    12. Class B extends A{
    13.  
    14. public void show(){
    15.  
    16.  System.out.println("show method of sub class B"); 

    17. }
    18. public void print(){
    19.  
    20. System.out.println("Print method of Sub class B"); 

    21. }
    22.  
    23. public static void main(String[] args){
    24.   
    25. A obj= new B();
    26. obj.a=10;
    27.  
    28. obj.print(); // print method is overridden in sub class so it will execute sub class method.
    29. //obj.show();   compile time error
    30. ((B)obj).show(); // works fine


    31.  System.out.println("a="obj.a); 

    32. }
    33. }

    Output:
    1. Print method of Sub class B
    2. show method of sub class B
    3. 10

    Static class in java

    • Yes we can create a class as static. But class should be inner class or nested class.
    • We know how to create static methods, static variables and static blocks.
    • As Java Supports defining a class within a class we can create a static inner class inside a class.
    • This inner static class inside a class can access static members of outer class even its private.

    Java Program to create static inner class:


    1. package instanceofjavaTutorial;
    2.  
    3. public class Outer{ 
    4.  
    5.   static class inner{
    6.  
    7. public void print(){
    8.  
    9. System.out.println("static inner class method called");
    10.  
    11. }
    12.  
    13. }
    14.  
    15. public static void main(String args[]){
    16.  
    17. Outer.inner in= new Outer.innner();
    18.  
    19. in.print();
    20.  
    21. }

    Output:

    1. static inner class method called



    Static inner class accessing outer class static variable:

    1. package instanceofjavaTutorial;
    2.  
    3. public class Outer{ 
    4.  static int a=10;
    5.   static class inner{
    6.  
    7. public void print(){
    8.  
    9. System.out.println(a);
    10.  
    11. }
    12.  
    13. }
    14.  
    15. public static void main(String args[]){
    16.  
    17. Outer.inner in= new Outer.innner();
    18.  
    19. in.print();
    20.  
    21. }

    Output:

    1. 10

    • In java there are two types of nested classes one is static and another one is non static nested classes.
    • We saw static classes in java lets see what will be there in non static nested classes.
    Non-static nested class(inner class)
    1. Member inner class
    2. Anonymous inner class
    3. Local inner class

    • A class is defined within a class and outside of methods of that class known as member inner class.
    • Anonymous inner class is a inner class which does not have a name and whose instance is created at the time creating class itself.
    • A class which is defined inside a method of another class known as local inner class

    Click here for more information about inner classes

    Java Versions, Features and History


    Java Versions, Features and History

    • Released on 23 January 1996, JDK 1.0 version.
    • Released on 19 February 1997 JDK 1.1 version.
      New features in JDK 1.1
      1. JDBC (Java Database Connectivity)
      2. Inner Classes
      3. Java Beans
      4. RMI (Remote Method Invocation)
      5. Reflection (introspection only)
    • Released on 8 December 1998 J2SE 1.2 version.
      New features in J2SE 1.2
      1. Collections framework.
      2. Java String memory map for constants.
      3. Just In Time (JIT) compiler.
      4. Jar Signer for signing Java ARchive (JAR) files.
      5. Policy Tool for granting access to system resources.
      6. Java Foundation Classes (JFC) which consists of Swing 1.0, Drag and Drop, and Java 2D class libraries.
      7. Java Plug-in
      8. Scrollable result sets, BLOB, CLOB, batch update, user-defined types in JDBC.
      9. Audio support in Applets.
    • Released on 8 May 2000 J2SE 1.3 version.
      New features in J2SE 1.3
      1. Java Sound
      2. Jar Indexing
      3. A huge list of enhancements in almost all the java area.
    • Released on 6 February 2002 J2SE 1.4 version.
      New features in J2SE 1.4
      1. XML Processing
      2. Java Print Service
      3. Logging API
      4. Java Web Start
      5. JDBC 3.0 API
      6. Assertions
      7. Preferences API
      8. Chained Exception
      9. IPv6 Support
      10. Regular Expressions
      11. Image I/O API
    • Released on 30 September 2004 J2SE 1.5 version.
      New features in J2SE 1.5
      1. Generics
      2. Enhanced for Loop
      3. Autoboxing/Unboxing
      4. Enum
      5. Varargs
      6. Static Import
      7. Metadata (Annotations)
      8. Instrumentation
    • Released on 11 December 2006 J2SE 1.6 version.
      New features in J2SE 1.6
      1. Scripting Language Support
      2. JDBC 4.0 API
      3. Java Compiler API
      4. Pluggable Annotations
      5. Native PKI, Java GSS, Kerberos and LDAP support.
      6. Integrated Web Services.
      7. Lot more enhancements.
    • Released on 28 July 2011 J2SE 1.7 version.
      New features in J2SE 1.7
      1. Strings in switch Statement
      2. Type Inference for Generic Instance Creation
      3. Multiple Exception Handling
      4. Support for Dynamic Languages
      5. Try with Resources
      6. Java nio Package
      7. Binary Literals, underscore in literals
      8. Diamond Syntax
      9. Automatic null Handling


    • Released on 18th march 2014 JDK 1.8 version.
      New features in JDK 1.8
               

    1. Default and Static methods in Interface
    2. Lambda Expressions
    3. Optional
    4. Streams
    5. Method References
    6. Data Time API
    7. Nashorn Javascript Engine
    8. Parallel Arrays

    Select Menu