Collection Framework Tutorial

Limitations of Arrays:

  • Arrays are fixed in size. need to estimate the size of an array while declaration itself. once array created we can not increase the size of an array.
  • Arrays can hold only homogeneous data elements. Means we can add same type of elements in an array. While declaring an array we need to mention the data type.
  • int a[]= new int[10];
  • By using Object array we can add heterogeneous elements to the array.
  • Object o= new Object[10];
  • There is no underlying data structure for arrays.
  • Arrays are not recommended to use with respect to memory.
  • Performance wise arrays are good to use.

Collections 

  • Java Collection framework added in J2SE 1.2 release.
  • Collections are set of classes and interfaces.
  • By using Collections we can store and manipulate objects easily.
  • Collections can hold heterogeneous data elements.
  • Collections are no fixed in size and dynamically increase in size.
  • Collection of objects. No primitives.
  • All collection classes having underlying data structure.
  • Collections are good with respect to memory. Bad with respect to performance.

Collection interface Hierarchy:

  •  java.util package contains all collections classes and interfaces.
  • Lets see collection interface hierarchy.
  • under Collection. Set , List , Queue are the sub interfaces.

Collection interface Hierarchy

Collections Abstract classes and classes:

  • Let us see  all the abstract classes implementing all the above interfaces and classes which extending these abstract classes.
  • To Collect Objects in array format we choose Collection hierarchy classes.
  • Main abstract class is AbstractCollection.
  • AbstractSet
  • AbstractList
  • AbstractQueue
  • AbstractSequentialList
  • All the classes in Collection hierarchy are
  • TreeSet
  • HashSet
  • LinkedHashSet
  • LinkedList
  • ArrayList
  • Vector
  • Stack
  • PriorityQueue 
  • To collect unique elements we must choose Set implemented classes
  • To collect unique and duplicate elements in indexed order we choose List implemented classes.
  • To retrieve elements in FIFO manner we choose Queue implemented classes.

Collection interview Questions

Map Hierarchy:

  • In this hierarchy Hashtable and properties classes are avilable since java 1.0.
  • LinkedHashMap class is available since java 1.4
  • NavigableMap is available since java 6 and all other classes available since java 1.2.
  • SortedMap and NavigableMap are two main interfaces.
  • TreeMap
  • HashMap
  • LinkedHashMap
  • Hashtable
  • Properties are the classes. 
  • To collect objects in key, value pair format we choose Map hierarchy classes.


Collection Map Hierarchy tutorial


Difference between error and exception in java

  • Exception and Error both are sub classes of java.lang.Throwable class.
  • We can handle Exceptions at runtime but Errors we can not handle.

  • Exceptions are the objects representing the logical errors that occur at run time and makes JVM enters into the state of  "ambiguity".
  • The objects which are automatically created by the JVM for representing these run time errors are known as Exceptions.
  • An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
  • An error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Examples of errors include OutOfMemoryError, StackOverflowError, and NoClassDefFoundError. An exception, on the other hand, is a subclass of Throwable that indicates conditions that a reasonable application might want to catch. Examples of exceptions include IOException, SQLException, and NullPointerException.
  • Exceptions are used to indicate that a problem occurred that the application can handle, while errors indicate that a more serious problem has occurred that the application cannot handle.
  • Exceptions are events that are triggered by the code you write, such as a null pointer reference or a file that cannot be found. When an exception occurs, the program will stop executing and the control will be transferred to an exception handler. You can catch exceptions using try-catch blocks and handle them appropriately.
  • Errors, on the other hand, are typically caused by external factors such as the JVM running out of memory, or the system running out of resources. These types of errors are not typically recoverable by your application and are not meant to be handled by you.
  • It is generally recommended to handle exceptions, as they are often the result of programming mistakes and can be corrected in the code. Errors, on the other hand, should be logged and reported to the user, but the program should not try to recover from them.
  • In summary, Errors are serious problems that are not usually handled by the application and are thrown by the JVM when it encounters a problem that it can't handle, like running out of memory, stack overflow, etc. While exceptions are events that are triggered by the code you write or external libraries, and can be handled by the application using try-catch blocks, to handle the exceptional events in an appropriate way.
difference between error and exception handling

  Difference Between Exceptions and Errors

  • If exception occurs we can handle it by using try and catch block. If Error occurs we can noyt handle it , program execution will be terminated.
  • In Exception we have two types
    1. Checked Exception
    2.Unchecked Exceptions
  • Error are by default unchecked exceptions.
  • Exceptions are related to application where ad Error are related to environment in which application is running.

  • Exception are of type java.lang.Exception
  • Errors are of type java.lang.Error
  • Error will run at run time.
  • In Exceptions Checked Exceptions will known to compiler so we need to handle these exceptions at compile time itself otherwise compile time Error will come.
  • Unchecked Exception will come at run time need to handle by using try and catch blocks.

Read More About Exceptions here:
  1. Exception Handling Introduction
  2. try catch finally in Java
  3. User Defined Exceptions in Java
  4. Throw vs throws 
  5. Final vs finally vs finalize()


Why StringBuffer Class not overriding equals and hashCode methods

  • YES StringBuffer and StringBuilder classes not overriding equals()method and haschcode() method.
  • Before discussing about why these classes are not overriding equas() and hashcde() methods lets see the usage of overriding equals and hashcode() methods.
  • String class is overriding these equals() and hashcode() methods.
  • When we want to compare two strings we use equals method.
  • basically equals() method is defined in Object class and it will compares the references of two objects if those two objects reference is same then its returns true.
  • And if equals() methods returns true on comparing two objects then their hashcode() must be same this is the contract between equals() and hashcode().
  • Lets see a java program which compares two strings.


  1. package com.instanceofjava;
  2.  
  3. class StringEqualsDemo{
  4.  
  5. public static void main(String [] args){ 
  6.  
  7. String fstr= new String("Javatutorials");
  8. String sstr= new String("Javatutorials"); 
  9.  
  10. System.out.println(fstr.equals(sstr));
  11. System.out.println(fstr==sstr);
  12.  
  13. System.out.println(fstr.hashCode());
  14. System.out.println(sstr.hashCode());
  15. }
  16. }
Output:
  1. true
  2. false
  3. 1921912019
  4. 1921912019
  • In the above program we compared two string using equals() method and it returns true.and comparing using == operator returns false.
  • Basically equal() will also return false on comparing those two strings because default functionality of equal() method is to compare references and two strings are created using new operator so both references are different.
  • But String class overriding equals() method and in that equals method it comparing content of the strings and returning true if both are having same content false if not.
  • Lets see what happen if we compare two stringBuffer objects using equals() method.


  1. package com.instanceofjava;
  2.  
  3. class StringBufferEqualsDemo{
  4.  
  5. public static void main(String [] args){ 
  6.  
  7. StringBuffer fstr= new StringBuffer("Javatutorials");
  8. StringBuffer sstr= new StringBuffer("Javatutorials"); 
  9.  
  10. System.out.println(fstr.equals(sstr));
  11. System.out.println(fstr==sstr);
  12.  
  13. System.out.println(fstr.hashCode());
  14. System.out.println(sstr.hashCode());
  15. }
  16. }
Output:
  1. false
  2. false
  3. 1704856573
  4. 705927765
     
  • If you observe above java program when we are comparing two stringBuffer objects equal() method returning false even content is same. Because StringBuffer class not overriding equals() and hashcode() methods.
  • StringBuilder is also not overriding equals() method? lets see a program and clarify. 


  1. package com.instanceofjava;
  2.  
  3. class StringBuilderEqualsDemo{
  4.  
  5. public static void main(String [] args){ 
  6.  
  7. StringBuilder fstr= new StringBuilder("Javatutorials");
  8. StringBuilder sstr= new StringBuilder("Javatutorials"); 
  9.  
  10. System.out.println(fstr.equals(sstr));
  11. System.out.println(fstr==sstr);
  12.  
  13. System.out.println(fstr.hashCode());
  14. System.out.println(sstr.hashCode());
  15. }
  16. }
Output:
  1. false
  2. false
  3. 1704856573
  4. 705927765
  • So now its cleared that StringBuffer and StringBuilder classes not overriding equals() and hashCode() methods.
  • But Why?
  • Why StringBuffer and StringBuilder classes not overriding equals() method and hashcode() method where as String class is overriding these two methods.
  • Basically Strings are Immutable means Whenever we try to change the value of string result will be new string. So string content wont change.
  • StringBuffer main use is mutable means when we append a string to it it will add to existing object.
  • When the content changes the hashcode will changes. 
  • Lets see a program on adding elements to hashmap.


  1. package com.instanceofjava;
  2.  
  3. class StringDemo{
  4.  
  5. public static void main(String [] args){ 
  6.  
  7. String fstr= new String("Javatutorials");
  8. String sstr= new String("Javatutorials"); 
  9.  
  10.  Hashtable ht=new Hashtable();
  11.  
  12.         ht.put(fstr, "abc");
  13.         ht.put(sstr, "xyz");
  14.         
  15.         System.out.println(ht);
  16. }
  17. }
Output:
  1. {Javatutorials=xyz}


  • In the above java program we tried to add two strings objects as keys to the hashtable.
  • Hashtable put method internally calles equals() method and if its true it wont add.
  1. package com.instanceofjava;
  2.  
  3. class StringBufferHashtableDemo{
  4.  
  5. public static void main(String [] args){ 
  6.  
  7. StringBuffer fstr= new StringBuffer("Javatutorials");
  8. StringBuffer sstr= new StringBuffer("Javatutorials"); 
  9.  
  10.  Hashtable ht=new Hashtable();
  11.  
  12.         ht.put(fstr, "abc");
  13.         ht.put(sstr, "xyz");
  14.         
  15.         System.out.println(ht);
  16. }
  17. }
Output:
  1. {Javatutorials=xyz, Javatutorials=abc}



  1. package com.instanceofjava;
  2.  
  3. class StringBufferHashtableDemo{
  4.  
  5. public static void main(String [] args){ 
  6.  
  7. StringBuilder fstr= new StringBuilder("Javatutorials");
  8. StringBuilder sstr= new StringBuilder("Javatutorials"); 
  9.  
  10.  Hashtable ht=new Hashtable();
  11.  
  12.         ht.put(fstr, "abc");
  13.         ht.put(sstr, "xyz");
  14.         
  15.         System.out.println(ht);
  16.  
  17. }
  18. }
Output:
  1. {Javatutorials=xyz, Javatutorials=abc}


Top 10 Java Interview Questions On main() Method

1.Can we define a class without main method?
  • No, you can’t run java class without main method. 
  • Before Java 7, you can run java class by using static initializers. But, from Java 7 it is not possible.
2.Can main() method take an argument other than string array?
  • No, argument of main() method must be string array. 
  • But, from the introduction of var args you can pass var args of string type as an argument to main() method. Again, var args are nothing but the arrays.
  1. package com.instanceofjava;
  2. public class MainMethod
  3. {
  4. public static void main(String args[])
  5. {
  6. }
  7. }

3.Can we change return type of main() method?
  • No, the return type of main() method must be void only. Any other type is not acceptable.
  1. package com.instanceofjava;
  2. public class A
  3. {
  4. public static int main(String[] args)
  5. {
  6.  return 1;    //run time error : No main method found
  7. }
  8. }

java main method interview questions



4.Why main() method must be static?
  • main() method must be static.
  • If main() is allowed to be non-static, then while calling the main method JVM has to instantiate it’s class. 
  • While instantiating it has to call constructor of that class. There will be an ambiguity if constructor of that class takes an argument. 
  • For example, In the below program what argument JVM has to pass while instantiating class “A”?.
  1. package com.instanceofjava;
  2. public class A
  3. {
  4. public A(int i)
  5. {
  6. //Constructor taking one argument
  7. }
  8.  public void main(String[] args)
  9. {
  10. //main method as non-static
  11. }


5.Can We Declare main() Method As Non-Static?
  • No, main() method must be declared as static so that JVM can call main() method without instantiating it’s class. 
  • If you remove ‘static’ from main() method signature, compilation will be successful but program fails at run time.
  1. package com.instanceofjava;
  2. public class A
  3. {
  4. public void main(String[] args)
  5. {
  6. System.out.println("indhu");         //Run time error
  7. }
  8. }



6.Can We Overload main() method?
  • Yes, We can overload main() method. A Java class can have any number of main() methods. But to run the java class, class should have main() 
  • method with signature as “public static void main(String[] args)”. If you do any modification to this signature, compilation will be successful. 
  • But, you can’t run the java program. You will get run time error as main method not found.
  1. package com.instanceofjava;
  2. public class A
  3. {
  4. public static void main(String[] args)
  5. {
  6. System.out.println("Indhu");
  7.  }
  8. void main(int args)
  9. {
  10. System.out.println("Sindhu");
  11. }
  12. long main(int i, long d)
  13. {
  14. System.out.println("Saidesh");
  15. return d;
  16. }
  17. }

7.Can we declare main() method as private or protected or with no access modifier?
  • No, main() method must be public. You can’t define main() method as private or protected or with no access modifier. 
  • This is because to make the main() method accessible to JVM. If you define main() method other than public, compilation will be successful but you will get run time error as no main method found.
  1. package com.instanceofjava;
  2. public class A
  3. {
  4. private static void main(String[] args)
  5. {
  6. //Run time error
  7. }
  8. }

8.Can we override main in Java ?
  • No you can not override main method in Java, Why because main is static method and in Java static method is bonded during compile time and you can not 
  • override static method in Java. 

9.Can we make main final in Java?
  • you can make main method final in Java. JVM has no issue with that. Unlike any final method you can not override main in Java.

10.Can we make main synchronized in Java?
  • Yes, main can be synchronized in Java,  synchronized modifier is allowed in main signature and you can make your main method synchronized in Java.

Select Menu