Java ArrayList Class –
- Java ArrayList class can contain duplicate elements.
- Java ArrayList class maintains insertion order.
- Java ArrayList class is non synchronized.
- Java ArrayList allows random access because array works at the index basis.
- In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if any element is removed from the array list.
Java LinkList Class
- Java LinkedList class can contain duplicate elements.
- Java LinkedList class maintains insertion order.
- Java LinkedList class is non synchronized.
- In Java LinkedList class, manipulation is fast because no shifting needs to occur.
- Java LinkedList class can be used as a list, stack or queue.
ArrayList Vs LinkList
- ArrayList internally uses a dynamic array to store the elements.
- LinkedList internally uses a doubly linked list to store the elements
- An ArrayList class can act as a list only because it implements List only.
- LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
- ArrayList is better for storing and accessing data.
- LinkedList is better for manipulating data.
Java HashSet Class
- HashSet stores the elements by using a mechanism called hashing.
- HashSet contains unique elements only.
- HashSet allows null value.
- HashSet class is non synchronized.
- HashSet doesn’t maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
Java LinkedHashSet
- Java LinkedHashSet class maintains insertion order.
Java TreeSet
- Java TreeSet class maintains ascending order.
- Java TreeSet class doesn’t allow null element.
Java Map Interface
| Class | Description |
|---|---|
| HashMap | HashMap is the implementation of Map, but it doesn’t maintain any order.one null key and multiple null values |
| LinkedHashMap | LinkedHashMap is the implementation of Map. It inherits HashMap class. It maintains insertion order.one null key and multiple null values |
| TreeMap | TreeMap is the implementation of Map and SortedMap. It maintains ascending order.cannot have a null key but can have multiple null values. |
Difference Between HashMap and HashTable
| HashMap | Hashtable |
|---|---|
| 1) HashMap is non synchronized. It is not-thread safe and can’t be shared between many threads without proper synchronization code. | Hashtable is synchronized. It is thread-safe and can be shared with many threads. |
| 2) HashMap allows one null key and multiple null values. | Hashtable doesn’t allow any null key or value. |
| 3) HashMap is a new class introduced in JDK 1.2. | Hashtable is a legacy class. |
| 4) HashMap is fast. | Hashtable is slow. |
| 5) We can make the HashMap as synchronized by calling this code Map m = Collections.synchronizedMap(hashMap); | Hashtable is internally synchronized and can’t be unsynchronized. |
Sorting in Collection:
- sort a list -> Collections.sort(list);
- sort a list in reverse order -> Collections.sort(list,Collections.reverseOrder());
- sort a user defined class -> need to implement Comparable<ClassName> and implement compareTo(Class Obj) { field > obj.field return 1}
- Sort a user defined class with multiple field like based on name,roll no, age Class nameComprator implement comrator
- public int compare(Object o1,Object o2){
- Student s1=(Student)o1;
- Student s2=(Student)o2;
- return s1.name.compareTo(s2.name);
Difference between ArrayList and Vector
| ArrayList | Vector |
|---|---|
| 1) ArrayList is not synchronized. | Vector is synchronized. |
| 2) ArrayList increments 50% of current array size if the number of elements exceeds from its capacity. | Vector increments 100% means doubles the array size if the total number of elements exceeds than its capacity. |
| 3) ArrayList is not a legacy class. It is introduced in JDK 1.2. | Vector is a legacy class. |
| 4) ArrayList is fast because it is non-synchronized. | Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in runnable or non-runnable state until current thread releases the lock of the object. |
| 5) ArrayList uses the Iterator interface to traverse the elements. | A Vector can use the Iterator interface or Enumeration interface to traverse the elements. |
String , StringBuffer, StringBuilder
- String is immutable, synchronized can be used in multi threading.
- String buffer and String builder is mutable.
- StringBuffer is synchronous so you have thread-safety.
Conversion from one to another
- String to StringBuffer and StringBuilder
StringBuffer sb= StringBuffer(str);
2. Stringbuffer and StringBuilder to String
String str= sb.toString();
3. StringBuffer to StringBuilder or vice versa – first convert stringBuffer or StringBuilder to String then convert it into the same.
Thread , Runnable – there are two ways to implement the multi threading in Java 1. using thread class 1. Runnable interface.
Callable and Future Task – Need for callable is because runnable interface does not provide any return value from thread so we need something which can return some value after execution is complete and that’s where callable comes into picture.
1.the call() method needs to be implemented which returns a result on completion. 2.Another difference is that the call() method can throw an exception whereas run() cannot.
class CallableExample implements Callable { public Object call() throws Exception { }}FutureTask[] randomNumberTasks = new FutureTask[5]; for (int i = 0; i < 5; i++) { Callable callable = new CallableExample(); // Create the FutureTask with Callable randomNumberTasks[i] = new FutureTask(callable); // As it implements Runnable, create Thread // with FutureTask Thread t = new Thread(randomNumberTasks[i]); t.start(); }- As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
- Increased Flexibility: We can make the variables of the class as read-only or write-only depending on our requirement
- Reusability –
- Testing code is easy
- example of encapsulation is model or Entity class
Abstraction: essential details are displayed to the user and non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components.
Abstract classes and Abstract methods :
- An abstract class is a class that is declared with abstract keyword.
- An abstract method is a method that is declared without an implementation.
- An abstract class may or may not have all abstract methods. Some of them can be concrete methods
- A method defined abstract must always be redefined in the subclass,thus making overriding compulsory OR either make subclass itself abstract.
- Any class that contains one or more abstract methods must also be declared with abstract keyword.
- There can be no object of an abstract class.That is, an abstract class can not be directly instantiated with the new operator.
Key points of ConcurrentHashMap:
- The underlined data structure for ConcurrentHashMap is Hashtable.
- ConcurrentHashMap class is thread-safe i.e. multiple thread can operate on a single object without any complications.
- At a time any number of threads are applicable for read operation without locking the ConcurrentHashMap object which is not there in HashMap.
- In ConcurrentHashMap, the Object is divided into number of segments according to the concurrency level.
- Default concurrency-level of ConcurrentHashMap is 16.
- In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updation in object, thread must lock the particular segment in which thread want to operate.This type of locking mechanism is known as Segment locking or bucket locking.Hence at a time 16 updation operations can be performed by threads.
- null insertion is not possible in ConcurrentHashMap as key or value.
Checked exception: – exceptions that are checked at compile time.Java program that opens file at location “C:\test\a.txt” and prints the first three lines of it. The program doesn’t compile, because the function main() uses FileReader() and FileReader() throws a checked exception.
Unchecked Exception :Java exceptions under Error and RuntimeException classes are unchecked exceptions.
Internal Working of Java collections
1.Hashmap is implemented using hash table internally and in case of collision worst time complexity is O(n).
HashMap Changes in Java 8
As we know now that in case of hash collision entry objects are stored as a node in a linked-list and equals() method is used to compare keys. That comparison to find the correct key with in a linked-list is a linear operation so in a worst case scenario the complexity becomes O(n).
To address this issue, Java 8 hash elements use balanced trees instead of linked lists after a certain threshold is reached. Which means HashMap starts with storing Entry objects in linked list but after the number of items in a hash becomes larger than a certain threshold, the hash will change from using a linked list to a balanced tree, which will improve the worst case performance from O(n) to O(log n).

Multi threading Important Notes
http://web.mit.edu/6.031/www/fa17/classes/20-thread-safety/
Use Inbuilt function for Collections And Arrays for basic operation
- sort
- binay_search
- max, min
- reverse
Internal working of collection – HashMap, HashSet(Internally uses HashMap).
Java 8 New features
As part of Java 1.8 , there are couple of new features that has been introduced to robust the Java language.
Features
- Default method in interface : before Java 8 we can not define a method in interface , we were only allowed to declare and these method need to be implemented whenever a class is implementing these interface. Now we can define a method with default as a prefix of a method, which will be available to all the implemented class.
- Static method
- Functional interface : there are three type of interface in java 1. normal : should have more then one function declared in interface 2. functional interface: can have only one method as declared 3. named interface: will have zero declared method its just for name shake example : serializable interface.
- Lamda expression – we can use only functional interface inside lambda expression.
- Stream API : to leverage CPU we can execute our code in different core , we can also use parallel streaming api.
- New Java Date Package :
Question : How multi inheritance work if two interface has same default method
Answer : if two interface has same default method then class need to implement that method explicitly else it will give error.
Question: Public class ABC extend xyz , implement JKL , if JKL interface has default method which is same name in XYZ class then which method will be called.
Answer : class method will be given preference over the default method in interface.
Multi Threading
Introduction to Java multi threading
https://howtodoinjava.com/java-concurrency-tutorial/
Java Generics
https://howtodoinjava.com/tomcat/a-birds-eye-view-on-how-web-servers-work/
https://howtodoinjava.com/java/generics/complete-java-generics-tutorial/#why_generics
Collections Sorting
https://howtodoinjava.com/java-sorting-guide/
Why Enclose wait() in a while Loop?
Since notify() and notifyAll() randomly wakes up threads that are waiting on this object’s monitor, it’s not always important that the condition is met. Sometimes it can happen that the thread is woken up, but the condition isn’t actually satisfied yet.
We can also define a check to save us from spurious wake-ups – where a thread can wake up from waiting without ever having received a notification.
Internal working of LinkedHashMap
https://anmolsehgal.medium.com/java-linkedhashmap-internal-implementation-44e2e2893036#