DataStructure
DataStructure
Array
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Matrix
Misc
Advanced Data Structure
Example: Design an algorithm to multiply the two numbers x and y and display the
result in z.
Step 1 START
Step 2 declare three integers x, y & z
Step 3 define values of x & y
Step 4 multiply values of x & y
Step 5 store the output of step 4 in z
Step 6 print z
Step 7 STOP
. Alternatively the algorithm can be written as ?
Best case: It defines the input for which the algorithm takes the lowest time.
The commonly used asymptotic notations used for calculating the running time
complexity of an algorithm is given below:
Linked List
Linked List can be defined as collection of objects called nodes that are randomly
stored in the memory.
A node contains two fields i.e. data stored at that particular address and the
pointer which contains the address of the next node in the memory.
The last node of the list contains pointer to the null.
DS
DS Array
DS Array, 2D Array
DS Linked List
Linked List, Doubly Linked List, Circular Linked List, Circular Doubly List
DS Stack
DS Stack Array Implementation Linked List Implementation
DS Queue
DS Queue Array Representation Linked List RepresentationCircular Queue open link
DS Tree
DS TreeBinary TreeBinary Search TreeAVL TreeB TreeB+ Tree
DS Graph
DS Graph Graph Implementation, BFS AlgorithmDFS Algorithm Spanning Tree
DS Searching
Linear SearchBinary Search
DS Sorting
Bubble Sort Bucket Sort Comb Sort Counting Sort Heap Sort Insertion Sort Merge Sort
Quick Sort
Radix Sort Selection Sort Shell Sort Bitonic Sort Cocktail Sort Cycle Sort Tim Sort
JAVA
The meaning of platform-independent is that the java compiled code(byte code) can
run on all operating systems.
In case of C or C++ (language that are not platform independent), the compiler
generates an
.exe file which is OS dependent.compiled code is Machine language which is
understandable only
by the current OS.
Java is platform-independent but JVM is platform dependent
Frameworks are not part of java Se or java EE they are deveoped by third party
Companies by using java EE technologies.
Java Sc lnaguge cocepts
datatypes, operators, contorol Statement
OOPS
JVM Architecture
Garbage colection
String handling
wrapper classes
exception hadling
multithreading
IOStreams(File IO)
Networking(Socket programming)
collections framework
regular expression
reflection api
annotations
inner cllasses
AWT, Swings, applet
Working with jar
date, time and text format
JVM executes only main method because it has mainn method's callinng statement.
it does not have user defined method's callling statment in its logic. it
executes user defined methods only if they are called from main method.
We can create two main method in two different classes there is no compile time
error
but we have to tell to jvm which class first is exicuting.
Wrapper Classes => the classes which are used to represent primitive
values as object are called wrapper classes.in java.lang package we have 8
wrapper classes.
Exception handling.
Error-> error tyype exception are thrown due to the problem occurred in side jvm
logic,
1. if there is no memory in Java Stack Area. 2. if there is no memory in Heep
area
Exception-> Exception type exception are thrown due to the problem occurred in java
program logic execution,
Two categories of exceptioons
1. checked exceptions -> Throwable, Exception, and its direct subclasses are
called checked
exceptions because if they are thrown by using "throw" keyword compiler
checks their handling
and if they are not caught by using "try/catch" or not reported by using
"throws" keyword,
compiler throws CE:"unreported exception must be caught or declared to be
thrown".
2. Unchecked exceptions-> Error, RuntimeException and their subclasses are
called unchecked
exception becase these exceptions handling is not checked by compiler when
they are thrown
by using throw keyword. it means these exception object catching or
reporting is optional.
Finally ->As per coding standards in finally block we should write resource
releaseing
logic(or)clean up code. resource releasing logic means unreferencing
object
those are created in try block. ex.. closign a JDBC connection inside
finally block.
throw keyword is used to throw exception manually. in most of the cases we use it
from
throwing checked exceptions explicitly.
throws keyword is used to report that raised exception to the caller. it is
mandatory for
checked exceptions for reporting, if they are not hadled.
Types of method
1.Based on static
a. static methods
b. non-static methods
3.Based on parameter
a. parameterized
b. non-parameterized
JVM Architecture
Method Area->all static variables
Head Area->object of a class, non-static variables memory created in this area
Java Stack Area->all java methods are executed. in this runtime jvm by default
creates
two threads, (i).main thread (ii).garbage collector thread
->main thread is responsible to execute java methods stats with main methods, also
responsible to create object in head area if it finds "New" keyword in any method
logic.
->Garbage collector thread is responsible to destroy all unused object from head
area.
->for each method execution jvm creates separate block in main thread. technically
this
block is called stack frame. this stack frame is created when methods is called
and is
destroyed after methods execution.
Note:java operations are called "stack based operations (sequential)", because
every method
is executed only in stack.
ClassLoader subsystem
classLoader is a class that is responsible to load calsses into jvm's method are
we have basically three types of class loaders
1. ApplicationClassLooader-> is responsible to load classes from application
classpath,
(current working directory). it basically uses
classpath envirnment
variable to locate the class's ".class" file
2. ExtensionClassLoader-> is responsible to load cllass from extension classpath,
"%java_Home%\jre\lib\ext"
3. BootStrapCllassLoader-> is responsible to load class from bootstrap Classpath
"java_home%\jre\lib\rt.jar. these classes are
predefined classes.
.we can place return type in constructor prototype will not lead to error , because
compiler and jvm
consider it as method.
.type of constructors
java supports 3 types of constructors
1. Default constructor
2. No-argument | non-parameterized constructor
3. parameterized constructor
.in a class we can define multiple constructors, but every constructor must have
different parameters type (or) parameters order.
So in a class we can define one no-arguemnt constructor + 'n' number of
parameterized constructors.
Type of Class
1.interface
2.Abstract class
3.Concreate class
4.final class
5.enum
Use of suepr keyworkd: the super is java keyword, used to access super class
members and constructors from subclass
members and constructors. it has two syntaxes they are:
1. super() -is used to call super class constructors from subclass constructors
2. super. -is used to call super class variables and methods from subclass members
and consturctors.
"super." is used to access super class variables and method fromm subclass members
or constructors. It is mandatory
to user "super." in accessing superclass members only if subclass has member withh
suerp class name.
OOPS principles
1. Encapsulation
2. Inheritence
3. Ploymorphism
Java.lang package => this packe is called default packeage, because jvm loads all
classes of this package
automatically. So to use this package classes we no need write import statement.
some important classes in object class.
1. Object, class, String, StringBuffer, StringBuilder, Wrapper classes(All
primitive capital latter INTEGER,
BYTE...), Throwable, Exception, Error, Thread, TheadGroup, System, Runtime,
ClassLoader, Process, SecurityManager
Object subClasses->Class, classloader, compiler, system, package, process, runtime,
number, Math, String
StringBuffer, StringBuilder, thread, theadGroup, Throwalbe, Void,Wrapper
Clsses,Error, Exception,clonable,
charSequence, comparable, Runable
Obj1.state->x=10,y=20 reference1=1010
Obj2.state->x=10,y=20 reference2=2020
The above two object e1 and e2 .are equal based on their state and
.are not equal based on their reference.
(equal method compare object based on their data)
==operator compare object's references, not state(values)(it return true,false)
When jvm is created in its java stacks area by default two threads are created with
names.
1. main- to execute java methods
2. garbage collector -to destroy unreferenced objects
Thread priority
Every thread created in jvm is assigned with a priority
1 is called minimum priority
2 is called normal priority
10 is called maximum priority
threadGroup-> Every thread is created with a thread group. the default thread group
name is "main" We
can also create user defiined thread group oname is "main" We can also create user
defined thread
groups useing threaGroup class.
Types of threads.
Java alllows us to create two types of threads they are
1. Non-Demon threads
2. Demon threads
1->A thread that executes main logic of the project is called non-daemon thread.
2->A thread that is running in background to provide services to non-daemon threads
is callled daemon
threads. So we can say daemon threads are service threads.
Synchronization
thre process of allowing multimple thread to modify an object in sequence is
callled synchronization.
Deadlock
Deadlock is a situation where if two thread are waitinig on each other to complete
there execution.
Deadlock is occurredd due to wrong usage of synchronized keyword. If first thread
is calling a synchronized
mehtod by using a locked object of second thread, and second thread calling a
synchronized method by
using a locked object of first thread then deadlock is occure.
Wait(). The functionality of wait() method is block the currently executing thread
by releasign lock
on the current object fo the currently executing method. so that the other waiting
threads can use this
current object to execute other dependent synchronized method..
notifyAll(). notifyAll() method is also used for the same above purpose but if
there are multiple waiting
thead are available.
String
String, StringBuffer, StringBuilder
All these three classes are final classes
These three classes are also subclasses of java.io.serializable interface
String class is a subclass of Comparable interface, but StringBuffer and
StringBuilder are not.
Strnig s1="rohit";
String s2=s1;
System.out.println(s1==s2);true
Collection(Java.utill package)
in java project collectin framework classes are used to store and transport object
are of same adn different types withhout size limitaion.
in java 1.0 version SUN only interoduced 2 classes to collect objects in above
formates, they are
a. vector: it stores objects in array format
b. Hashtable: it stores object in(key, value) pair formate
we havae one more class called Stack, it is the subclass of Vector class. it is
used to stores objects and to retrieve them in last in fors out(LIFO) fashion.
These two classes were created as thread-safe classes, means alll the mehtods in
these two
classes are declared as synchronized. Hence for every method call on these two
objects either
for adding or removing elements, jvm locks and unlocks these two objects. so in
single thread
model application it leads to performance issue. in single thread model application
execution
is sequential so there is no data corruption, hence no need locking. To solve this
perfomance issue
problem
in java 1.2 version more number of collection classes are added alternate to vector
nad hashtable
.ArrayList and HashMap respectively.
java 1.0 version are called as legacy classes.
from java 1.2 version all collectin are called as collection framework.
Collection
├── List
│ ├── ArrayList
│ ├── LinkedList (also Deque)
│ └── Vector
│ └── Stack
├── Set
│ ├── HashSet
│ ├── LinkedHashSet
│ └── SortedSet
│ └── NavigableSet
│ └── TreeSet
└── Queue
├── PriorityQueue
└── Deque
├── ArrayDeque
└── LinkedList (also List)
Map
├── HashMap
│ └── LinkedHashMap
├── WeakHashMap
├── IdentityHashMap
└── SortedMap
└── NavigableMap
└── TreeMap
Collectin hierarchy
Collectino hierarchy classes are divided into three categories -Set, List, and
Queue.
Using Collectioon hierarchy classes we can collect unique and duplicate objects in
array format.
Set=>is a unique collection, it does not allow duplicate elements. Set is the super
interface
for all unique collection classes.
List=>is a duplicate collection, it allows duplicate elements.List is the super
interace for all
duplicate collection classes.
Set does not store elements in indexed or sorted order, whereas List stores
elements in indexed order
but not in sorted ordeer.
SortedSet is a sub interface of set that stores elements in sorted order either in
asceending or desending
ordeer based on the object's natural sortnig order.
Map
Map is having a tow sub interface
sortedMap NavigableMap
TreeMap sub class of NavigableMap
map is having direct subclass
Hashmap, LinkedHashMap
LinkedHashMap is Sub class of HashMap
map is having direc subcllass
Hashtable, properties
properties is subclass of HashTable
SortedMap is the sub interfcae of Map. it sorts entries based on keys natural
sorting order.
To collect objects in (key, value) pair format we should choose Map hierarchy
classes.
To store and retrieve duplicate elements in random access we must choose ArrayList
Or Vector.
These two classes functionality is same except, vector is thread-safe. So, in
Single
thread model Application we should choose ArrayList, in multithreading model
application
if list object is modifying concurrently we should choose Vector.
The drawback or arraylist and vector is "they give less performance if we perform
insertioons and
deletion in middle", because for every insertion or new element, all remaining
elements must be moved
right hand side, and for every element deletion, elements must be moved to left
hand side. As shown in
the below diagram.
To solve this performace issue we must choose linkedList. It gives high perfrmance
in inserting or deleing elements in
middle . it internally uses linked list data structore, so there will not be any
data movements, insted we
will have onlly changing linkes, and the indexes.
Three Type of cursor to retrieve elements from all types of collection objects
We have three types of curser object for retrieving elements they are:
1. Enumeration
2. Iterator
3. Listiterator
All Above three are interfaces.The subclasses objects are returned vica
factory methods. Tyese facory methods are also defined inside collection classes.
to these factory methods must be called with collection object for whhich we want
to retrieve elements.
performing above two task these three cursor object must have minimum two methods
1. for checking element available or not
2. for returing the elemnent reference from collection and moving cursor to next
location
All above cusor objects cursor is initially pointint to before first location of
the collecton.
List object has index so we can retrieve elements by usig for loop
But how can we retrieve elements from set objects since they do not have index
iterator is only the option we have to retrieve elements from set objects.
Iterator interface provides below three method for retrieving elements from
collectioon
hasNext(),next(), remove()
Map we can retrive value by passing key its associated.. So key should be unique,
but we can duplicate values.
home work
Casting, instanceOf operator(102), Auto Boxiing and Auto Unboxing, valueOf,
xxxValue
InstanceOf :->
The instanceof operator in Java is used to check whether an object is an instance
of a particular class or not.
valueOf :->The java string valueOf() method converts different types of values into
string. By the help of string valueOf()
method, you can convert int to string, long to string, boolean to
string, character to string, float to string,
double to string, object to string and char array to string.
Stream:->
There are two basic types of stream defined by Java, called byte stream and
character stream.
The byte stream classes provide a convenient means for handling input and output of
bytes and
character streams provide a convenient means for handling input and output of
characters, respectively.