Introduction to Java Programming Basics
Introduction to Java Programming Basics
what s JAVA 2
JAVA is
genral puxpose, high evel object -oriented
ptogramming Langage
Tt was orta'nay developed b James
a
Gosling
at Sun
eleasedin
& 1995, as coRe Component
Microsysiem
as nvA
Java has 3 editions
IAVA
12ME
Java to Java to Java to
Standaad edition
fnterprise Edition Miuuo Edition
.
1. Monolithic Paoqtomming Appxoach
3.
Procedunal
Sttuctuncd
BASTC
FORTRAD,
PASCAL, C
COGoL
No
Cc Sttuctuted approach but Proxcd utal Orientcd La03
a
featuucs o JAVA
Java is Compiled ass well as intepeted
4ongnae
i) Java is platfonm independent
i) Java suppotts object Oruentcd ptogtamming
iJava
Java is used to develop intcanet based applications
Ce
Cea sRYLET ,APPLET, 3SP CJava Seavea Pagrs)
(
class Fitst
public
Static void main String angs 1) of
Object
Prin StmeOn
[Link]. println
C" Hello World "); (outm
memben of
Al he Java progtcms
must be 60ved
b class namn
C:
C
>
Command Ptomp+_
>cd..
cd..
C >cd\ Command
tgmo
tih
ntetión
C:>cd 31
c131 javac [Link]
Compslatio)
to change
te teeel din, use C: d:
Output He llo
onld
Path settina
1. Cick on m P oR his Pc
Prtoperties
3. Advanced Tab
Envitonmental vatiable
5 Path (orn sHsttm variable)
6 Edit
7 c:\Program Files1Java jdk1s\ bin.
8. Save
1. Command ptompt
Entea
3. 8pe javac 4 press
the soltwar installed successttulla, a set of commords
)
wap to enteR int¢gexs 10 4RO and dispto the' Sum
class Scum
public
Static void main(Stung ogs
a class Add
int a, b, c
a [Link] (angslo1);
b-Integen-patse Int(angsl11);
C atb
he sum is"+c);
[Link] print ln
save [Link]
pLess Entea
The sum is 40
impot [Link].*;
class Add
'
public
static void main(Sttig ogsl)
Scanner K=new [Link]); K objec4 no
"¤mea two numbeus);
[Link](
int a [Link]);
int b K nextlnt();
int C atb
System. [Link] The sum is +c);
Compilejarac [Link]
Run java Add
7 impoe [Link].*
class Add
int ab,
new
Buffeaad Reader K BuffexedReaderlneu InputStncamRcad
[Link])):
[Link] CEnter oumbers);
[Link] Int([Link] ));
b: [Link] ([Link]));
catb
[Link] he sum is "+c);
Save>[Link]
compile javac [Link]
import [Link].x
class A
6ave Ajava
Compejavac [Link]
Run javd A
Dato ype
Data data avatiable will hold
e
the
tHpe specidies ype of
Datarypes mo be
o
Non-primitive
Cta sses
Primitt
int double 1otertaces
shot floa AR
L Stuna tt
booloon
eha
byte
fi
AV
81
Solor yNT Cuda
tnt bytts floot1 te
shont 2 double
long boole an
bit (1tue false )
chan -1 yt
default,
0OL s1docbk
5.4f floa t
loat [Link]
detble [Link]
Paimitiv
Dumeruc
1ndegaal
chakccdea
[Link] panttn
C4 "Hello"+ a) ; telte 10 naen
30 Helo
ysten, [Link] tb+ "lell .")>
fe
Function name should ith smal
begin tettet.
4 he classnome consists of onds CR
mutiple -theo itst
ofeach vOrd should be
capital, Pes (PascalCase)
So it is be to tollo
he mentioned ules while CAAatim.
NOAC
int
niegen paaseInt(ongslo1)
a meihod of ckass This methe
Here pase Intis ntegen
a imo
used to ConvCat a datatipe into JPR
he a bove $1atemen
conveats the
the
a
conte of
vaiabie
aags lo]
type 3
StoLs in
intcger
into inHeqen
(00P)
Object Ortentcd PRogrammio
It is a prrogomntnA pa4odim which deals wh he (on
cept of object to bu ild Prgiams Softwarc applications
It is. a progitammin
poradigm that
emor
alloos a mode o
asea
prognam 1ormina separat
by formin
modulonising
as unctionns that is sed as objeet
or data as wel
foca psulation
Inheitane
'
clas
Polymorphism
Dynamic
Delegtio
Messag
Btnding
passtn
ctass is a templaie
Or hrmework
tus
ghich
which
ob
ob,
A
Cts are CXeated.
be no. of
can an objects
For
fo a single
class 1heat
Objest
A s he instaoe of a class
A abject
is the basic tu time entits
o object
An object
6ste
o
oiented
he object epcsent
he
a petson, plate,
ca handle
a
.
bank ace-
that pogtam
0bjet (Stucdent)
Dard
Dame
Rellno
DOB
Adress
Ema
Function
SName
Sr
Sdobl
SAddC
SemaIL
Method
Ii
Method dofines he abili4 of an dbject
Tt is the enti*
entity hzougb which an objec4 intexacAs wh
walkn
un doga
the exteanal environment .
is an
etc.
eample of object then bak, bit i
aLits abilities.
object doa
VAbstactioo,
is the ptocess
Aastitaction ofrepresent ing essetial Aect-
cARcs ithout 1ncluding
the unnece
essan details C bock.
ound details).
£ncapsulation
t he
is process of combining data members (vauables)
tundt
membe functions (functhons) into
asingle
e class
vi- Inhetitance
The precess o Cxeating new class inheuting thc
4ne
behavioLn of one mona existing cdass
properies
known as înhez ttna mechanism.
g
is
3
Child Sub class
e LA (Exishrg)
(New CReated)
Hpes
Jnhexitance
Single
-iditectl ho SupPented b jcua
Multtipt but indReeil suppoatcd bsing intajace
Multi level mechc nis
Hiero achial
Multipath
[Link] Toheritano
When a ne»class is zoated" inheriting he Prope. b
hes behaiota of one existing elass hon tis knoun know
as inhetitance mechanism
single
b. ulthple
vohena new class is Cuat ed inhetuh
nheuting
Ahe
h
prop
ethes behaioun of oK mox existig lasses Ahcs
the
C. Multilevel
mechantsm.
LA
[Link]
When Ahe
H is koown
classes
as
ahieenchi a
devved ke
inhedtanca
ee uctent,
mmechaSm,
hon
CTnce Stxuestttae)
hybrid
twhen the acL deAved
classes
usina mora the
hen onc
tohostonte
HdnL
mechanism, te it is kaon as Hybid inhe.
mechanism
A aSin
[Link]
[Link]:th
When a new is esreate
clogs inheti
inhoitinm ke ptopea
behaiou fhos classeswhich
nc having
ties as multipbth inheu
class hen it is knocon
Some patcnt
paten+
tanca mechansm
ViiPolmophis
Te OOnd polymz phzs m Comes tzom 4he word poly
monphets foims)
Polmonphism
s he PLocess mechani s) which the
C 52 7 Additio
pe Palymo aphiEanlBndtime
Static Polymorphim Compile.
Dynomtc Polrmazphism
time.
Rn
poljmoxphismLate Binding
C-Dynanis Bicdtng
it s the prtocess o Connecting
one
praoJko)
to a0otho,ie
to be eaeuted n ep to a cal
d Deltgafto).
closs wil
act as data m
of one
when he object
in anothe class,then Such composition is
benCvoaiabl)
KQoa as deligat ion.
eAMessage Passtn
difeaent is koeun as
objects
he Communt caiion
betweun
esage passin
Assignmeot 03 01 2023
1. Oap to a sting 4 displaj
en
2. splay
displa he add" 4 scubsttactu of 2floati
no.s ustn Command
ne angtmers, Scennes class
type
ButfeReador volem
3 Desiga PrLogToOm
to dsptoy
he value o4 a cube uuboid
sphete lindu
tapezium
JAVA TOK.E NS
A
A token ts the Smalles individceal unid o a proge
TyPES
Tdentitiens Opetatots Constants String Special&
Keywords chosack
Keywords
Keqwod are he rsetved ords chich are use to
Statement
Al the keywords must be writ Lowercase letteu
goto
t
instanceoof pRotcetc
public
Retca
tru
40nsient
Operatorg
TyPES
1 Acithmetic opeiaton 6 Conditional operotor
[Link] 7. Speeial
3 Logi cal
4 Asstgnnnt
[Link], Decxeament
1. Arithneti
Artithmetit
Operaiors
openalou orc used
to constrtttct e
he mathema.
mathemati.
Calexpressions.
Meanuni Examplc
Operato
Additio
5 +3 7
.
Substiactio 5-3 3
Multipicatio
5* 10 /51-2= -1
5/2 2 5.-2 1
sio
Divi
S7 -2 =-1
Modulus diisio 5/2 1 * 1S613 1
55 50
Jote ge Ar:thmeti 5 15
ohen both the operands pei a
ahmetic operation hen it kown as integen
au thmeti
5*3
Real Aithmetic
an aith
when both operca nds ant 9tcgRal type
in
S1 +3-1
Mixed mode Acithmetil
whe one o ahe opecnds is
inteeyPe anothe
s Fal type, it is
know as nixed Hpe mode authme
S 3-1
[Link] Operators
operands.
QperatonA Meantns
Exampe
tess
Less
th0
than on egual to
53
S3CF)
C)
Gnaa ha S3 T)
3
Gnnatn han equel to
5>3 (T
F)
Dot eual to
53 T)
Result of opettenpression wher rrelationa opea
operaron
is sed is a Boolean Valu True on Fals)
[Link] Operaton,
Logical operrators at uSed to
to combine tolaional
erpress Tons
Mean i
T
Operato Exomple Result
Logical
AUD G)& C745) f
G (7<6)
NOT 5<7)
Not
A B A&&B A !B AAB
T
T
1 Asstqomen Opetaton
to avalue to
is
tesed as5
assi
Assignmeni perato
a vaiable.
e int
double
a= 5
b=7.2
float b- 7.3f,
Nott
with
Statemeni with shothon
Statement
a551geOpeato 551gaeN opetaton
a at1 at1
a a/b ; a b;
aa 3 a* 2R
a at(n*1) at nx1;
Temove
bra cket
the
VV op Exp op Exp
ilocrementOperato
sed add Ho ho
ncceament operaton is to 1 valtu
of a voiable
++a a+t
Post ocacment
Pae-locemen+
the valu 1 Fiest assij the
.
Incaease print
1 Fixst
valu
o4he vaiabte
Then incneasu ha val
[Link] piasiqn4he of he vadable 1 1
Yalue
e
att
ta /p: aS
int int a:5 e tnt
int b a41
int t+a
a
6 S
S)De ctemen4 Oper a10
ts ased to SubsAa ct 1 rom the Yalu of a va.
able
int a5 a:lo
int
b 7; intb:20
int C a>b )a :b inta<:b?atbx2 * b-a x 3 .
C: 50
p: C:7
Here,
the
a4e
exp3 wl
-he
Expiession-1
be
o/p of
will
evalua1cd
conditiona
be evaluaicd
its
exp
S
eSsion.
finst.
wil
Tf ttue
it's
be valu-
[Link]. Opecatoa
OpeiatOA Meann-
Bitwise AND
OR
Ey ampl
int
int
c:axb; irtb7
b:7
alb; d-> 7
t int aS5
7
int
instanaof S T
T T
bje
he
he 1he
De pending
on no. o opeLAnds peAaOA
cle ssifieinto folaroinj UPe
Pes
peAato
Bina
. Terna
opeseto
opeLcnd,it
"
when
's
calle
he operatoa, opestfs
uno
a
sing
at', att, a et.
opeicndi it's
calo bina
bina
abetc
)ena oesato
ope whe ihe opeca to n
opeictes 3
opeand it's calle 4A0 ay
ab2 a :b (conditimal operca to)
Dectston inJava
Stateeni
Switch case
1 stateme nts
.
[Link] istatements
ii. if-else stattments
(
Ladde else -if statements
iv.
Nes4ed fstatement Nested i-else sta4emens)
Simple if Statements
is ne-way conttol statement.
Synda fCconditton)
f
Stattment ;
e class A
static void
pablic main(tring angsl)
int [Link] Int (ogs to 1),
.
3
i-else statcments
tis a [Link] contro. stateme ot
Suntaa: class A
iSCcondlition)
pubic static void main
else
statement ;
3
eg clas A
,[Link] to (Hello);
3
else
C" World
Systtm. [Link]ý
Statement
else fConditien)
Statement
3
else
:
else if Ctondition)
Statement Statement;
3
e cass A
staie J)
publ void main(Sming acgsl
int
[Link] Int (angslo);
)
int
y [Link] Ini (angs[11):
int z:[Link] Cogsl]):
&&2>z
3
S [Link]("Gaeatest numben"+ 1;
else
Whe one
0hen i statement is
paeseni inside anothe
f Statement, it's koouon as nested f statcment.
Sntaa Ccondition) if
Cconditien)
fCcondition) if
Ccondition)
statement Statement
3
else
statcmeot;
ctass A
static vord
pubtic mainStting acgsl)
int [Link] (ags(o1);
int
if
Cx>y)
if Ca2z)
[Link] ptint(nHello);
3
else
- Find a o. Gmo1 df tt s
Nested f f.
class A
tt
int Z
else if Cz>y)
[Link] nzt 'is grc
a*st
else
Asstgnmcnt-3 11/01/2o23
1
Discuss about 3ava id CAals
a
oord
3. Oap to cs{ whethen tve R
is
not
Suwitch Case
Swtich Case 6taementa tis used to
ezecute cettan
task fre) multiple tosk to the
according congitioa
syotax
SwitchCExp)
class Color
Case valuai
puhit statie vcid
Statement mainung gsl)
break,
Case value
int P
[Link] Iot(a«gstol);
Statement B3woitch CP)
beeaks Case 1:
defaut:[Link] "uh
LOOPS
Lotps a used to exe cure the same
stateme e
again aain.
ecteAlie,
c Whtlo loop
In while loop. te
condition
Syota
whilcCcondt tton) wil be checked iast. -it f
is hen the conten G4
tue,
Statement
whle be
incte amentdecaeameot
ahe oop will ez
uotil the condition is
uteo
false.
alse
(ii) for loop
Hntaz
for Ciniiializat ion; condition; increment/de cAement)
Statement;
In for
fo loop, the inittal:2ation,
and
contion incaemem/deca.
ement Statements Can be e presetcd above.
while Loop
class A
e)
class
do-while lsop
A
Puble
publc statit void man (Otrion agsl J)
gsl
int a:
do
[Link] a);
att
}whilela« 5);
Jsoa leop
Class A
Puble statie
void manScm ags1)D
int aS
fonCa= 1 a<=5 att)
stem [Link] Ca)
3
Nested for-loop
When one foa loop is available inside anothe to
Loop
Loop. then it is knon as nested for
leop
fon a,
for
fona:1 a<3 at
Stattme
;
Fon Chs1 b<3; btt)
S.0.P
3 CHeto")
Difeence betweeo wwhile
Loop 4 do wh:le loop
whileLoop
oop
In while loop the condii-
do-whil,_
Jn [Link] toop. its
0 wil be checked first Contcot wil be execute
f it is 4te then he once ioitially & hen the (o
contco o he whil loop dit ion will be che cked .f
wi be exettco uniil the the condition is tu he
condition is false. he cooicO+ of -the do while
Coop be eecutc
wll cinti
3
staement
incaement/ decmant j
incement( decALmet
while Ceo ndition )
. OapP
t
to check whetha a o. is
-m preme O
Stiton
n
o
ot
Constan
Constant netens to a sxed valu hich cant be
changed dutina he exe eution of a pitogrom.
hinat inta 5 :
Hon
Hone 'a' will act as constant which
wilcontain 5
htoghcut the pte gton xeceution
Numexic
Chanacten
1
ote Real G.7, 7 s11)
.1
Choaaete
St 1
eeimal Octal Cn
Huradsuimal ens
(S72 (O5. Dx5 "el."
07 Ox7. b'
weltone
Struog
Sning ishe colection of choractens
sequene.
Srungs oAe
,
enelosed within double quotation mee
Symbo
ej Purnima Heln." et
Specia Symbola
Special
Special sumbols ae used in pit qtoms t0
pK oqoms to peador
Sevela tsk peafom
? 2 O, . auonding to
i,3, t,1,4# et.
the
rquinement
JAVA VIRTUAL MACHINE, LJVM
Lin
(
[Link]
( Java
javac Bgte
Code ndso
Progmam
(Compilea) anies
Tnteapaeter
Cjeva)
|
o's 1s
0S
he .class lis
Ahe
piatfoxmn
.class
independont
Codos
he kpocon as java.
JVM Contans intepTe 4cA
vth
Now-a- days, JvM is embeded operatingsgstem.
i
A 1ava uses unicode ststem o Repr chaac
Cten.
ASCII chaa-
Uniçode chata cien 4akes bytes whereas
Class_Object Concept
A class is he cole ctton of dissim:(om ttpes ofdass
methods
Sentax
class classname class Finst
vaiabls; int a
float b;
mehods;
void displayC)
default private
Same class Yes ves
pitoiectcd.
yes
pabic
yes
Same qe
packa yes No yes
yes
Subela
Same paekgat
yes No es es
Non-subclass
Dfteunt packag
No No Yes yes
Subclas
pakages
he
Privatee
data membexs
Eme-thod) a deelarad
Evaxiebles)
as ptvate
menbe funetionn
acnessi5l
within
the class on in hich the ate. declasd.
Publi
he data membes
ane
mem be functions deeldeel one
the
as pubic accessible eexwhone
in
pTeem
hee is no rostiittion on the of pub ic data
membes memben tun ctens
Protectcd
he data members me mbe functions deelarcd as
Default
is fox a class
Wheo mentioned
,
no access specijie
+hen tt is said to be haung the,
variable method
by detault.
access specitiel
e
default
ar access ble
Objectosa class
Syotax:
class
name object
nam
neu classnanc );
K new AC
class A
od dispta)
System.o ut. prtintinC'ttello vortld;
3
3
class B
AK
Pubbe stati 1)
void main
CS+nags
new AC
Kdtsplay)
wap pain
Piun4 additioo KCsult o nos Jo 420 ..
cla ss A
int
a,b,,
void displa)
a:10
b:20
Catb,
[Link]»C"he Sum "+ );
class B
Statie
pubuc votg main(Stiom ogst)
AK w AC)
[Link])
Las A
int a,b,
rotd $1C)
a 10
b 20
Yotd s3 C
3
Ctb
void S3(
[Link] printlah gum is="+C:?
Class B
static void man Stt ogs(1))
pubLe
ARnew AC);
K S1C)
K.$3
K.S3C,
A
cAass
tnt a,b,c;
void
dispta Ctnt i, int
j)
a'
bJ
C atb;
S [Link]"+ c);
class B
pubtc Static
void main (Stnting gl3)
A Kne AC);
[Link] C1o,2)
Wap
wap to displo the addition osar o ay nos
class A
class B
3KdispayCxj
3
class A
int a,b,c
Votg disp1Cint i, int j)
bj
void disp3C)
C atb
votd disp3C)
import [Link]. *;
class AG
float a,b, c3
displafeat i, ftoatj)
void
a»
bj
C at
Yoid show )
[Link]
C"Sum: "+ cO
class
B
p&blcstatic voif
main (Strung ongl)
float
in)
Scannen K* new SconnorSqstem. add
[Link] C'[oten 3 nunbens to
Spstem.a
[Link] FJoatC);
1K ne f C); a4 leat
At new AC)
tdispey Cj
t sho );
cla bject
,
ss
tuT
impott [Link]¥
class studsnt
Stning
it a
floatm
on int
t
int
j, fleat k,long int t)
Yot accept (tringi,
m: k
3
veid sheC)
System.o&[Link] nC"Jame "n)
[Link]:"* a);
stene paiel» ("Mork"t m);
Sytem edpirtih (Ren. "t O; 3
class S1
a1
Sloat m1
n1 [Link]*t );
m1 ne
zt floatl );
n1 [Link] LengD
ta
[Link]
cep: Cn1, a1,m1,t1)3
Statie Membeu
The static membeus Can be state data membets Cstatic
Stati data members Static Yatiable s.
i) static function /static
) Stotic block
meshod
A
knocwn
.
of eah
CP object
rariabia basis
* A static available as
per the class Peet
wheas non Static vadable is
dlable as the
basis. peA
object
e int
static" int "b;
void shoo C)
.StatictuNCHoD
when a functio
is celled
is
st atic
de clauod
unction
siatioid display).
ith static
kegon
the iit
A static meihod ca9 drect accesse thestatic vai
ables. he non-stathc
A static meth
Jo
cant
Odonto acces.
dree aecess
as he non-static Yariables . be
tunctions can
Statit Yoriables static dinec
class name the can
accesse bthe help
of
be acesse he obect
A
e class
int aa
Static t b
b
rotd accept (nt i,
int j)
bj
void show)
[Link]);
class 3
public
6tatic void
moin (Sting agslJ
A Knew A C)D
s*
K-aceeptCS,7)
O
[Link]
K. displa t);
A dis play) 33
We
h know
mat
har
function
a static
is static in JAVA
imeshoo ean
, be
2
acce
ssa Hh
oCct etating
he obec
As manc) is membe Ptioction of a
he
class in
object CLecteA.
Static Bloch
xe cutc Ras b
f
proqac) he
is
a Static block
ho JvM
a class Contans 3tatic Sfock ma ftncti on
class
0
Static int
3tutic
[Link]» (a)s
static
ptublic void mainCSwing ongstJ)
[Link] Stotic Block enettctcf J:
Block exeecute
Static
class
A
int
static
Static
[Link](n)
;
[Link](6);
Qz AP to he getest doub
P
displc le
;
class A
a, doubec b)
void displa double
f Cab)
[Link]
a+is greatesi.J
3
i Cb>a)
else
"is gtcatct.
System.6tut-ptintln(b+
else
Both a J;
lnC Egal,")
Systcn. otutptint
elass GrcatCst
Static void mainStnig acgsl
peublic
Scconen K new
ScanneSjste).in);
docble [Link] Double);
doubtt =[Link] C)s
A Z=new AC);
zdisplayD}3
Method ovetloadinmfunction overdoading-
When more han one method weth Same namehavina
eithet diffecent no. o azquments Ot ciffecnot datat
datate
oof angument o difeaent Ovtde of
Ouments hen
hen it
koown metho oveseadina
To metho ovetloasing. he me1hod ame is
same
bctt each method has ac eithar
ro of agume
ume
oK datatpes o aguments arde of
aqments
ee Yoid
vod
displa
disploy
Cint, int
Cfloar, flea)
data Yp
void
YO
dsplay
displa
C int, int)
class A
int a, b,
oid display Cint i)
[Link])
3
oid displa Cint i, int j)
a:
b
i
bj
[Link](a+" "+b);
class
public
A
[Link]
B
static
K:new AC);
5)
void
main(Stün args[ )
[Link] (5,10) ;
3
Inhetitance
inherit
inhetit a class, extends Keywond is used.
To
Sntax
child extends Parent
class class class
name name
class ebends A
class B extends A
class B eztcnds A
cdass C extends B
A class
class B extends A
Ci)tbrud
elass A
3
class C estends A
class B ext¤nds A
class C extend s B
ceass D extends B
aorite a progaam tot the implementatio tstngl
of single inl
inh
:
[Link].
class A
2void disp10)
3
class C
Public
public static
vo main(Steing oqsl1)
[Link] C)
.disp3 Os
Heto
Wold
WAP tort
implementatt69 o multilove inhesritenc
mechanism
class A
rold showiC)
class 3 xtcnds A
void shotuC)
[Link] printlnC"Cla ss
B);
C extends B
class
void sho3)
c); }3
[Link]
class D extends C
A Shos1C 2
yoid show1C) Bsho(){shoula,
D "): show30 ): sho2
[Link]"Clas show1
show 20 sha3
;
)
3 show
E
3
(Ghowl(,shoua
Shoi
elass
C
static void main (String acsl
pubbe
D K- new DC);
K.shou1O;
[Link]
shou3C
[Link] O;
,
3
class B extns A
Yoid shou)
[Link] printfnCcass B"):
C exiends A
class
showic
show1
show1),
[Link] "Class B"): sneu, show
Show3
show
class C entends B
void
shos3
[Link]'Class C");
class D extends B
void shouw4C
[Link] pronttnC'Clas D)
class E
PMEC
od oveuding
to method ovetridim the protottipe o he ttnctHo
ttnctio
as we as
is eattly Same Ah ptent closs
he thld cla ss
inheitane.
class A
void ow)
[Link] C"Hello",
Class B extends 4
void show
[Link] C"Oorld")
class C
pblse static void ma,(Stting angslV
;
A RneA AC
B Z new BC
[Link] C): lello
[Link] wor ld
Consttuctor membex
ConSTIU Cto spec taluncta
class A
votd
whose name s Same asthe clas
dispto name
The constztucton is
aetomaticala
AC Calod when an is catd
object
To call a cOnstULAOn
At new AC); V
[Link]) X
A z ew A(I0d;
A.y n0 A(s0,Co)
pes ot constructor
Default Constucton
ConstuctoN
Parametexized
Constuutton
CoPd
a Default
a
Constxucton
constuckon deoesn't acecp an agumon G
When
g, -
it is kneton as Dofa ult constucton
parameten
class A
AC)
[Link] (n (
"Helo
class 3
vo id ma'n (Sthting C1 arqs)
static
pubtic
class A
ACint i, int j)
[Link]
CX+
3
B
)
elass
1)
2pube Stat void man(tung osgsl
AK new A (10, 2
P 10 20
Cop Consttucto
a ype o ConstRuetor which
Ttis
p
special passe
the ot dass
edass
agtumert
ConsHucton class
Sntax nam
objece)
name
5
cass A
AC)
3
A Cint i)
t
void
ACA t
displa
:
class B
pubtc static
man (Stnng t3 a1)
voi
AK new
AK3new
AC
A
Foa
Ki =5
(10)
K2 lo
A
A K3 ne
K1 O A CK1);
ACK?);
K1
CFeatues
copieK3
f K1
[Link] 10
[Link]);
[Link] ;
K displayt
Coostaucto Overlocding
Class A
int
AC)
5
[Link](3);
3
A Cint
[Link]
(*
)
A Cint i int j)
2ei Jj Czt" "+P:
[Link]. priot (n
class B
5
50
Abstrcact Class
a claSS containS at least1 abstract mehod
when
tt is kpown as abstract class.
then
f of ao
class. abstract elass
elass
We an't create 1he
a
object
absttaed class
class thon t
thon it is
is
3
ckass
vozd
B
show )
exte nds A
[Link] ptint{»He
lle )
class C
abstitact class A
k
absttact void shetC);
class B eztends A
vod show)
[Link]ênCx +""+j" "t)3
3
class C
BK new BC
Kac cept£10,20,30)
Ksho()
1o 20 3
Super kewoTt
is a retezcnce varicble uhch
TheScpe kequotd
ess
s ased to ede immediate pancot dass
OR
object
ca
cal h
the
is sco ttnvake
Stper keoord
Constuctor hrom he d
chelh
cht cla ss
paceny
closs.
arg
child
of java supe kewo
Usage mmedi atc
Go be used to retea par
Supe
inslane variable
class
immedrdic
upe' can be Caseto invoke
mho d
to 0oke
to invoke immediste patcnt (c.
be uco
SupeA ca
COnshucton
class A
String c= "Red";
elass 6. eetends A
[Link])
class D
pubte
publie
slatic void ma(Sing rgst)
[Link]
3
Yelo
class A
void shou1)
[Link]("Hells")s
class B exttnds A
voic
void
shotu1
hous3)
C)
[Link]"dozld") ;
[Link] prntinC"elcene);
void show)
[Link])
shew)
3
class C
Z,show3C)
UUHEBtttaue
Hel Hell
Weles me
class A
AC ")
[Link] "class
3
3 entends A
chass
6C
superC);
Stystcm [Link] C" ckass B );
3
ckass D
stati void main S+ring aqs [j)
publ'e
Znew B)
class A
class B
)
class
ot
A Cint
[Link]?);
eloss BB A
class B ertends
int
Cint i itj)
supenG),
[Link](q)
;
class DD
20
TNTERFACE
a blue ptint o a classJtis c speif
Intertace is
b
tcation
hat mecns
whtch
contains
is
static
in
completclinplemented
inteface
constants
the
ad abstract
vaiables
aclass
methods
methods
declaned
aL Static and final
lt cG
CGn also be used to achieve absHraction
To
To inherit he data from inteutace to a clcss, implem-
final static
datatype vatiablei-value
varable2
varuablen
rcetuntype method1 Cparametta) ;
method2Cparameen)
mehodn
CparametC)
bimplamenti
displo
intetac mechanisn
Studao+
Nocpa intertaceStudent
Pubc
votd nome (Stong );
void clept (Stina dD
void ge int a);
New no1e
pa
A mplemorts Studont
pccblrc class
vOZd aqe
Cint
[Link]
a)
(
ln Age
"t a);
void show)
l
System.o&[Link]
([otcdace cxOmple
"
pubGc
AKOew A)S
[Link] Petc");
[Link]"
CSt ") Executhon
Cts); [Link]
[Link]
jnvac Ajava
K shos(J
java A
Seve
*DOHe : :jav
Both
in
sStudent.
San
thefolden.
java [Link])
shouldbe save
oAP to implement. multiple ioheaitonu injava using 'in4
ine
;
tace echanism.
Pet noteped!
pubb eneface A
veid dspiat
note pad 2
publc inteface 3
voi displeacD;
public cless
implemeis A,G
ScpaLa1
eps
votd
void
diplay
Ss4 c
dispícq2
t 10)
painttn C"Tote«face A ")
fuhlie class D
Aa
ts the collection o similoa pes o ata in
Locations.
memo
idt
int ol JL 3oe« int(01Jl3] ; 0,1,2
nt alj
a ne in (J
int al :{x lo, 20, 30, 10,$0};
2
JF size is
{3133
a7i
[towJlcolumnJs
x2 1
0:1
alojlo
a (oJ[1]
e
2
[1][e1 3
a [31[11
, WAP to
displa am
eterc 5integes 1o, 20, 30, 0,SO to aô muti oma
classA
petbcc stad
voi ma'n(¥ al)
1t alJ: { 10, 20, 30, uo, 503
int i
[Link] print (n" he aas elements Cac:" );
on Ci:o; i<5 itt)
[Link]. printtnCal:])
Hitauou
SOrite a progron
to ente Ginteq2 10, 0 30, 40 S0
Go to a 2 a 3 displehen
closs A
.23
public static votd ma'n CString ocgC) 3x 2
int
a jJ- {{10,2o, 303, {qo,So,Go} 3
se.0et paintlo
C"lhe. arnae elemn nts a:D;
fonCi o; i< 2; itt).
jo;j3;
Se
fon jrt)
[Link]
tn ( oli]lj]) ,
3
wAP to enter itegeu
to D aure 4isply the
cless A
public static
icvoid main St] aaj'
int clJ:ne int s) ;
int
[Link] "to*u
fonCi 0: iK5 i4 A)
aCiJ [Link]
[Link] tn
ho. arna elomets ane"
fon Ci=o ; i<S s it1)
S [Link]
lo (alil);
WAP to entea
GinteaCs D ot 3 disple
hen
tmpor [Link];
class A
[Link] paint (a 3;
;
pub S1 ati void man (titio gs 1)
intO,is
Scannen R:new Scenner Systcm. in) s
S
System. out prinn tnte
S20 of
asm
Knextlotl
int alJ:dew in
[Link]:prürtnC° Enten"*n+
; inteqes to 1D ata"
,
foaCio ic'ti+*)
alij- [Link]);
[Link] lo (ati1) ;
public
static void manlOp ogs(J)
in
DE K neztlnt C)s
int alJ netw int (n]
tn ("Eome elemet
[Link]
dal i o in it t)
[Link]
(Suy of all h aaney elememts: "
ikns it4
S St a[ij
3
[Link]:paiotln
(s);
8 WAP to apiea disploy. mfaraa
impott ava uts(.*;
A
;
cless
publie
Public
static void main CStina ogsU)
cljt]-ne
:
int (3J(3)
int
nt bI) new int (33(33
intcC] ne in [33(3J:
K new [Link])
Scanne
[Link] Entr elements to 1st mctwr
feLCj=o i<3itt
faCi o i3 itt)
fn Cj-o js3;j*
bCi013 K nexeIot();
)
3
FonCio ik3: it t)
fon j oj js3 j+
3
[Link]
("he tResltent mattx is D;
fonCizo i<3 itt)
[Link] CO3
3
Wroppert Class
to Can vént
Wrapper class tovide the mechanism
i9to
he Dimiie dattype into
abject & objeet
into puimi
a
tive
ONappea
datalype
classes tused to neat one e. into
Qnothe type
float Cloct
Lon
shont Shont
dotuble Doble.
chan Chaae
by
booleco Boolecn
Autoboxinq
he
its
autoboin
automatic
Cenee sponding
e
cenvension
PpeA clos
o paimitive
Cobjeca) is
datetpe
kno
into
as
int to Tnege
fleat to
(Stn
o
public
public s atic voi main
ost))
int a: ,
b:
1n1Caen a
[Link] (a t"
nboaiog9
he atttomatic ConveSion of wpperi clcss
tpe.(objece)
into ifs Conaespond n pamitive. yP skocon as
unotin
int
Float Slect
class
ptublic
osegas o:
siatt vo
0
(main
Stinn osl)
int b: a
[Link] (a+""b):
Packa
Package
ts a colle ctio
oi classes a inteataces
Poekeg whee
intcafaces
and Co
A package
als as a Contane classes
be toed
as uk +a
he
'he package
Can be broad cassified
patkage
pock
pockog.
a userde4neeto
bslt in etess pedetined elas
() Paedetined
Built-in package
Java
-
Notepad.4
etáss sia1
public voud
mcun (Srdng aqsl j)
Red :e Red ),
nree ne ntern),
Bluc b: new Btue ( )
displO,
[Link]
b.dsp30O
Comncnd ptmpt
Colon javac [Link]
Colon javct G1Len avc
Colon jovac Gue idv
O
Coloa iovot .jaa
y7Javac A java
*Y2 >
java A
rEDatera!TREHEnODr
,
Hpe conveRs ion Ype castin
) wideni
Convatinq
Castinj
a lotwen
CAutomaticay)
datajPe 1 hyoner datetpe
a
t
is known widenig ccsn
ccs
is a also knon ainptG1 convetsion o
einP.
CG stina
down.
- t is done anualy Pt
tnt 10
float:
NasutOWing casn
double {leat - lons int chca - shott bytt
Slot 1010.24
int
int) * s
Eaception Flandlin9
a thime anamay Cetto)
u to
zceptwn is u
set shous, abnoamal
behavia
whichhe system
instte
due ecution of illegal
Exception OCCC
tins duai
Cn zme
the
is abortc abno
khon cxccption occ tits PrOgRomn
RAtts he operciina skn
Umal and the Contiol
pes of
zceptions
Exception
ae r0ad cotCedzo
into tpes :
checked Excepti
Unchcehed
Checkeod Except0s
hese ase he exceptions which ae checked
the Compile an the progacm wil not exewute
un less hese excepions ace handted
run ime the
*AN exceptions except except i0ns
checke exceptons
Object
hrtowable
Exception
StakOveuflowlnno -IOException
SQLException
FVitualMachinefrroL
Lo
LOut 0fMemozy faton ClassNotfoundEzceptzo
Runtimefzception
FAcihmetic Exception
-NellPointerExceptio
FDumbefotmatExcaption
IndexOut 0fBound sExcepti
ALuaSMUns
the Exceptions
Handling9
he fon handling
Java ptovides following *eytwords handing
the exceptions
t
Catch
.thrtow
thows
finall
1t
he codes which ae Lkel to
genexate the exceptio,
kpt within the block
tre excepthn.
his block is useo to detect the
is CeateA,
Caich
his block is sed to handle Ahe exceptho 4hros
Ane 1 block
Tecved.
block, here mees be
be a
fok a t catch biock
For
Catch
a
block
sugle 1 block Ahede can a
be ao1
nunben of
3hdw
thow kejcoond is tused to htod Gn exception object
ftom a ty biock to cetch block o One caich
block to anotheer Cach block
ROthoin exception
4. throws
handle the eeeption
eKeeption
used to
thtows' keyuond is
5fioalky
whehery da
do
alu is exececteo wheher
inally block
is handled OR ot
exceptio9
t contains all the nece ssC $iatcmeots ho1 nec
Ahot neo to
be
be panie rcqandCess o he ex teption occcaly
btock to
btock handle exception eaich block to handle
excepthon
eqrcod.
3. We ate alloued to how 3. We
o one exceptioDn
can
Can be throw
kessond tha
he
. thtotw
method
is used wihin the L theus
nethed.
nt [Link] (argsLo])
int y Iotcqc. pazselnt Cangs l1 1D;
int Z /
[Link] in
"
Result: "+ z);
Class A
int
[Link](at1slo3)
int
Tolegei .parse Int (angsl:1);
[Link] tn C "Result+z)
catch Ardthmeticfxception k)
z2
catch (4rcIndezOtHBoundxCeption
"D;}
33 [Link] {n Paovide
prepe aginents.
v A Jo 2 Result:5
10 inte
Ploiele
10 20 30 Paride. pa pe Anjimants
class A
public
static void disp(int *,
int
j
intint z-73'
[Link]'ntln"Resut
"+2):
catch CArthmeticException K)
Sys [Link] pin4 tn "Deno mnato r cco'be 0"J;
hrow K
3
publie
S1ati voicd
man(SJ ay1)
isp (5o,10);
disp 50, o)
catth CArithmeticFxception a)
tocnd.J 3
,
[Link] o("Ixceptien
statio void
dispCint int )thtnus Atiihmeiic xop.
ptblie
th0n, Munbea totumatfrcoptio
tnt 2 /
Hste)otet-printloC
3
Result: "+7)
i41
dispC do, 5),
dispC10,o)
.
[Link] ln "finalby blockis exeutef."J;
thro)
class A
f Cac18)
thow new Acthmetctxe ption
"Not eligi
ble foa vote..");
3
else
Multiple heeadin=
Thea
AA +hriad is a ightueight sub proccss the Smeles
untt of procesi0.
r is a
singie
sequentiak flo cs occnthto within a
program within
A thead is an independent path of execeution
uiple threadin1
Multiple ofas to a po cess of
mukiple
hoding execuxtinn
thLads simult anests
C"Threood: Run"):
[Link]
closs
T3 Thaeao
closs exttnds
void nt)
)
puble
cless T
pubtt
atie void nasnSiny opl
T1 K1 new T1 (
TRK2:nw TRO;
T3 K3 n0 T3O;
KI.St6tC);
K 3taN I;
K3-Stat C)
II IILSUnuun moarpwrrre
Notes_
avc PtOTem ha is
is at onst
lerst ong hraa know
fn
A child chss Con be UetNS Asin
os 'ma9 thieod
elass.
Thea
tay to
alwegs
Ahe mat 4haead.
The p ORa
executio2
thceo sends
to the child
chrld heea4
4heas
eman sEgnals
ead.
orden to he child thread
The main 1hreool ust 8'ves
hrcad, the
haead,
uwina the esponseol
ch:ld tha
iihote4 uahna HS to own job
CAmes back
man 1hceod
methods of Threaf clas.
StantC) &RonC)
headPuo
hread class mahods anc constants to
provides
set the thteads.
I4 itOides
paiorsiof
setPaiorc+ C) method to seRA h
to
por
and method know tha
ofa thKead gelrionity)
of a thaead.
pion
class Contains 4he tollouing constaots to se
Thtead
ahe. thceads
he prioni of
C valu 10)
MAX PRIORITY
MIV-PRI oRIT
Y value = 1
NORMPRIORITY value
S)
Ezecutio o multiple hauads -tn with_priorit
[Link]
C Thatod3 Runnio D
elass T
pubic static void ma'n (Srn agst1)
T K1 =new T1C
T2 K2 new TRO;
T3 K3 e new T3C;
[Link] huead.M X_PRIORITY)
[Link]);
;
[Link](K32eiionttt1)s
[Link] C);
KR statC
K3. StatC 03
[Link] "Pnsentiy
os meaf1" t KigetPriot
Sen [Link] C° Peonin of ad K2ge4 Paionity);
class
pubtic
A implemets
Void
[Link]
tunt
prúnt
)
Runoable
A
pubc angs1)
K1 new AC;
Thad K2-ne h oo C K1)
[Link] );
Stepsi
1
Crec
CceateC
able
a
co
cla ss
intenta ce
objeci ofa
implumentin
class s ha qunnabl intefau
hich has the
. had
Sovoke
class
O
eass
objece
al
Constaucdon
CY CLE OF ATHREAD
LIFE
NFUBORN
stop
stact
Runnabu
unt
(Runing )
i2ldt)
(Runncble Stopt
Dead
Suspendi)
skopt
Casunc
notidyt
C
/Stbpl
)
wait C)
Suspendad
tt Runnable state
when aa-ha ead is in tnna ble State
slate, *
4 has
except
he poce sso
stal hae thneod
has poceison (CPU) aby
it? Suspendo.d
whcn a heead
statc
is 4cmporo spended
due o
4hcad goes to
he 4hcead
iputout pud evn otintepis
Suspended
Aecn
AHe
siatc.
Dea
iv staHc
Completl eetutrod.
lass T1 extends Thre ad
psblic
void uun)
7:3!11fl
closs T2 extends hKead
void tunt
public
3
fonC1nt jao; j< j+t)
[Link]
C"Thntad execution ":
Cj5)
Siop ;
chass T3 ezttnds Thead
pubU void en)
dass T
[Link]
(
C)
)
ieldc
-T yieldC) method Stops
he ce t executn1. threRad
Psam
the
her waitin hccad of
a chonw
ves
StopC)
the stopt) s use terminete eexe cution
mathod
me4had
sleepC):
is used paus
the exerution f.
Asleept) metho
the thee a speeied
in
setnd
joinC)
joint) method allows One he od to wat unti
anothe
Applet
a of
Applet is special pe Pejtam that is
embede
in he wep p to
nami COntcnt
Side.
Applea an based
application.
Steps to cate a appiet
1.1port [Link]
package
a import ava. awt
.
3. Ckeatt
Prcovide
Shapes,
a class
thepaint
b inhenstinj
method
Atom
in
Apples
Applea
ondoA to dea
cla
less.
deaw
s
graphical usen intentace
et. in the C2i) ampenents
appl
5 Create an
htmfila ane proid
G. Exe cut
Exeeutt Ahe provide he
Ahe applet
applet 4
browseA
applet using
appletviewer. ea a
Implementation
java, applet.
** ;
Apple+_
Save =A-java
htm ile:
html
.
body
code : "A class" width 300 heht=30o
Lapples
/applett>
L/boda
htmt
Save this htm ie CLet htme) in the same toldea
xhere apple
is Saved.
Compil
javac [Link]
Run
appLetviewen
htm
Hello Worl
Applet Liecycle
Born
StortC .
Statt
Tdle
(Runnt
Stop)
desttoy )
paintC) Dead
slate
Runnia
3. Tdle State
De ad stak
Stat
Runoio
Apples ntCs into he unning statc when he sscm
calls taatC) meahod of
Apple class
3 Tdle State
.
he
contaning
Dead State
applet
is
tha
Said
CLatly
to be
be doa
cunni
unning
when
applet
PPlet
1S ROMoveP
SmmemoRy.
his ote ateiomaticaly celling invokinq e
destre) method
.
his
This
public void_ initC)
method is used
desto
to initialze an applet
public vo dstact):
his me-thoo is used to Stat he exe cction of ao
applet
s
Ptram beai
the exe tion of an
is
applet
method ts retacsh
automatically called he
button is cltcked
lo apple Lfe ycle,
he initt
is calle only
start()is many
cales. times
wherea the
is
mize
method
button.
ts al caled when we chick maxi
S. public
mehos
is cicke
voiddestto)
is
is
applet
memo
a
also called on onc oHhin he e yeef
applet
mpot [Link].*
impont [Link]. *5
pubLe cless A extods Applet
[Link] C"Tnitializim")
pubte void tart()
C" Stated");
[Link]
C Paintin1);
U
Systen. [Link]
30, 30)
.dnawSnioC"My Applet,
[Link]. ptinten
C Stoppina'):
3
void deshtey
pubtic
Sdve A-jeve
htm ht
html>
bod
applee Code
A. cless"with 300 heaht:3o0
applat
/body
htmi
Scve [Link] (s0)
Cmp:le jae Ajava
Kan appletviewen .htm
Graphics class
raphics cless is [Link] dra aeometrical Shapes
hapes
in the applet
class al
ane
Some o the metheds of. Gnaphics
daawStint)
drcaw Rect C
drawRpundReetc)
daawLneC)
daawOval
oltaw Polgon)
of he aectane 20
.drawRe ct(10,
1o, 2o, 30) 3
Cnfnue
Iis 0 Poto9minIn4edoce En
application
Components in JvA.
wi ndow
Tt c cao allow he
Su ch
to Compenon-ts
be uses
as button Label. checkbo et
Object
Component
Containes
Tezhea Tee Fiel
Oindew Panel
Applee
Frrame Diale
Layout
U Mana1en
layo huw
.
manage spec:dies Ccmpnents
1 Fleo
lcgot
2. Bordon eyou
3
. Chnsd
Gidbaq
L
oo
daycu
S Cat
import
import [Link].*
publicclass A extends pplet
public void ini+ )
Setlayotut Cne flowlqyoat()):
Font. BoLD, 32)):
Setfont new FontSansSerif,
Beetton 61 0ew Button "OK');
)
mpot jayc awt ¥
impott jaC appltt, *
pubic elass A exttnds Applet
vo d nit
public
"
C "East", b1)5
addC" West ",b2)
add Nocth", b3Os
add C"South ",b1
add "Centen", t1);
Abont
Canu OKI
Rettieve
ThcaoSyochrenisetion
head Synchrnis ation is the c cpab:t to Conttolthe
Snchrtonise. mathod
Snchrtunised 5lock
Statte Seynchrtar
Stni
Stinq S new Sti1)
Strina
t new StdngC"helto ') ;
Strin
Khells"
j a', 'b,'«,'a'}
,a
chan
S1 new Sirg(d;
rng
Srin
chan {'a'. 'b', 'c', 'd'2
b
ofror 32: ew Stnin*,1,3);
t new St "); Str
Stre K hel
Stn
Strin
C"Hella
o 231
[Link]);
[Link]('L') ;
tieder [Link] Tode rOf C.0');
- 3
-) Hewwo
[Link] (t','w');