0% found this document useful (0 votes)
165 views18 pages

Dashrath Nandan JAVA (Unit2) Notes

1. Java collections provide a unified architecture to store and manipulate groups of objects. 2. The collection framework contains classes and interfaces for common data structures like lists, queues, sets, maps and more. 3. Common methods of collection interfaces include adding/removing elements and checking if the collection is empty.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
165 views18 pages

Dashrath Nandan JAVA (Unit2) Notes

1. Java collections provide a unified architecture to store and manipulate groups of objects. 2. The collection framework contains classes and interfaces for common data structures like lists, queues, sets, maps and more. 3. Common methods of collection interfaces include adding/removing elements and checking if the collection is empty.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

classmate

UNIT:2 Dashrath Date


Page
Namdam

allectin
Collectier Ln jaua is afameuok that praides en
Lanckitectne to stere and manipulatu he ge f

Collectien fameuek ebesents a unifid anchileckre

*Hienaxchyi
Jhe jata util bactage cotains aucassesand inteface
tor he lollectiern frameuask
Iterable : In erface

- - e : Impements
exends.

List Quene Sefl


|Hash et
Array list Pricriy Qutue
nked it Sorled Set!
Linked tash[et
T

-Necton
JArray Deguel Tree S e t c
Stack
*Methocs af (ollechion 4ntenlace:
Public boelean add(Ee) :insert an elemment in this Cellecten
Peblic boelean Yemove (Ch;. Ele): elete an elenent fron the (8llehen
Hbublic t Siel) : retuon the total nmbe of element
Checks cellecton iu enpty:
iubic boolean eguals (obEle) : 4/ mathes teo celleclien
clAsSMAGe
Date
Page

* Terate indeface:
eator intojace ueidea he Jailty g ttraling the
element ina tasuand dinction only Jhree chods o
) Publie boolean hos Next ): Tehoen tue if ileatr has more element
D) bublie Bbjctnext (): ksenthe element and move Cuvsor pinka bles
i) bublic usid Yemove ): Yemove Lost element etened by ileiat,.
inkeol List
i) Diagram in Hienovchy
DJhe auxaylst implements linkedllist insement the
the lit° intntae cellection intofacee
dubly lnked list t
to store tke slments.stene Hhe element:
iv) dt can act as a litonly t can act as a ist and Quu
be t implemet lit enly.| both
Qnd accsino oloto.J Ldata
Vi) Manisulatien usle Manibulatien u fast
Vi) Conshuctoys t oArnaylst(0> uyalinked bste) : Congbucemphy lit
Avayist(olleeion C): "linked listolection c):
Ayoylist(nt Capaiby):
Sromye import jauas utl.* imbart jaua- util o*
class
phath clas Dshrath
pubie sttie woidmanSting Ioay) þublie statie uoid mainShing
Araylist<stingy list=huw Araylist LinkedistKsbing) al= new inked ust O
ist add("Dash ah): al add (" DQshrath");
ba st add'Nandan); alo add ("ANandan");:
ioratr ib= list. ieretor (); erator<shin2 ib= al itrabrl
thile (it. kashint0) While (i has Net0)5
Sap( ib nert); 332 SoP(iho
0utfti Dashyam
natO);
Cutbut: Dashyath
332
Nomdan Namdam
cassMste
Date
Paqe

4 mab ontains ualues bn he basis of key ie Kay and


uolue pain bach Ky and value fain is noon as an enty.
Hashing iu the few a couenting an chict into an
intisir ualue h bntigu ulue tilyu in iiolxing
Bucket
key= 67 Key=55 equal(): Chces egyatity
1 (key-21 Val 45 Vel=10
Val= 89
n eact next nextsobash codel): Ketrmm hefe
2
AlDcakion of hades in Bucket |oft the ohjectin iahqer fomj
101
Buckek: Anay ot /odes

Hesh maþclas nplementa Mas intenfac wtich ab|


implementi
lleur s to stohe key and usle ain
hnt ky sheulad be wnigue Abztrac Mab
lextens
Hash Map

Constu ctors : HashMap , Hashmap(Map m),ete


Note:HahSct contains ony uaues whertas Hashmab
Centainsnentuy (key and Value )
*TauaJaeMas Clas Mabl
Texerds
Jaua hiee ma class ts aed black Serked Mab
tee bossd implementatien dt jeuides extend
an cficitnt mmeans b stoning ky- Value auigable Masl
bn dorted rder
inplemutt
hua TeéMah ynconiged obo Tree Ma
(onzhuctox :TieeMap), TreMab(lomparalor <?supen ks
comparator)
clAssMAte
Date
Page

Examble Naua Hash Mep


Import jaua tilo K3
Jaua TreeMas
import faug util 3
bblic clas Hash ap Class Tree mas5
s Pubc JBatic usid maim (hinello þublic Dotic uea maim
Hosh map<integer, Shing) map = Tremap<inleger, Srng> map = hew Tresn
meo HashMas <integer, Sting>0;
map put (1,"Dashath ") map put l00," Dashxai)
mab put (102 " Namdan'');
put l 2, "Nandam")
sop t"Tenating HOShmap");
map: put (10l "Singh'");
folmas-Enhy
or(mas Enby m mapentysu)s
7or(ap"Entry m: maþ entyse c)Ssop(mget key (9 t m'get laluet)
s sep (m:getkay()+" "+mgt Value0); 33 3
Cutputi 100 Dashath
333
Otput 1 Dashath 1o! Singh
Nad an 10 2 Namdan

t a n Hastset clas
Jaua Hashet clas cued to cCeate a collecten hot
Lsesahash tasle for storage " Hohset stoes the
elements by sing
sing
Java Hashsét clas
aa mechanism calleol hashing
linked Hshset
Kexends
ellecie Collectipn
ext
im þlements St
Abstact sot rblament
Abskact Set
Texens -ext Sorted St
Hosh Set
inked Hash set Nauigalle set
Tmblemeny
Fxame: Set
Class tshSet wile lfe hasNext)
bubie sIate loid man (Gny la»g) Sep(ienet O); 334
HoshSct (sbingy slt= newhshSet);
Set add( "one'" Stadd |" To");
Sct add " Ihne' ;Set.cd("fous'); hree
IeatoyKsting>= Set: ieratoy t);
elAssmate
Date
Page

Multitthrcading i a gaua fatre that alsas cenzuni


ereatin tue chmene bands ya prepam, hread
Jheads ane
"NewtAneuo Thread beqen.
New Fyead)>New gelRunnale Yun( ih lye ycle
Rumable ARrthread
Breubion. sstarkd, t becorna
bndo Aunnasle
Deadt haiting|osu "Rutning, bwaiings
Dead

Adiaailage Ruadantage
imultanLsus Qccess to multe
aplicatien
Hew t cueott hread
By estending Thyead clau by ialmentng unnabl
las ulti exends hyead
Publie uoid yunc) clas Mult2 inplemnt Kunnable
Sop(thread is eming)5q ublic oid n)
PS Vm(Shirng Jangs) SoP("threac is unntng');?
Multi f new mult (0j

Thyead ti new Thread (m1);


Dutpt2 thuead u ranningtl-sBatC03?
aASSMAte
Date
Page

ynchuonigatien in yaua i the tapabilty ental


hcces t amullblehads to any shard teswrce
"ti mainy ssed to
Io peeuent sensisteny preblem

D) Process syncknigotion
Helps Keeb threads from interfeing win
Mutial Erclisie one anofier sile Shaving data.
By Snchron'zed method
block
By Stat'e synchbnigation
Cooperatienlner thread ommuniialien in jaua)
i Synchaoned Method
4is uidto leck an byect thlt =ti?
for any shared HesDUNLe. Puslie ueied yn (05
bxamble: cas Table toprint Ta,e( 100)3 33.
ynchonized void þint (int n)s
Aalie clas Test Synchrenigatien
SoP (h*); PS ym (Sbing(] arg)f
Tabe ebi=new Table);
CaHA (aaptine)f sop le);i;
clay ma Thsead! exlende Thyead

t00
clay My hxead?exends Thyeag S
200

?Table tj joo
Date
Poge

) ymchronigud black
3can b wsed to bentom you makL any sale melnsod
dyndiangalin
clas Tabls
ueid þnt Table (int n)

atealCrcspicn e)fsople) 33
Rest Code Bome as
dynchaonigd method's lode

Lock: ychamizatien úbuill anend an lntorgal


yect has an lock aseciatdl wuis it
Pisitis ae
Hebtesuntd by anumben behuien l anol io. Jhe Hread
duten sehiduls Hhe thsead according to thein proniy
Deoult butohity of a hread is 5(NoRM RIARTT),The ialu ot
MiN PRIORITY i 2 ond Value f AX- PRIORI TY Ls 10.
import java. larg.; thisetPioriy (e);
use clas Theadl exknds byeodf th2set Prienty (3)
fubtic d n0{sop ("Inside")S?
PSVM (ShingtTargs) $
ThreadP th1 = neo ThreadPOS
hread P th2 =mew ThreadpOj Paoniy of tm : 5 /default
sepl"fitniy mt" h1geRierity o); Pronty f 62:5
soP("nonty h2'+ h2-gfiorityo);
classmate
Date
Page,

he uapbr class in faua jeouiole he mchaniim to


Count timilie indo itict And Ghject inlo primitliua
xleachy: Compagake
Nuzben Charace Bocean
Dobte Ebat lohg short Byk
4utoboring: he autemai conwsin bf yimitia dalo type
Char to Chaacer, long to long tloat to FioaB , boolean to Booleam

þsVm Sbing L7ar3)5 byk bytialu =bye obs


byte b=10; 0nt intFValue =intib) )
Choy Chanelu= Charei i
chan C=a; psnting brimities
tato boving: yerate);
Sop/"int velue:" ntvale);
Byke bytect= b; Sop/" char Valust hanvalee)?

Chanacer chartfz C; CukputByte object: 10


7Phntng o6jects Inleger Cbjecd:30
sOP("Byle bhject: +byjecH); Charact Dhjed : a
|SoPC"Iakeger Chject:'+ intob ); byte alue 10
SoP(henacke Chyedt:+ Chorth); Tnt Vale : 80
Cha Value: a
aassMate
Date
Page

io
Consumey in,
tis an Dbstaction that Cihen broolues or
DByte Sheamy : Roauide lonunient means fo hanalng knh
and autut st byty hut
TijutSheom (read data brom oute) fandlig inhe
Ano
Outtut Styeam(Stir data to odegination)
i) Charackex Stseamy:. .ou handling nput nd butut st
ChavacteHL- Readr andl Winn oe
Charactor sheam:
Fle onsole
oking oe Io Stream: Asocke
Al Consoil Socket
oo1
TnbutSteam Output Sheam
Souxe Java ioro Destinaion
Reacl
Abb Wsite

X Byke Shean. CharacteH Streom


impart java i0:*
þublic clas Cobyfile ? Some ode
PSVm/Shing tuangs) throus IbExceb:
Fie InpuShream fin nuut; fle Reader fin= rul;
file QututSream fut =nuls File wrier fout= nelj
O fAin = nw Frs("input txt");
tout= newFos ("inpuf tt ");
int C;
bame lode
fout. uite(0j
finaly
Ains Clesel
Date
Page

I/O Stream
Byte Avray FlteH bibed cbfect T/oShream
sheam Io Streám Io, Stream Ho Steam
Data Buztered Push Back Input Stream
oStheam Pint Shream

"Buksed bykSheamj allus yauo to do Io shonahonu en


mDe thamo byte at a timi shence ncuasing þtomance
StandadSthea, wthee the uen's bIogyam con tate inbut
rom a keyboand And þuduce otput on the computn sarn
Standand Tnput- System in ;Stamdad 0utput- System:oud sSyster

Cbject Koialiyotion is he pusces of sauing an Ayict


lbuilding thoue bytes into a liue bhject at seme fulwre
time Ye an nly derialje hu btict af a cless hat
inlmenls iatyabe lnteyac
Sesuolinakorn Jesesiali2ain
2Ale
Jcbject Byte Sheom Byksheam Objec
Dalabase

hene the byte steamn i sed toleceate he actal


jaua styict in memeny
dlssMate
Date
Page

Ex:
Import java- io.; imþort java- jo.*;
Clas Example Class Example
Psvm(Shhng (34r9s)tys PSVm(Sting C) rgs) toy
Student sI= new Student(16,"Dr); 0bi. InbStream in haw UlsT
FOS fout= new FOS(" t); Shudents= (Student) in-1eod Ohjec Ü;
Object-OS out= nw O0S (fou); Sop( S- id+' "+Sname) ; G

out writ Ohject (S1); in: close 0; 4


Out fush); Out- Closel); CotehlExcesion e) fsoP(eli;
Cateh (Ercepione) SoPlel3 Outbut : 6 Dn

Orput: Soualijcd
* he keyuod: tramsient
hanaint keyuord is uAed in Objcct Senaliatin h
tranint oyuerd fuuids t uith the abilathy to
contsl th srializatien þucs and giue w fleibilil
*ening:
eract
he sbject clening s a way to
reot
clas uld'to clone an Clone () method ef Ghyect
’Jhe jua -lang. Clonable
buby the clats wthee inerkace must be implmes
&hyect clone ue uant to cHeat
alassnste
Date
Page

* Annatations
Anmetations ane used toadd meta- data to the aa Elements
ie instance variable , Constuctors, mehods lases, ete
Annotatien stat uith @
lytes a Annotatien
1 Morkex nmetation i eOvenide annotation aswnw hat
he subclau method ia DreHKioing the parent clas methad
Hhas no method

Value Annotation 3An annstatisn that has Cne method


TestAnnotaten ("festing")
3 Multi- Value Anmetatien i an amnetation that has mere
Hhan ene method.
Test nmetation (Owner "'Dashyah" , Value ="Nandan')

*ustom Annotations
sUH-oened annetation! can be sed to nnenate
usgyam lements
O[aen spcfen] intrtace (Annotatien Name>
Data ype (Method Name >(1 elefaut Valua] ;
Examþle : Thes:
Clas Animalf Predehined annottions :
Public uBd YUn()F PDeprecateed oveice
Sop ["Running"D3?
Clas Dog extends Animelf @
Subprehaenigy SaseVanang
Pebllesveude
A
td runl 1a-Meta- annotationy:
soP' Dog)532 Retentin Dowmentd
Psvm/shsng [largs)
dl" yun033 3 13 (ustom ainttatiers
Outut : Do9
beon important sín the deueligme
anguape Jirit has
ates-diwn deuelepment
sting is the þuecsef checking undinalt an
llnit testing iu dne at the dlevetohen'slwel
Feases:
DJUmitu an oben sourceframeuork
Prouide annotatior to identiy test method
np Prouide test nennes for Humningtut
to wmiti edes faatea
Unit Test Case i Jt i a bart f code, hich ensws
hat aneher bat code(method) orkA as exhected
*AnnotakiorA fox Junit teting
Test dhecitis that mehod is testmehod.
Before clas methed invoked cnly once, before
Beore mehod inwoked before tet gBasting al tet
Aer , 9 Afer Clas case

%AMent las
Jhe orge jnit oAset clas
bueidle metods to ayet
LMetols :
Void asertTruel bookean
Concliton)
Check that concliHon
Mad att Nul |9hid y) : hck
that ohject ii ne
alkssste
Dashrath
Nandam
Date
Page

tJDBC : Jaua Dahbase ConnectiWity


JDBC isiA aa jaua API to cenmect' and eutt gueny
ith database JDBC API uaes jlhc duiuers to cennect
uith the database

* JDBC OBDC
.hn Database Connecity: Open Daabase Connectiuity '
i) Uscd yor eny Jaa langioges Used for any lang. ,<,c,
ctt, Ja, ek.
i) We can le it on any blatorm Ondy hhindasBatform.
1) DBC i Qhjcct Oriented
) SunMlcresystom in 13?7 Inteduced by 1Miesosat inîn 1992
1
*TDBC Arhitectue
Java AbplicaHon
TDec diver Mamager

TDBC/natve DBC/ODBC JDBC Drive JDBC middewae


Bridge bride (Dems Specife) (vaies DBns)
JNaHve dnver
(DBms Speic)o0DBCDiveh

DBMS

Xouking wtth tabbase using JDBC


Oep1:Lmþortin Packagesi im þort java- sq1.B; ,inmport jave-mat,.*;
Loading JDGC Divers : clam or Name("ovacde -jlbc diver -Oade Dnve") ;
3:| Create onnection : DriverMane getannechen(wd, Usen, Pasword) ;
4: Creaking aStaement boject : Statement Shmt =Con- Creake StalementO;
5: keuke Quny and Retning akeult Set tbjict
6:
7:
PAucsing'he Rsutt set
Clesing the Resut set and statement sbject :
8 Close Connectibn'
elaseate
Date
Page.

JDBC Driye.
JDEC Diver is a oóottuwase compenent that enos jaua
abblication to intovat with the dotabase hoe are 4 typa
TypeJ: JDBC- QBBC Brdqe Tybe 2: JDBC-Natine API
4tconunts JDBC methed callsNatue-API þay-Java Driver
into the ODBC functisn calls. Convert JDBC Calls on theclient
ApI foY OYaclei or Othen DBMS.
JDBC-0D BC 0DBC Vendor I. DE Jdbe APT
Jaa bide Dhver Datab
Naive
Java -APE Vendor
disey DB
Dver ib

Type3: TDBC-Net Pune Joua


tu fully rittem in jau. Jabc APr
hree- tin ashhoach is Netwoyk
Aeo to acces database LAppl. Protoce Muddlwane
Driver
No clint dide librny

ybe 4: 100 7. Pure Jaua.


Convet JDBC diectly to native APr. :Jabe API
ed by RDB MS. Je daLsr't IJaw DB
ned -Appn Shén
cient's machime Drtvet

t MVC hamellouk
Zhe model- iew -Contoller MVC
battrn that ssenates an aplication nto the
man lgical Comperent- thé model, the uieo,
he conbélloro
alassnate
Date
Page

* MVC lombonents MVC flew Dioqrarn.


Mocel BrowSen Send
Three Comþonendi Viewt
Yeg.to MVC
Applcn.
dBrowseL
HContoller Incomingl request
)Model: olivected to Cortelle
he Model lombenent Corneapenls o all ContelloL
Hhe dat-Heleatd ogic he the lser Contoll
reguest Bform a Model

sti ued yor all the UIlogic sf asle' is mo del pesed to iew
D) Controllen :
Contstlen act as aintintace blw Jhe uiwendiy outbt
Model and lliew to busces al the Butput
busines legie and incoming Yeguest

XExamble :
import java).*3
clan 'db
Psvn (ShingClargs)$
ry$ Lood the ves
das for Name ('orade jWbc dnver):
Connecion (on =Drives anagyr 9et(onmictien Jdbc torace :thin:D
local hot: Is20: xe");
Cseale connecon bhject
Stalement Shmt = Con 'reate Statement U;
Resutset rs = execute Quexg("3elec+ *from student' ;
Sop("value fom shudent table ane : ");

SoP (rs gekShing (1)+""+ s:qetshing (2)+75 ge Dae(3) );


Con" cibse (033
Catch ( Excaplon e)? outbut:
Ydlues fom Studert table:

Sople333 21Bcs lUH6 Dashyath Nandan


21BSIL682 Aolitya Bansal
9bo
SOL SEQUENCES.
defenecd schema beund
that qeneHatos a Ceouence bf nmeic Value
he deuence of mumexic ualues is gennattol a an
Syptax: dscanding DHder
Name of the Sequen ce
CREATESEQUENCE Segumnte _hame 5
stt
START bLith Inital Value sStaning value tom where eg-
ncrement_Valuo alue by wtich Seg- increment i l
itey
INCREMENT By s
MinlALUE minmumValues min value ot sequence
MAXVALUE maimm_Value maimwm Value ot seqene
CCLENnCYCLE An excption wiu thrown if seg. exceads mar.Jly
BAher seg. reaches is setlinit it statfrom begnin
* Dual Table

Ldeaut in all OHacle dotabases Jhe table hasa singl


VARCHAR 2 0) cahumm callead DUMMY that has a Valie sf X
DESC DUAL; SELECT * FROM DUAL;
Outfuuti1amiluDType
9DUmmy.VARCHAR 2) X

bosic daa types e -la ksia


ThemicKBSst JDBC DHir tor S9Senuer. lses the D8C.
5l·Dati
Jaw- uiu afer
alassate nameol
long'byfet) Shing
baoleam Biq
mahceuble þacudurt
procde. andl00.stantvalu
Date.
Page uale
Jawa quey. aleguence
1faom
stroed masimm
panameteriyed
sthed start from
typce a
sting fom eateiL Iat
cata a Aaguencel
SEQUENCE
Create haung
to parametu
DECIMAL
BIG
IN
T BINARY
DATE
DouBLE egemce
BITCHAR a
as by by parametes uill hepeat
datadata
data L
lby
inchememt Quenybyitt
SQL
Senvez
Tyhe Retutuing
Retsiauing
OfeHatons: Retriiuing 1uth
&tayt 100
ale
Max beguence-l.
Linchernentid
100
"Ubdating O
minvale
Segence
bigintbinavy decimal
assing 2Bboue
Char
date float
bit
"

You might also like