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.

Life cycle of thread in java

  • Its recommended to learn about life cycle of Thread before you start programming on Thread.
  • Threads exists in different type of states.

  • Thread having below states.
  1. New State
  2. Ready State
  3. Running State
  4. Dead State
  5. Non Runnable States 

Life cycle of thread in java with diagram
Life cycle of a Thread

1.New State:

  • A thread has been created but not started yet. A thread will be started by calling its start() method.

2.Runnable State:

  • This state is also called ready to run stage also called queue. A thread starts in runnable state by calling start() method.
  • The Thread scheduler decides which thread runs and how long.

3.Running State:

  • If a Thread is executing that means Thread is in Running stage.

4.Dead State:

  • Once a Thread reached dead state it can not run again.


5. Non runnable States:

  • A Running Thread transit to one of the non runnable states, depending upon the circumstances.
  • A Thread remains non runnable until a special transition occurs.
  • A Thread does not go directly to the running state from non runnable state.
  • But transits first to runnable state.
  1. Sleeping: The Threas sleeps for specified amount of time.
  2. Blocked for I/O: The Thread waits for a blocking operation to complete.
  3. Blocked for join completion: The Thread waits for completion of another Thread.
  4. Waiting for notification: The Thread waits for notification another Thread.
  5. Blocked for lock acquisition: The Thread waits to acquire the lock of an object.
  • JVM executes the Thread based on their priority and scheduling.

Thread Scheduler:

  • Schedulers in JVM implementations usually employ one of these two Strategies.
  • Preemptive Scheduling
  • Time Sliced or Round robin Scheduling
  • Thread schedulers are implementation and platform independent, therefore how thread will scheduled is unpredictable

Thread priority:

  • JVM will assign a priority for every Thread created in it.
  • 0- will be the minimum priority
  • 5- will be the normal priority
  • 10- will be the maximum priority
  • To hold all these values Thread class has below three corresponding variables
  • public static final int MIN_PRIORITY
  • public static final int NORM_PRIORITY
  • public static final int MAX_PRIORITY 
  •  A thread inherits the priority of its parent Thread. The default priority of the every thread is normal priority 5, because main thread priority is 5.
  • We can set the priority of a thread by using setPriority(int priority) method
  • public final void setPriority(int priority)
  • public void getPriority();
  • User defined thread created with default name  Thread+<index>, where index is the integer number starts from 0.
  • The name of a thread can be change using setName(String name) method.
  • Get by using getName() method.
  • public final void setName(String name)
  • public final String getName().



Life cycle of thread in java program
  1. package com.instanceofjava;
  2.  
  3. class UserThread{
  4.      
  5. UserThread(){
  6.         super();
  7.  }
  8.  
  9.  UserThread(String name){
  10.         UserThread(name);        
  11.  }
  12.  
  13.  public void run()
  14.  {
  15.       System.out.println("thread started running..");
  16.  }
  17.  
  18. public static void main(String [] args){ 

  19.   UserThread thread1 = new UserThread("Thread1");
  20.   UserThread thread2 = new UserThread("Thread2");        

  21.          System.out.println("Thread 1 initial name and priority");
  22.          System.out.println("name:"+thread1.getName());
  23.          System.out.println("priority:"+thread1.getPriority());
  24.  
  25.       System.out.println("Thread 2 initial name and priority");
  26.       System.out.println("name:"+thread2.getName());
  27.       System.out.println("priority:"+thread2.getPriority());
  28.  
  29.       thread1.setPriority(6);
  30.       thread2.setPriority(9);
  31.  
  32.       System.out.println("Thread 1 initial name and priority");
  33.       System.out.println("name:"+thread1.getName());
  34.       System.out.println("priority:"+thread1.getPriority())
  35.  
  36.       System.out.println("Thread 2 initial name and priority");
  37.       System.out.println("name:"+thread2.getName());
  38.       System.out.println("priority:"+thread2.getPriority());
  39.  
  40.       thread1.start();
  41.       thread2.start();
  42.  
  43.       for (int i = 0; i < 5; i++) {
  44.           System.out.println("main method i value:"+i);
  45.     }
  46. }
  47. }


Output:

  1. Thread 1 initial name and priority
  2. name:Thread1
  3. priority:5
  4. Thread 2 initial name and priority
  5. name:Thread2
  6. priority:5
  7. Thread 1 initial name and priority
  8. name:Thread1
  9. priority:6
  10. Thread 2 initial name and priority
  11. name:Thread2
  12. priority:9
  13. Thread1i:0
  14. Thread1i:1
  15. Thread1i:2
  16. Thread2i:0
  17. Thread1i:3
  18. Thread1i:4
  19. Thread2i:1
  20. Thread2i:2
  21. Thread2i:3
  22. Thread2i:4
  23. main method i value:0
  24. main method i value:1
  25. main method i value:2
  26. main method i value:3
  27. main method i value:4

Java programming interview questions

  1. Print prime numbers? 
  2. What happens if we place return statement in try catch blocks 
  3. Write a java program to convert binary to decimal 
  4. Java Program to convert Decimal to Binary
  5. Java program to restrict a class from creating not more than three objects
  6. Java basic interview programs on this keyword 
  7. Interfaces allows constructors? 
  8. Can we create static constructor in java 
  9. Super keyword interview questions java 
  10. Java interview questions on final keyword
  11. Can we create private constructor in java
  12. Java Program Find Second highest number in an integer array 
  13. Java interview programming questions on interfaces 
  14. Top 15 abstract class interview questions  
  15. Java interview Questions on main() method  
  16. Top 20 collection framework interview Questions
  17. Java Interview Program to find smallest and second smallest number in an array 
  18. Java Coding Interview programming Questions : Java Test on HashMap  
  19. Explain java data types with example programs 
  20. Constructor chaining in java with example programs 
  21. Swap two numbers without using third variable in java 
  22. Find sum of digits in java 
  23. How to create immutable class in java 
  24. AtomicInteger in java 
  25. Check Even or Odd without using modulus and division  
  26. String Reverse Without using String API 
  27. Find Biggest substring in between specified character
  28. Check string is palindrome or not?
  29. Reverse a number in java?
  30. Fibonacci series with Recursive?
  31. Fibonacci series without using Recursive?
  32. Sort the String using string API?
  33. Sort the String without using String API?
  34. what is the difference between method overloading and method overriding?
  35. How to find largest element in an array with index and value ?
  36. Sort integer array using bubble sort in java?
  37. Object Cloning in java example?
  38. Method Overriding in java?
  39. Program for create Singleton class?
  40. Print numbers in pyramid shape?
  41. Check armstrong number or not?
  42. Producer Consumer Problem?
  43. Remove duplicate elements from an array
  44. Convert Byte Array to String
  45. Print 1 to 10 without using loops
  46. Add 2 Matrices
  47. Multiply 2 Matrices
  48. How to Add elements to hash map and Display
  49. Sort ArrayList in descending order
  50. Sort Object Using Comparator
  51. Count Number of Occurrences of character in a String
  52. Can we Overload static methods in java
  53. Can we Override static methods in java 
  54. Can we call super class static methods from sub class 
  55. Explain return type in java 
  56. Can we call Sub class methods using super class object? 
  57. Can we Override private methods ? 
  58. Basic Programming Questions to Practice : Test your Skill
  59. Java programming interview questions on collections

Difference between throw and throws in java

throw keyword:
  • throw keyword used to throw user defined exceptions.(we can throw predefined exception too)
  • If we are having our own validations in our code we can use this throw keyword.
  • For Ex: BookNotFoundException, InvalidAgeException (user defined).

Program:
  1. package com.instanceofjava;
  2. public class MyExceptionThrow {
  3.  
  4.  public static void main(String a[]){
  5.  
  6.  try{
  7.  
  8. MyExceptionThrow thr = new MyExceptionThrow();
  9. System.out.println("length of INDU is "+thr.getStringSize("INDU"));
  10. System.out.println("length of SAIDESH is "+thr.getStringSize("SAIDSH"));
  11. System.out.println("length of null string is "+thr.getStringSize(null)); 
  12.  
  13.  }
  14. catch (Exception ex){
  15.   System.out.println("Exception message: "+ex.getMessage());  
  16.  }
  17.  }
  18.  
  19.  public int getStringSize(String str) throws Exception{
  20.  
  21.  if(str == null){
  22.    throw new Exception("String input is null");  
  23.  }
  24.  return str.length();
  25. }
  26.  
  27. }


Output
length of INDU is 4
length of SAIDESH is 5
Exception message: String input is null



 throws keyword:

  •  The functionality of throws keyword is only to explicitly to mention that the method is proven transfer un handled exceptions to the calling place.

Program:
  1. package com.instanceofjava;
  2. public class ExcpetionDemo {
  3.  
  4. public static void main(String agrs[]){
  5.  
  6. try
  7. {
  8. //statements
  9. }
  10. catch(Exception e)
  11. {
  12. System.out.println(e);
  13. }
  14. finally(){compulsorily executable statements
  15. }
  16. }
  17.  
  18. }

Select Menu