String vs StringBuffer vs StringBuilder
• If the content is fixed and wont change frequently then Its
recommended to go for String
• If the content is not fixed and keep on changing then its not
recommended to use String, Because, for every change , a new object
will be created which effects performance of the system.
• To handle this requirement, we should go for String Buffer. All
required changes will be performed in the existing object only.
• Length vs capacity. StringBuffer has initial capacity of 16 and grows @
new capacity = (current capacity +1 )*2 ( 16➔34➔ 70➔142➔ …)
String vs StringBuffer vs StringBuilder
• StringBuffer sb = new StringBuffer(); - with default capacity of 16 and
later can grow ([Link]() method returns current capacity).
• StringBuffer sb = new StringBuffer(int initialcapacity);
• StringBuffer sb = new StringBuffer(String); //capacity will be
16+String length…
• length(), charAt(),
• public void setCharAt(int,char)
• public SB append(String or int or long or char or boolean),
• public SB Insert(int index,String or int or double or char or boolean)
String vs StringBuffer vs StringBuilder
• public SB delete (int begin, int end);
• public SB deleteCharAt(int index);
• public SB reverse();
• public void setLength(int); //truncate will happen if actual length is
more
• public int capacity();
• public void ensureCapacity(int); //to increase the capacity
dynamically
• public void trimToSize(); // to reduce the capacity.
Array
• An Array is an indexed collection of fixed number of homogeneous
data elements.
• Using Array, we can represent multiple values with a single variable.
• Arrays are fixed in size (Once we create array with some size there is
no chance of increasing or decreasing its size). So we should be know
the size of the Array in advance.
• It can hold only homogeneous data elements.
• Using Object Arrays , we can indirectly have heterogeneous data
elements.
• Array concept is not implemented based on some standard data
structure. Hence readymade method support is not available
Collection vs Collection Framework
• Growable in nature ( we can increase or decrease the size)
• Can hold both Homogeneous and Heterogeneous data elements.
• Collection is implemented based on some standard data structure
(Readymade method support is available for every requirements).
• Collection represents a group of individual Objects as a single entity
• It defines several classes and Interfaces used to represent group of
individual objects as single entity.
• There are 5 key Interfaces are available in Collection Framework
(Collection, List, Set, Queue, Map).
Collection Interface (1.2v)
• Collection Interface represent a group of Individual object as a single
entity
• It defines the most common methods which are applicable for any
collection Object.
• Its root interface of Collection framework.
• There is no concrete class which implements Collection interface
directly.
Collection Methods
• boolean contains(Object)
• boolean add(Object)
• boolean containsAll(Collection)
• boolean add(Collection)
• boolean isEmpty()
• boolean remove(Object)
• int size()
• boolean removeAll (Collection)
• Object[] toArray()
• boolean retainAll (Collection)
• Iterator iterator()
• void clear()
Collection doesn’t contain any method to retrieve objects. There is no concrete class which
implements Collection directly.
Collection vs Collections
• Collections is an utility class present in [Link] package to define
several utility methods (Sorting, Searching) for Collection objects.
List Interface (1.2v)
• List is child interface of Collection Interface
• List represents group of individual object as a single entity.
• Duplicates are allowed (We can differentiate duplicates using Index)
• Insertion order preserved (using Index).
• It has 3 classes
• ArrayList (1.2)
• LinkedList (1.2)
• Vector (1.0)
• Stack (1.0)
• Vector and Stack classes are re-engineered in 1.2V to implement List
Interface
List Interface Methods
• int indexOf(Object)
• void add(int index, Object o)
• int lastIndex(Object)
• boolean addAll(int, Collection)
• ListIterator listIterator()
• Object get(int index)
• Object remove(int index)
• Object set(int index, Object o)
ArrayList
• Resizable Array or Growable Array (Underlaying DataStructure)
• Duplicates are allowed
• Insertion order is preserved (using Index)
• Heterogeneous Object
• Null insertion is possible
• Every Collection class already implements Serializable and Cloneable.
• ArrayList and Vector implements RandomAccess Interface (to access
any random elements from AL @same speed). AL is the best choice
for frequent retrieval operation.
• RandomAccess is Marker Interface (Interface with no methods)
ArrayList Constructor
• ArrayList() – Creates an empty ArrayList with default capacity 10.
Once AL reaches its max , a new ArrayList will be created with new
capacity (current capacity *3/2)+1.
• ArrayList(int capacity).
• ArrayList(Collection)
• ArrayList is not recommended if insertion and deletion operations are
frequent in the middle which needs several swift operations.
ArrayList vs Vector
• Vector methods are synchronized and thread safe
• Due to this vector’s performance is low.
• Vector is legacy (1.0V).
• We can get synchronized version of AL using below methods
• ArrayList al = new ArrayList();
• List l = [Link](al);
• Set s = [Link](Set);
• Map m = [Link](Map);
LinkedList
• Doubly Linked List (Underlaying DataStructure)
• Duplicates are allowed
• Insertion order is preserved (using Index)
• Heterogeneous Object
• Null insertion is possible
• Every Collection class already implements Serializable and Cloneable
(not RandomAccess)
• LinkedList is the best preferred if our frequent operation is insertion
and deletion of elements in the middle (as no swifting operations).
• LL is not preferred if our frequent operation is retrieval operation (as
no RandomAccess). It takes time to retrieve elements from LL.
LinkedList Specific Methods
• To Implement LL based implementation of Stack and Queue, following
methods are used in LL dedicatedly.
• void addFirst(Object)
• void addLast(Object)
• Object getFirst()
• Object getLast()
• Object removeFirst ()
• Object removeLast ()
LinkedList Constructor
• LinkedList() – Creates an empty LinkedList (no Capacity concepts)
• LinkedList(Collection) – Creates an LL Object for the given Collection
ArrayList vs LinkedList
• DS ??
• Best Choice for ??
• Worst Choice for ??
Cursors
• Enumeration
• Enumeration e = <<vectorObj>>.elements()
• [Link]()
• [Link]()
Enumeration is applicable only for legacy classes
We can perform only read operations
Iterator is Universal Cursor and we can apply to Iterator to any
Collection Object. We can perform both Read and Remove Operations.
Cursors
• Iterator
• Iterator it = <<CollectionObj>>.iterator()
• [Link]()
• [Link] ()
• [Link]()
Using Iterator, we can navigate only forward direction (not bi-
directional).
Replacing and adding of new elements not possible.
Cursors
• ListIterator
• Iterator lit = <<ListObj>>.listIterator()
• [Link]()
• [Link] ()
• [Link]()
• [Link](), [Link](), [Link]()
• [Link](), [Link](Obj), [Link](Obj)
ListIterator is child of Iterator interface, so it has all methods from
Iterator and its own methods.
<E>/<it>/<Lit>.getclass().getName()
Set Interface(1.2)
• Set is child interface of Collection Interface
• Set represents group of individual object as a single entity.
• Duplicates are not allowed
• Insertion order are not preserved
• It doesn’t have any new Methods (only Collection Methods)
• It has 2 classes
• HashSet(1.2)
• LinkedHashSet (1.2)
HashSet
• HashSet is implementation class of Set Interface
• DS - HashTable
• Duplicates are not allowed (add method returns Boolean value , no
exception thrown when trying to add duplicate values)
• Insertion order are not preserved (Objects are inserted using
hashcode)
• Heterogeneous
• Null insertion is possible
• Implements Serializable and Cloneable (But not RandomAccess).
• If Search is frequent operation, HashSet is the best choice.
HashSet
• HashSet hs = new HashSet() – Empty HashSet with default initial
capacity 16 and Load Factor/Fill ratio 0.75
• HashSet hs = new HashSet(int capacity) – Empty HashSet with
specified initial capacity and Fill ratio 0.75
• HashSet hs = new HashSet(int c, float f) – Empty HashSet with
specified capacity and specified Load Factor or Fill ratio
• HashSet hs = new HashSet(Collection c) – HashSet with existing
Collection loaded.
LinkedHashSet (1.4v)
• LinkedHashSet is child class of HashSet (LinkedList + HashSet)
• DS – HashTable + LinkedList
• Duplicates are not allowed (add method returns Boolean value , no
exception thrown when trying to add duplicate values)
• Insertion order is preserved (Objects are inserted using hashcode)
• Heterogeneous
• Null insertion is possible
• Implements Serializable and Cloneable (But not RandomAccess).
• Its frequently used to develop Cache-based application.
TreeSet
• HashSet is implementation class of SortedSet Interface
• DS – Balanced Tree
• Duplicates are not allowed (add method returns Boolean value , no
exception thrown when trying to add duplicate values)
• Insertion order are not preserved (All elements are inserted based on
some sorting technique )
• Heterogeneous are not allowed.
• Null insertion is possible (Only Once)
TreeSet
• TreeSet ts = new TreeSet() – Empty TreeSet with default natural
sorting order (Integer in ascending order and String in Alphabetical)
• TreeSet ts = new TreeSet(Comparator) – Empty TreeSet with
customized sorting order.
• TreeSet ts = new TreeSet(Collection c) – TreeSet with existing
Collection loaded.
• TreeSet ts = new TreeSet(SortedSet) – TreeSet with existing Sorted List
loaded.
TreeSet
• For Empty TreeSet as the first element null insertion is possible.
• But After inserting that null value, if we insert any other element, we
will get NullPointerException
• For Non-empty TreeSet if we insert Null then we will get
NullPointerException.
• Can we add heterogenous Object to TreeSet?
• Can we add StringBuffer Object to TreeSet? StringBuffer is not
comparable?
• If we depending on natural sorting order, JVM will call compareTo()
method while inserting objects to TS. Hence Objects should be
comparable.
Map(1.2) Interface
• Map is not child interface of Collection Interface
• Group of individual objects are represented as key and value pair.
• Both Key and values are Objects
• Values can be duplicated but not keys.
• It has 2 main classes and 1 Interface (SortedMap).
• HashMap(1.2)
• LinkedHashMap (1.4)
• SortedMap(1.2) used to represent a group of Key and Value pairs according
to some sorting order of keys.
• NavigableMap(1.6) is a child interface of SortedMap Interface
• It defines several utility methods for Navigation purpose (next , previous)
• TreeMap(1.2) is implementation class of NavigableMap.
HashMap
• HashMap is implementation class of Map Interface
• DS – HashTable
• Duplicates are not allowed for keys but duplicate values are allowed.
• Insertion order is not preserved (Its based on hashcode of keys)
• Heterogeneous Keys and Values are allowed.
• Null insertion is possible (only once for keys, no restrictions on values)
• Implements Serializable and Cloneable (But not RandomAccess).
• If Search is frequent operation, HashMap is the best choice.
HashMap
• HashMap hs = new HashMap() – Empty HashMap with default initial
capacity 16 and Load Factor/Fill ratio 0.75
• HashMap hs = new HashMap(int capacity) – Empty HashMap with
specified initial capacity and Fill ratio 0.75
• HashMap hs = new HashMap(int c, float f) – Empty HashMap with
specified capacity and specified Load Factor or Fill ratio
• HashMap hs = new HashMap(Map m) – HashMap with existing Map
loaded.
LinkedHashMap
• LinkedHashMap is child class of HashMap (LinkedList + HashMap)
• DS – HashTable + LinkedList
• Duplicates are not allowed.
• Insertion order is preserved
• Heterogeneous
• Null insertion is possible
• Implements Serializable and Cloneable (But not RandomAccess)..
TreeMap
• TreeMap is implementation class of SortedMap Interface
• DS – Red-Black Tree
• Duplicates Keys are not allowed (Duplicate values are allowed)
• Insertion order are not preserved (All elements are inserted based on
some sorting order of Keys )
• Heterogeneous are not allowed (Keys have restrictions but not
values).
• Null insertion is possible (Only Once) – (for keys same as Set but no
restrictions on Values).
TreeMap
• TreeMap ts = new TreeMap() – Empty TreeMap with default natural
sorting order (Integer in ascending order and String in Alphabetical)
• TreeMap ts = new TreeMap (Comparator) – Empty TreeMap with
customized sorting order.
• TreeMap ts = new TreeMap (Map m) – TreeMap with existing
Collection loaded.
• TreeMap ts = new TreeMap (SortedMap) – TreeMap with existing
Sorted Map loaded.
Comparable vs Comparator, Iterator and Utility
Class
• Comparable: Default Natural Sorting Order
• Comparator: Customized Sorting Order
• It has 2 methods , compare() and equals()
• public int compare(Obj1,Obj2)
• Enum, Iterator, ListIterator
• 2 utility class
• Collections – Contains utility methods for collection Object(sort,search)
• Arrays – Contains utility methods for Array Object (sort,search)
MultiThreading
• Multitasking
• Executing several tasks simultaneously
• AIM is to improve performance of the system by reducing response
time of the system (processing idle time).
• There are 2 types of Multitasking
• Process Based Multitasking
• Executing several tasks simultaneously where each task is a
separate independent program (Process)
• While typing a program in the editor, we can listen to audio
songs from same system and do multiple tasks.
• These tasks are independent of each other.
• Its best suitable at OS level.
MultiThreading
• Multitasking
• Thread Based Multitasking
• Executing several tasks simultaneously where each task is a
separate independent part of same program (Thread).
• Thread is a separate flow of execution.
• Searching a file in multiple folders parallely.
• These tasks are independent of each other.
• Its best suitable at Programmatic level.
• Develop web server or Application server
Methods to Prevent Thread Execution
• Yield() - public static native void yield();
• Causes to pause the current executing thread to give the chance for
waiting threads of same priority
• If there is no waiting thread or all waiting threads have low priority ,
same thread can continue its execution.
• If we have many waiting threads with same priority, which thread will
get chance to execute lies on Thread scheduler.
• Yielded thread will move to Runnable status and wait for its turn.
Methods to Prevent Thread Execution
• join () -
• If a thread wants to wait for some other thread to complete
• [Link]() – inside t1 run method.
• t1 thread will wait for t2 to complete.
• t1 thread will go in wait status until completion of t2 thread.
• Once t2 completes, which thread will get chance next , is depends on
the scheduler.
• After invoking join() method, t1 thread moves to Waiting (Blocked for
joining) status.
• Once t2 completes or time expires or t1 interrupted, t1 thread moves
to Runnable status. Moving to running status is depends on Scheduler.
Methods to Prevent Thread Execution
• join () - public final void join () throws IE;
• public final void join() throws IE;
• public final void join (long milliseconds); 30mins
• public final void join (long milliseconds, int nanoseconds);
• We need to handle InterruptedException mandatorily (interruption of
a thread is caused by any other thread calling the interrupt() method).
• How child thread can execute/call join on Main thread???
• What happens if both threads (Child and Main) executes/calls join on
each other?? Deadlock.
• Can main thread can call join on its own ([Link]().join())
Methods to Prevent Thread Execution
• sleep () -
• Cause the thread sleep for particular period (Thread wont perform any
operation for particular period of time).
• public static native void sleep(long ms) throws IE
• public static void sleep(long ms, int ns) throws IE
• Running thread will go in to sleeping/waiting status, once time is
expired or interrupted, thread will move in to Ready/Runnable status.
Thread Interruption
• interrupt () - public void interrupt()
• Sleeping or Waiting thread can be interrupted using interrupt() method
by another Thread.
• Can we interrupt() non-sleeping or non-waiting thread??
• No exception will be raised
• Interrupt() / (JVM) will wait for that thread to go in sleep/Waiting
status and execute on it.
• What happens if thread never enters in to sleep/Waiting status then
in its life time ? (there is no impact of interrupt call).
synchronized – Access Modifier
• synchronized is an access modifier applicable only for methods and blocks
• If multiple threads trying to operate simultaneously on same Java Object,
then there could be chance of data Inconsistency problem.
• To avoid this , we should go for synchronize keyword.
• If method or block declared as synchronized, only one thread to execute
that method or block on the given object, at a time. So that data
inconsistency problem will be resolved.
• But using this approach, Threads are going to execute one after another,
increases waiting time of thread and leads to performance issues.
• Its better to avoid using synchronized until there is strong need of it.
synchronized Block
• When very few lines of code requires synchronization, then its not
recommended to declare entire method as Synchronized (Method).
• We can enclose those few lines of code by using synchronized block.
• Advantage of using synchronized block (over method) is, it reduces
waiting time of threads and improves performance of the system.
• We can write synchronized block using current object (this) or specific
object or class ([Link]). (as we know we have only Object and Class
level Locks only).
• Can thread can have multiple locks (from diff objects)??
• Synchronized Statement : Statements presents in synchronized method
and/or synchronized blocks are called synchronized statements.
Inter Thread Communication
• 2 Threads can communicate each other by using wait(), notify() and
notifyall() methods.
• Thread can request/wait for updates from some other Thread.
• Other thread can notify the waiting thread. So waiting thread can
continue the execution.
• Thread which is expecting updation is responsible to call wait() method.
• After executing wait() method, thread will enter in to waiting state.
• Thread which is responsible to perform updation ,after performing
updation, it is responsible to call notify or notifyall method.
• Once Waiting thread gets notifications, it will continue its execution with
those updated items (after obtaining lock).
wait(), notify() and notifyall()
• These 3 methods are available in Object class (not in Thread class).
• These 3 methods can be called on any Objects.
• Using these Objects only thread calls wait ().
• Using these Objects only thread receives notify() and notifyall() method
• These 3 methods can be called on any Object only by owner of these
Objects.
• Thread who has lock of these Objects , can call these 3 methods on these
objects (These 3 methods should be called inside Synchronize method or
block only).
• If we call these 3 methods outside synchronized Area, we will get
Runtime Exception - IllegalMonitorStateException
wait(), notify() and notifyall()
• Once thread calls wait() method, it releases lock of that object
immediately and enters in to waiting state (Remember thread can have
multiple locks, so it releases that object lock only).
• Once thread calls notify() or notifyall() method on any Object, it releases
lock of that object (may not be immediately - as thread may do some
updations if required on this Object).
• NOTE: Thread wont release locks at any point of time except for after
calling these methods. Why??? Object level lock is shared by these
threads in communication.
• Once Thread get notifications from another Thread, Waiting thread
moves to Waiting state again for Lock , after obtaining that Object lock ,
it continues its execution.
wait(), notify() and notifyall()
• public final void wait() throws IE
• public final native void wait(long ms) throws IE
• public final void wait(long ms, int ns) throws IE
• public final native void notify()
• public final native void notifyAll()
• notify() – will give notification to one waiting thread(Which thread?? JVM )
• Remaining thread has to wait for further notifications
• We need to issue multiple notify for individual threads
• notifyAll() - will give notification to all waiting thread (for same Obj)
• All these threads will move to waiting state for lock and have to wait for
their turn to get lock (one by one).
stop (), suspend(), resume() - Deprecated
• public void stop()
• To kill the thread in middle of the execution/running
• Thread will move to Dead/Complete state.
• public void suspend()
• Thread can suspend another thread
• Suspended thread will enter in Suspended state.
• public void resume()
• Thread can resume suspended thread
• Resumed thread will move from Suspended to Ready/Runnable state.
Thank you