Java Adv
Java Adv
:NEED :
The main advantage of array is we can represent multiple value with a single variable
Optimize code,reusability.
Limitation of Array
Arrays are fixed in size i.e once we create an array with some size there is no chances of inc or
Declairing the size we need to know about size before creating an array.
Collection
➔ Collection are growable in nature i.e based on our requirement we can dec and inc the size
➔ It can hold heterogeneous data.
➔ Implements some std ds.(ready made method support.)
Difffernce b/w
Arrays collection
Only homogeneous hetrogenous
Size fixed growable
Not implemented on some std DS implemented on some std DS
w.r.t m/m not recomended w.r.t m/m recomended
Primitive data type & obj Only obj
What is collection
If we want to represent a group of individual object as a single entity then we should go for collection.
It defines several classes and interfaces which can be used by a group of individual object as a single entity.
Collection(I)
Collections collections is an utility class present java.util package to define sevral utility methods
collection(i)1.2v
Map
List(I):
0 1 2 3 4 5 6
List is a child interface of collection.
Duplicate allowed and insertion order preserved. We can differenciate them on the bases of index.
list(1.2v )
stack(1.0)v
child of
vector(LIFO)
ArrayList
• growable array(DS)
• def cap=10
• (c*3/2)+1
• null*
• implementing RANDOM ACCESS(I)->marker
• present in java.util.
• retrival opration best choice
• ->worst choice insertion and del in b/w
• not syncyonized
ArrayList a1 = new ArrayList();
import java.util.*;
class Arraydemo{
public static void main(String[] args) {
ArrayList al = new ArrayList<>();
al.add(13);
al.add(67);
al.add("gras");
al.add(null);
System.out.println(al);//[13, 67, gras, null]
}
}
Note: we can use collection to hold and transfer objects from one place to another
import java.io.Serializable;
import java.util.*;
class Arraydemo{
public static void main(String[] args) {
ArrayList al = new ArrayList<>();
LinkedList l1 = new LinkedList<>();
System.out.println(al instanceof Serializable);
System.out.println(l1 instanceof Serializable);
System.out.println(al instanceof RandomAccess);//array list
System.out.println(l1 instanceof RandomAccess);
}
}
ArrayList Vector
Not synchronized synchronized
Performance high Performance low
1.2v() 1.0v(legacy classes)
import java.util.*;
class Arraydemo{
public static void main(String[] args) {
LinkedList l1 = new LinkedList<>();
l1.add(123);
l1.add("sonali");
l1.add(56);
l1.addFirst("first");
l1.remove(2);
l1.add(2, "middle");
System.out.println(l1);
ArrayList LinkedList
Best choice retrieval Worst choice for retrieval
Wrost choice ins/del in b/w best choice ins/del in b/w
growable Doubly linked list
Random access implements Does not implement Random access
Vector
Synchronized.
import java.util.*;
class Arraydemo{
public static void main(String[] args) {
Vector v1 =new Vector<>();
System.out.println(v1.capacity());
for(int i=1;i<=21;i++){
v1.add(i);
}
System.out.println(v1);
System.out.println(v1.capacity());
}
}
Stack :
LIFO
import java.util.*;
class Arraydemo{
public static void main(String[] args) {
Stack s1 = new Stack<>();
s1.push("a");
s1.push("b");
s1.push("c");
s1.push("d");
s1.push(34);
System.out.println(s1.pop());
System.out.println(s1);
System.out.println(s1.search("c"));
System.out.println(s1.search("abc"));//-1
System.out.println(s1);
}
}
import java.util.*;
class Arraydemo{
public static void main(String[] args) {
Stack s1 = new Stack<>();
s1.push("a");
s1.push("b");
s1.push("c");
s1.push("d");
s1.push(34);
System.out.println(s1);//[a, b, c, d, 34]
System.out.println(s1.peek());//34
System.out.println(s1);//[a, b, c, d, 34]
}
}
Arrays->single variable->multiple value
1. Arrays and Collection->primitive are not allowed im collection and obj in both
* collections = it is a utility class present java.util pack to define sevral utility method like sort ,searching
* collections framework= It defines sevral class and interface which can be used by these group…………
List l1 = collections.SyncronizedList(al);
list(1.2v)
stack(1.0)v
child of vector(LIFO)
Enumeration
import java.util.*;
class enumer{
public static void main(String[] args) {
Vector v1 = new Vector<>();
for(int i=0;i<=10;i++){
v1.addElement(i);
}
System.out.println(v1);
Enumeration e1 = v1.elements();
while(e1.hasMoreElements()){
Integer i1 = (Integer)e1.nextElement();
System.out.println(i1);
}
Set Interface
HashSet(1.2) SortedSet(1.2)
LinkedHashset(1.4) NavigableSet(1.6)
Treeset(1.2)
HashSet
import java.util.*;
class enumer{
public static void main(String[] args) {
HashSet h1 = new HashSet<>();
h1.add("neha");
h1.add("sonali");
h1.add(6);
h1.add("neha");
h1.add(89);
h1.add(null);
System.out.println( h1.add("neha"));
System.out.println(h1);//[sonali, null, neha, 6, 89]
}
}
LinkedHashSet
The underlying datastructure is HashTable + Linked List (that is hybrid data structure).
Insertion order preserved.
Introduced 1.4v
(rest same hashset)
import java.util.*;
class set1{
public static void main(String arg[]){
lh.add("smriti");
lh.add("anamika");
System.out.println(lh.add("neha"));
System.out.println(lh);
}
}
Sorted Set(i)
TreeSet
• The underlying data structure for tree set is Balanced tree.
• Duplicates object are not allowed.
• Insertion order is not preserved but elements are inserted according to some sorting tech.
• If you try to insert heterogeneous element you will get class cast exception.
• Null insertion is not possible .//null pointer exception.
Comparable(i)
10
Returns –ve if obj1 has to come before obj2
20
Comparator(i)
import java.util.*;
class set1{
public static void main(String arg[]){
if(i1>i2){
return -1;
}
else if (i1<i2) {
return +1;
}
else{
return 0;
}
import java.util.*;
class set1{
public static void main(String arg[]){
if(q1>q2){
return -1;
}
else if (q1<q2) {
return +1;
}
else{
int a = i1.compareTo(i2);
return a;
}
}
Comaparable and comparator mei difference
Map
LinkedHashMap NavigableMap
TreeMap
Map
• Map is not child interface of collection.
• If we want to represent a group of object as a key value pair then
We should go for Map.
Both keys and value are object…duplicates key not allowed…value can be duplicate
Key and value pair is known as entry
Hence it is known as collection of entry object.
Obj.put(“key”,”value”);
1. Set keyset();
2. Collection values();
3. Set entrySet();
Entry (i)
It is a pair of key and value which is known as entry s0,map is a
Collection of entry object there is no use of map without entry.
Interface Map{
Interface Entry{
Object getkey()
Object getValue()
Object setvalue(obj)}}
HashMAP (1.2)
• The underlying DS is Hashtable.
• Insertion order is not preserved bcz of hashcode
• Dup key not allow.,value can be duplicate
• Null is allowed as key but only once(value any time)
• HashMap h1 = new HashMap();
• Best choice for searching operation
import java.util.*;
class A{
public static void main(String[] args) {
HashMap m1 = new HashMap<>();
m1.put("sonali", 700);
m1.put("prerna", 800);
m1.put("neha", 567);
m1.put("anushaka", 600);
System.out.println( m1.put("sonali", 7800));//returing 700
System.out.println(m1);
//{sonali=700, anushaka=600, shivi=7800, neha=567, prerna=800}
Set s1 =m1.keySet();
System.out.println(s1);
Iterator i1 = s2.iterator();
while (i1.hasNext()) {
Map.Entry ME = (Map.Entry)i1.next();
System.out.println(ME.getKey()+" "+ME.getValue());
}
}
}
LinkedHashMap (1.4)
It is child class of HashMap including method of HashMap.
Data Structure underlying LinkedList and HashTable(Hybrid)
Insertion order is preservrd.
import java.util.*;
class map{
public static void main(String[] args) {
LinkedHashMap l1 = new LinkedHashMap<>();
l1.put(12, "neetu");
l1.put(13, "kriti");
l1.put(14, "deepika");
System.out.println(l1);
}
}
IdentityHashMap
It is same as hashMap including methods of constructor except following
difference.
1. ==(ref) 2. equals(content)
In the case of normal hashMap jvm will use .equals method for
comparison but in case of identityHashMap comparison on the basis of
==
import java.util.*;
class A{
public static void main(String[] args) {
IdentityHashMap h1 = new IdentityHashMap<>();
Integer i1 =new Integer(8);
Integer i2 =new Integer(8);
h1.put(i1, "sonali");
h1.put(i2, "smiriti");
WeakHashMap
It is exactly same as Hashmap except
In the case of HashMap even though object does ‘t have any ref .it is not
eligible for garbage collection.HashMap dominates the GC
But in case of
In the case of WeakHashMap even though object have any ref .it is
eligible for garbage collection.Gc dominates the WeakHashMap
SortedMap
It is the child interface Map if we want to represent a group of key-value
According to some sorting order then we should go for SortedMap
Sorting will be on the bases of key.
Sorted MAP defines following metods{102,112,123,144,567}
firstKey(),lastKey(),
headMap(123) ----(102,112),
tailMap(123)=---(123,144,567),
submap(112,567)->(112,123,144)
TreeMap
The Underlying data structure is red black tree.(insertion order on some
sorting)
WHETER we are depending on DNS or CS there is no restriction of value
But the key should homogeneous.
(after 1.7 v null inserton is not possible in single time)
import java.util.*;
class A{
public static void main(String[] args) {
TreeMap t1 = new TreeMap<>();
t1.put(56, "sana");
t1.put(6, "sonali");
t1.put(26, "anamika");
t1.put(13, "sandhya");
System.out.println(t1);
}
}
MYSQL DATABASE
Basic Commands
1. show databases;
2. use grastech;
3. create table eskill (id integer ,name varchar(50),psw varchar(50),city varchar(50));
4. select * from eskill;
5. select name from eskil;
6. select city from eskill where psw="45@p";
7. select * from eskill;
8. alter table eskill add column mobile_no integer;
9. update eskill set mobile_no=897966789;
10. select * from eskill order by name;
11. select * from eskill where name like '_i%';
12. select * from eskill where city in('delhi','meerut');
13. insert into eskill
values(4,"neetu","425@p","goa"),(5,"neha","78@p","meerut"),(6,"nancy","89@p","gurugram");
14. select * from eskill where id between 1 and 3;
15. select distinct * from eskill;
16. select max(id) from eskill;
17. truncate table eskill;//deletes data
18. drop table eskill;//deletes table
Dtabase Constraints : are used to limit the type of data that can store in table.
not null : The not null constraint enforces a column to not to accept null values.
Unique : The unique constraint uniquely identifies each record in database table.
Primary key : The primary key constraint uniquely identifies each record in db
It should not have null values and single table a single primary key.
Check : The check constraint limit the value range that can be placed in a column.
Default : The default constraint is used to insert a default value into a column if no
Foreign key : The foreign key is used to link one or more than one table together
Means a foreign key in one table refers to the primary key field in another table.
Composite key :
MYSQL
JOINS
Inner Join : The inner join keyword selects the records that have matching values in both
Table.
T1 T2
Left Join : The left join keyword return all records from the left table and matching records from right table.
Right Join : The Right join keyword return all records from the right table and matching records from left table.
Self join : A single table will join itself…..
JDBC :JAVA DATABASE CONNECTIVITY
1.Java standard edition(j2ee/jse) JDBC[standalone]
2.Java Enterprise edition(j2ee/jee)sevlet/jsp)[web
application]
3.Java micro edition(j2me/jme)[mobile application]
Menu
JDBC Store(Database)
(student.html)
Kitchen
(servlet):processing
Table(result.html)
JDBC : JDBC is a technology which can be used to
communicate with database from java application.
JDBC API:
1. JDBC API provides several classes and interfaces.
2. Programmer can use these classes and interface
to communicate with database.
3. Driver s/w vendor can use these JDBC API while
Developing the driver s/w.
JDBC API CONTAIN 2 package
Java.sql.package Javax.sql.package
It contains basic class and It contains more
interface for database advanced class and
connectivity. interface for database
connectivity.
INTERFACES:===== INTERFACE:
Driver,Connection, Datasource,Rowset.
Statement,PreparedStatement
CallableStament,Result Set
Classes:== DriverManger,Date
Types of Driver
Type-1 Driver
Also known as JDBC-ODBC bridge driver.
1. This driver provided by sun microsystem as part of jdk(after 1.8 not supported)
2. Internally it will take support of ODBC driver to communicate with database
3. Type-1 Driver converts JDBC calls into ODBC calls ODBC driver converts the ODBC calls into Database specific
calls.
4. Slowest driver and for windows(not portable) only (thick)
DB
1. It is same as type -1 driver only ODBC driver replace with Database Specific native lib.(written non java c,c++)
2. We have to install vendor provided native lib on client machine.
3. Type-2 Driver converts JDBC calls into native api partially calls native api partially calls are directly
understandable by db.
4. Portable.(driver platform dependent)
1. executeQuery : If we know the type of the query at the beginning and it is always select
query then we should go for executeQuery() method.
Eg: ResultSet rs=st.executequery(“select * from student”);//DQL
2. executeUpdate : If we know the type of the query at the beginning and it always non-select
query then we should go for executeUpdate() method.
Eg: int rowcount=st.executeUpdate(“insert into student values(1,”gras”);//DML
3. execute() : If we don’t know the type of query at the beginning and it is available dynamically
at runtime (may be from properties file or from command prompt ) then we should go for
execute() method.
If(b==true)//select query{
ResultSet rs = st.getResultSet();
while (rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getString(2));
}
else{
}
int rowcount= st.getUpdateCount();
System.out.println("The no of row affected"+rowcount);
}
PreparedStatement : It is a Precompiled Query. Because at the beginning associated with query.
Statement PreparedStatement
If 100 times execute then 100 times compile. 100 time execute but compile only once.
Req + compile + execution + Result Req + execution + Result
At the time of creating statement we don’t provide At the time of creating statement we provide query.
query.
Inserting large data is difficult. Inserting large data is easy.
Callable Statement : To call the stored procedure in database we use callable statement.
Statement(I)
PreparedSatement (I)
CallableStatement(I)
1. Database MetaData
2. ResultSet MetaData
3. Parameter MetaData
Metadata about database is nothing but database product name database version.
Metadata about resultSet means no of columns each column name and column type.
Metadata is defined as the information that describes and explains data. It provides context with details
such as the source, type, owner, and relationships to other data sets. So, it can help you understand the
relevance of a particular data set and guide you on how to use it. In a nutshell: Metadata is a cornerstone of
a modern enterprise data stack.
DataBaseMetaData(I) :
It is an interface present in java.sql package driver s/w vendor is responsible to provide the implementation.
ResultSetMetaData(I) :
Java.sql package contains extra info about ResultSet.
rsmd.getColumnCount();
rsmd.getColumnName(int i);
rsmd.getColumnType(int i);
rsmd.getTableName(int i);
ParameterMetaData(I):
When you want to get extra info about Positional Parameter.
Psmd.getParameterCount();
Psmd.getParameterType();
Servlet
Servlet is a web technology which is used to develop web-Application.
Web is basically a system of internet server that supports specially formatted documents.
REQUEST
Client
SERVER
RESPONSE
HTTP : is a protocol that clients and server use on the web to communicate.[Stateless]
HTTP Request : Is a packet of information that send by the client to server.
HTTP Response : Is a packet of information that send by the server to client.
It creates Web Application provides interfaces and classes .Must be implemented to create servlet.
It can responds to any incoming request .Deployed to create web pages.
It is Robust and Scalable.
.
START Init()
Initialized
Service()
Handling Request
destroy()
END
STOP
• Web Server : Is a application used to receives the request from web browser and process with help of
Web container.
Servlet Config :
The RequestDispatcher interface provides the facility of dispatching the request to another resource[jsp/html/servlet].
Client
Response
RESPONSE
Include()
INCLUDE() : SERVLET- SERVLET-
1 2
CLIENT
RESPONSE RESPONSE
SpringBoot
1.Introduction to SpringBoot :
What is spring Boot
Features of SpringBoot
1.Spring CLI : SpringBoot CLI allows you to groovy for writing springBoot
Application and avoids boilerplate code.
3. Spring Initializer :
This is basically a web application, which can create an internal project structure.
4. Spring Actuator :
5. Starter dependency : with the help of this feature springboot aggregates common dependencies together
6. Auto-Configuration :
The auto-configuration feature of springboot helps in loading the default configuration according
this feature
of springBoot ,ensures that all the application made using
spring boot are secure.
model model
Front-
controller
View(html/jsp)
Response