[Go to site: main page, start]

0% found this document useful (0 votes)
9 views86 pages

Introduction to Java Programming Basics

Java is a general-purpose, high-level, object-oriented programming language developed by James Gosling at Sun Microsystems and released in 1995. It supports multiple programming approaches, is platform-independent, and is commonly used for developing internet-based applications. The document also discusses Java's features, installation, and basic programming concepts, including data types, object-oriented programming principles, and examples of Java code.
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)
9 views86 pages

Introduction to Java Programming Basics

Java is a general-purpose, high-level, object-oriented programming language developed by James Gosling at Sun Microsystems and released in 1995. It supports multiple programming approaches, is platform-independent, and is commonly used for developing internet-based applications. The document also discusses Java's features, installation, and basic programming concepts, including data types, object-oriented programming principles, and examples of Java code.
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

OBJ ECT -ORLENIE D ROCIKAMMENG

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

o Sun Mictosysicm 3vA platform

1n 1qq1, Suo MCosystems developed


a project amed as
Gaeen Project in which one of tuware was dev eloped, om
ed as oak 8 thts oak' software in 1915. as Tenamed

as nvA
Java has 3 editions

IAVA

12ME
Java to Java to Java to
Standaad edition
fnterprise Edition Miuuo Edition

(CORE. 3 AVA) ADVAuCD 3AVn)

ypes ot proaramming pproach

.
1. Monolithic Paoqtomming Appxoach

3.
Procedunal
Sttuctuncd
BASTC
FORTRAD,
PASCAL, C
COGoL

4. Objet Oruentcd JAVA, C++

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)

9 Java suppouts mlti-threading.


vi)It is used to eneate
dynomicweb pages.
facilities to eleetonic
vii) Java pLovides prtogtam Consu
Such as pantop miuro-oe
mobtle, laptop. palmtop
mabl devius
machime ett
ashing
#wap to display Hello Wortld in
Java
In oicpad

(
class Fitst

public
Static void main String angs 1) of
Object
Prin StmeOn

[Link]. println
C" Hello World "); (outm
memben of

(in his ine 's' aftc 3is optional)

Al he Java progtcms
must be 60ved
b class namn

Save he abov prtoqram aS first ava


wiih a lettea 3S pe
Class name shou ld begin Capital
convênti0
namin
In

C:
C
>
Command Ptomp+_

>cd..
cd..
C >cd\ Command
tgmo
tih
ntetión

C:>cd 31
c131 javac [Link]
Compslatio)

c\31java finst Run/Exe teete

to change
te teeel din, use C: d:

Output He llo
onld

Tostallation oJava sof twar (Jdk)


1 Jdk icon

2. Cick on ext OR Ok ol Aceept or Submit as per 1he


Cequicement

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

How to kno path setting_is_corect oK not

whethe the Tdk sof tware coKn installed ou


lo check is ctly

not, we've to pettotm he folloin a Steps

1. Command ptompt
Entea
3. 8pe javac 4 press
the soltwar installed successttulla, a set of commords

uwil be displajed othewise itwi show the eioL Messap.

)
wap to enteR int¢gexs 10 4RO and dispto the' Sum
class Scum

public
Static void main(Stung ogs

int a 10, b:20 ;


int C atb
"+c);
[Link]("Sum:

To save » Sum. java

To compile javac [Link]


lo ru0 java Sum

Oap for the addition od an inttgens usia


d
a. Command ne azgument
b b. scannet class
class
BeuffeaReader

a class Add

statie void main(Stning azgs[1)


pubtic

int a, b, c
a [Link] (angslo1);
b-Integen-patse Int(angsl11);
C atb
he sum is"+c);
[Link] print ln
save [Link]

Cempile javac [Link]

execute java Add 10 30

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);

Save Add java

Compilejarac [Link]
Run java Add

7 impoe [Link].*
class Add

tatic void mainSting argsl)throos


pubie TOException

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]

Run iava Add


Command Line Angumentatio Scaone
(args[ol) [Link]()
Integen: [Link] Int
Float: [Link] loat (angsfo) [Link] U
[Link])
Douhle: [Link] Double(aqsfol)
[o) [Link]) fon single line
Stning: angs stin
[Link])+foL multitine
String
BufeacdReade
Jotesea Jntegen pa selnt [Link] ))
float [Link] [Link] ())
Deuble [Link]
Double ([Link] ())
Su S+ing-paLse
[Link]( )

to Read a chozacle in Jovc


Hoco Displa

import [Link].x
class A

pubtic static vod mn(Staing al])

Sconne K neu» [Link]);

[Link] tea a cheracte");

chaa.m= [Link]).chaaAt (6) ;


tnCtnterd chaqctHCA is: "'+m);
[Link]

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

Cha Toteaen floatn

byt shot nt loat double


long

int a:1o, b:20 ;


(Sum:"+a
( Heilo=
+': '+b) 10:2o
[Link]
Hell "ta 4b) He llo 1020
[Link]
[Link]+ "Helo") 30Helto

[Link] panttn
C4 "Hello"+ a) ; telte 10 naen
30 Helo
ysten, [Link] tb+ "lell .")>

Systen, [Link] "Hello (a4b) Hello30

Rules to witing avaProqro


1 Java is case sensitive.

Class name should begin wth captal lattc.

3 It's not a rrule, but a format).

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)

functionmame conststs o mutiple words, hco excapt


he firrst otd, the fins+lettc of
remoning shauld
ords
be capital. camelCase)
6The above teles ate foloued Javo
Bevelopment Ki
C3DKS
oa Hs ptedefined elasses 4 funetions.

So it is be to tollo
he mentioned ules while CAAatim.

use dedined classer 4 methods .

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

o module3 as pe he requ me ntr


to makjng Copies
of oOP
Concepts/FeatcaresElements
class
object
meshod
abstta ction

foca psulation
Inheitane

'
clas
Polymorphism
Dynamic
Delegtio
Messag
Btnding

passtn

A class is he colectton of similan objects having

Commo behavi0uA 4 prcopenties


Trut Cclas)

mangp Onsny PPke okje ts)


an usedef'ined whch is he collectia
A class is datatype collection
of
of data methods (functions)
dissmitaa types

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.

So baak ), biteC), ualkC), nunt) et ase he methods o*

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

The closs tskno as Base class/ Pancnt ele ss


existing
and
eat¢d clcs s known
hedëtived
th
as Detied
Super clcss,

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

Hybid xifmutiple. meehanijmis used

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

t'S koocw) aas multiple inhetancemachanism

C. Multilevel

when he dasses ae deived ox CKcote fae anothc

known as multitovel in houtanu


detved elass hen it is

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

behaves d:feaent in dHeunt sitiation


Same ent

C 52 7 Additio

"Hello" + h0oxld t(e Ho koad Concetcnatien

pe Palymo aphiEanlBndtime
Static Polymorphim Compile.
Dynomtc Polrmazphism
time.
Rn
poljmoxphismLate Binding

a-Compile ime Palmorphism


is achieved dutig complc time,
when poluamorphtsm
time
then it is ko as comptc pomorphism.
ovenload
e. meshod ovetloadn/funetion

[Link] time Polymonphism


Whon he polmozphsm is achieved dui7 tu time 0, exe
time, then it is known as R tme polymphis.
Cution

ej. mehod ovenid


Vil

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

am that ts meaningttul to he Compileu.

TyPES
Tdentitiens Opetatots Constants String Special&
Keywords chosack

Keywords
Keqwod are he rsetved ords chich are use to

pextormGome specitic task


kequords az ho basi building block o progro

Statement
Al the keywords must be writ Lowercase letteu

e- Java Keyonds (S3) or jdk 1.


abstratt* byt han ontinu ohoublo

boolean Cas class def ault else

break cath Const


extends
false
'toteafae stCictfp
final Super
native Switch
fLeet irdeperdent new 3synchce nize
mplemoots nul his
finaly
thtbw
Soat impou packe
PRive throos

goto
t
instanceoof pRotcetc
public
Retca
tru
40nsient

whl enum 5.0) Shont


Static voletl
Identifieu
Tdentities the Se delioed ames which rater

to the name of a vaniable, anray, tuoctions e


nsist of tcttcas CA-2 and a-7),
dentifieas aLe
underscone sjmbot (-) 3 dollan smbol)
digits Co-a),
wth a a Lettc o underscore sm bol ot dolla smbl
as tist choracte

Identitiets must not stai with digit


Whitc Spate must not be there in identiie

Keyoords co not be used aidentifiez


1 Ro
e- 1ax RoL
ro-no Roll. Mo x
Roll No-V
Rolltx

Operatorg

An operao iS a smbol which operates on operands

OperatoTu ae used 1o petioR cota athematica


a Prcoga
g Logical operations

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

meti opeia ion it's koown as anth etic.

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

Rolational operatos at ustd to


compa betoean

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

Pr DeeARmonE Post- DeeaO MROL


Finst demease he valu )Fis4 ptimassign tha
0 he
)
vaaiable by.1 value.

)hen print assiqn


he Thon doccease the valu
value.
a -5
int
e
int a5
Pa int
Q-
5

int b-a int


[Link]
Exp1 ? Exp2 Exp 3

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-

Othetwise Eap 3 will be evaluate & ids result willbe.

the o/P o conditiona ozpreSsion

[Link]. Opecatoa

Bit twise opetatoOs ace sed to peatorm 4he opena

tion a bit e vel .

OpeiatOA Meann-
Bitwise AND
OR
Ey ampl
int

int
c:axb; irtb7
b:7
alb; d-> 7
t int aS5

EXOR inte aAb


Compliment intf na,
Lest shifi with z0ro fi

7
int

Right shift with

Right shft with zeno fi int h Q>>>2S h


3. Spectal
Operators
Dot C) opeiaton
8 iostancoo} opeAAtO
nstanceof oposeton
This opeiatO 1S useo t atenin who the en 6je c
to a paticulo not
belnas

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.

.5ina opeLate wheo he ope tcton opecat¤s

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),

[Link] .printlo( lello)

.
3

i-else statcments
tis a [Link] contro. stateme ot
Suntaa: class A
iSCcondlition)
pubic static void main

Statement ing ags[j*

else
statement ;
3
eg clas A

pubie Statit oid maoString atgst 1)

int a:[Link] Int (axgsl));


if (aoo)

,[Link] to (Hello);
3

else

C" World
Systtm. [Link]ý

. Laddes else-it statement


lt is a multiway contto stattment
f(condition)

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

[Link] l "Gea+ numbe ="+a)

else if7z &8

3
S [Link]("Gaeatest numben"+ 1;
else

[Link] ln( Greatcs4 numbe="+z);

iv. Nested if (if -else) statements

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

[Link] o Wor ld");

- Find a o. Gmo1 df tt s
Nested f f.
class A

publc statie OId mainning argsl1):

tt
int Z

[Link] ptintly CAt "is grcates ");

else if Cz>y)
[Link] nzt 'is grc
a*st
else

[Link] (+ "is groates ");

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:

Cas valuun : System [Link]("Red');


break;
Stattment
buak
tase 2
defanlt Statenent; [Link] paintln(netn);
broak
3 ase 3
[Link] printly C"Bue'

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.

Cii) Ddo while loop


Sgotax:
do
Sn do-whilc loop. its
conient
wilt
wilt be ozecuted onca intiaj
{
Statcment s
LL and then the condition
inciement deciement, wèll be f he
3while Cconditian) t200
checked.
s tue, then he
condi-
coten
of 1he do-whe loop will
be
be
exectcd cuntil the condition is

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

public static void


main(Sting axgsl 1)
Sirt a1
.while Ca<= 53
stem. [Link] (a);
att

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

Ihe condition tt be false,


s
is

known as enhu Cont isknown as


ents C6nh
tol
loop
Hea, tonditio is
checked a Hels,tendhe checke f
he
is
checke
berinning f he to
lecp
a4
theend of he
Suntan
whle Cconolition do
Statement

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

display the eves e o a

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

A TV is a vittta machinhe that enables


compu
prLogrem

is speciticctio prre nd3 un time eni


bt
,
Can be exeeute
Loneot which java Code

Hexe javac he CompilCA which use to comple


[Link] le on Code.
hejava sl byte

he .class lis
Ahe
piatfoxmn
.class
independont

hle to genetote machn


inteapitet+es

Codos
he kpocon as java.
JVM Contans intepTe 4cA

SVMs available toaman hadwane 8 Soltw aa


ptattorms,ie, 1VM pictdormdependoot
is

vth
Now-a- days, JvM is embeded operatingsgstem.

JVM takes veny Small spacc

Why choracteA Cchon) tak s 2 bcs in


java

i
A 1ava uses unicode ststem o Repr chaac

Cten.
ASCII chaa-
Uniçode chata cien 4akes bytes whereas

ace tokes 1bge


Uniode sst pesents the chonaceuo mU
nten arional Language.
tuniuniCode Sstt wecan epacsent he chctactens of
chotacteu at
dffestnt chinese, panese,
lenguees tke duteh;
fand

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)

Access Specitien CAccess modien)


Tt specifies the visibit mode of class memberu
Jave
Suupponts foloing tpes aces mee [Link].
Aptvate
bpublie 1 defaut.

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

Dffeent packag No No No yes


non-subelas

Visibit* Sope wHhin the within te et classes Eveqwhcae


Same padk- Same class wthin Same
thoughout
package g
subclasses theP
Puny
from diffcent

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

axe aceessible within he same packagc o


protecte
d:feront pachages.
Scub- classes

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

he default membes having detault aceess


o thin the Same packege cn
specifiea.

ar access ble

Objectosa class

Syotax:
class
name object
nam
neu classnanc );
K new AC

#wap to disploy Hello otld using class object

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

disploy Cint 1, int


j)
void

SYstcm. ocaut printtoC"Sun: "+Gtj));

class B

Pubte Static void main (Stnin augs[1)


int Integen-pasent(orgs [o1);
int
Ingetparsent(angs[1])j
A K0ew AC;

3KdispayCxj
3

class A
int a,b,c
Votg disp1Cint i, int j)

bj
void disp3C)
C atb
votd disp3C)

[Link]" Stum- "+cO;


S
3
lass B
pubic ekasstatie
void mein(Stning aqsI)
int
[Link]
lne(oxqst-1D
nt y: [Link] Conqs[13):
A Kew AC)
K.disp1(,3)
disp(
.disp3 ;

&wap for addition o a flao4 nombeS usiA


Sconnen class.

import [Link]. *;
class AG

float a,b, c3
displafeat i, ftoatj)
void

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 );

ap to displo name, ae, tell no, nankN o1 a student

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

publicstatic void nain(Sing ogsl)


ni

a1

Sloat m1

OCaNne z: new [Link]);


Student t: neu Studen C 95
foni i i«5, itt)
pint
[Link] C"Enter name, age, matks, Roll no

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

i. Stoticvoaiable when a votiable is


declocc ith
static
'statit' keyotd, 4hen it's Krown as vaaiabie

Statit voiables ae koot as closs


vaiable s&nen-sta*
t varables aAe as instance vatiabs os.

A
knocwn

sttetic vaaiable has only 1


Cop fo the entite elass

and al he objects he class snato a.


single copy of
statie variable, whereasnon static vaAiab has sepana

.
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

it, the objec* wthiof 1h


Yaables.
CLe ate wthin ahe stati metheA.
lass is

he non-staio method aess he sttic as wefl

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] printl (a) ,


Static void d:splay)

[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

orde to accesswe nec it, object of class.


class.

When ve fast ime Java P catam,ajec


is ot CCote{.
a non Sfat
TE, we made thc ma ftnction as

neveinvoked b TVAM because


method hen Can

object CLecteA.

Static Bloch

When a btock is declaud with static. keywot ith


with
na me he it s hoon as stutu block

xe cutc Ras b

f
proqac) he
is
a Static block

ho JvM
a class Contans 3tatic Sfock ma ftncti on

tha Static btock is xeceetc faf f{loae


Plotue
mantunction
Jo JAYA we wte a ithott ma)
function

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

numbexs usn class object tonoph

;
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)

int, int, int)


oo aiguments

void dsplo int, floa))


void ORdo
dpley [Link])

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

ci Single Tohetanca C) Multilevel Tnheicitan


classA
class A

class B extends A

class B eztcnds A

cdass C extends B

(14 Hiearchial class extends C

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)

[Link] ptintinC" He llo ");


3
class B
votd disp20 )
System. [Link] "World"

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)

[Link] print&odass ");

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

AP foru impleme ntatio9 of Hierare chiainhettan ce


mechaqism Ashol)
closs

void showlC) show30)


show
C sho
lo C"Cless A"); show1t,
[Link] show2J sho3

class B extns A

Yoid shou)
[Link] printfnCcass B"):

C exiends A
class

Yotd dshow 3t)


[Link] printlnC'Class ")
3
class D
pubtic static void ma'n(Strcng agl)
BZ neu
C tnew
8C)
CC):
Z.shocs1c
Z shou
shoulC);
6.show3CI3

WAP for implamentatioo of


yorid inharitanee
mechent..
Class A
oid showiC)

[Link] n("Class A"); Ashoaic)


shou2
Cshowlt,sheu u]
class B. exttnds A

void show2 ) ShouX)

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

pubbe static void


main (Aring
acgsl])
Ctz:eo C(J;
D new DC);
t.show1O;
tshuw2;
tShou3
z.sho1C)S
2shouO
Zsho C);

a plogram for the inhesitance mechan ism 'ae


Desin
below.
mentiona
BPUT

PMEC

CAvAl D5P| AECJ EM


Method Overuid inq
morehcun 1 method with Same Signafcue
is

When hen i is knocn as meth


Ovalable in a prrogram

od oveuding
to method ovetridim the protottipe o he ttnctHo
ttnctio
as we as
is eattly Same Ah ptent closs

he thld cla ss

he same ttnction Can be ctofine differcottin he


pacent class
the chld class

Method ovetii takes placa only whe


when there is

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

Constttucton doesnt have


an t
A Cint i) CArt
pe
Consttuctor S u
sec to initiain
3
Object
A Cint i
intj)

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

AK: new A);


3
Outp
He to .
b Paameterizad constricton
aCpts Some
When a consttictor
Consht (ucton
pacometezc
then t 1s knocon

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

oiable = abject. veriable;

5
cass A

AC)

3
A Cint i)

t
void
ACA t

displa

stem out paintlnC;


3

:
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

wren more hon 1 CosmuctoR is. avaiabt vith in a'

of it is callod Constructoq averdoading.


class ptogtam

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

pbestatic vor man(itio3


A K1: new ACJ;
A KR new A C
A K3 ne A(so, Go) ;

5
50
Abstrcact Class
a claSS containS at least1 abstract mehod
when
tt is kpown as abstract class.
then

Method dclored without an definition ds kno o


absact method,
ts used to de clace he absttact
-absttact' keyword

f of ao
class. abstract elass
elass
We an't create 1he

a
object
absttaed class
class thon t
thon it is
is

a class nhouts otherwise


the absttac4 mehod
to define
required
alo become a abstraet closs

the inheritin elosss


class A
abstcact

abstraçt vord show

3
ckass

vozd
B
show )
exte nds A

[Link] ptint{»He
lle )
class C

pubte static vodd matn (Si pl)


B Knew B;
[Link]();
3

abstitact class A

void accept (int i, int


j, int k)

k
absttact void shetC);
class B eztends A

vod show)
[Link]ênCx +""+j" "t)3
3
class C

ublic shatic ot main Cring ags[1)

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

parcnt class Tmthe


It is al so
cla ss
use
to
to tho pass-the

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

Sring C"Ye low


vod dhost)

[Link])

[Link] println (Scepet.c);


3

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

Publc Sstati voi ma, CStain

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

puber static votd nainC)


B Z new BC o 20)
3

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

We Can not CILeate the object


off
intedac.
Ineface can be used to implement_ multiple inheatanu

lt cG
CGn also be used to achieve absHraction

To
To inherit he data from inteutace to a clcss, implem-

ents keyworrd is wsed

access nteda ce ntenlace


spectdier
name

final static
datatype vatiablei-value
varable2

varuablen
rcetuntype method1 Cparametta) ;
method2Cparameen)
mehodn
CparametC)

public 'otentaa Studsnt


final static int
r1;
void nome CStting n);

void dept CStting d


votd age Cint a);
name de pt 4 ge of.a
yOAP
hOAP
to

bimplamenti
displo
intetac mechanisn
Studao+

Nocpa intertaceStudent
Pubc
votd nome (Stong );
void clept (Stina dD
void ge int a);

SCve Sttedo ot. java

New no1e
pa
A mplemorts Studont
pccblrc class

vOtd name (Sting n


ln Name n);
[Link] print

void dcpt (ting d)


lo Depoatment "4d)
[Link]

vOZd aqe
Cint

[Link]
a)
(
ln Age
"t a);

void show)

l
System.o&[Link]
([otcdace cxOmple

static void main(Str 3)

"
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 ")

[Link] paornTmeaface "):

fuhlie class D

Puble statit vetd


main(Suing as3)
Kdisple11
Kdsplay?

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

int al JJ= {1,2],{3,13};


3f Size is 3x int all1:? {121, f3,1. f5,c}}
pes oara
1 1-D
C2D, 3-D, 4-D.. .)
aMulridimenstonakAa
Declaration o 1D ama
datap anianeme ( ] :neus datatypelsize] ;
OR
datatype a datatsre(sizeJs
Tnitialj zation of 1-D ama
int alj 10, 20, 30, 4o,50 3
Declosation o 2-D oe1-
datatjpee artesname (10] now derctype (coCelumn)
OR
JU;
datatype
w
oneyneme
Q
asionoma:
Toitiali zaution
int
a
o D_
Jj-1,2,
datat1pe

{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

tmpo t java. util.¥;

cless A

public static
icvoid main St] aaj'
int clJ:ne int s) ;
int

Scann er ne Scannen ([Link])

[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

publte Static oic main


(Stina ags(I)
int atJ[J:ne tnt
aJ(3);
int J
Scanner. K ne,Scanneulqstemin..
[Link] prantlC"Entea 6
integeas to he arna"
fon Ci o; i<R: itt)

fon Cjos j<3 s jt*)

[Link]. paint n ("The atc elemonts aa";


foR (ir o; KR i+t)
fon Cj 0sjs3jtt)
[Link] paintn Celi J0j 1)

To dioploy the above matuR in x3 matti torn;

[Link]"he array elonents ate : D;


toCi= 3 O is3 itt)
foa Cjo j3 jtt)

[Link] print tn Calijj + "")

[Link] paint (a 3;

OwAP 0 ente 0 intEgers


fo a 1D ar á displey c
mpotjava. tutil. *z
elass

;
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] C"he annc elements aa")


fonCiso; i4n itt)

[Link] lo (ati1) ;

WAP to ent n numbers tom to 0n armoy t


dipl
the um
imort [Link]*
class A

public
static void manlOp ogs(J)
in

Scanne Knta Scanne ystem. in)

DE K neztlnt C)s
int alJ netw int (n]
tn ("Eome elemet
[Link]
dal i o in it t)

ali KnezeTnt C):


3

[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

alilj] [Link] Tnt C);


3

prtntlaEoten 9 elenents tond mtx ")


System.o«t

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)

Son Ci-o, js3ijtt


System panln
.otet ( ctitj)+ "\t ; ",)

[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

Jo onder to make JAVA moe abject


ate
ouented pRag
prog
cusod.
closses
rammins9 angucge ACPpe
Primitive upe UMCPpen_clos
Tnt eger

float Cloct

Lon
shont Shont
dotuble Doble.
chan Chaae

by
booleco Boolecn

ADstabains int a»5


Iotegen q: 5.
ege a nC S);
TotC

Autoboxinq
he
its

autoboin
automatic

Cenee sponding
e
cenvension

PpeA clos
o paimitive

Cobjeca) is
datetpe
kno
into

as

int to Tnege
fleat to

primitive wrApper Catdobo wpq).


class A

(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
-

JavG a lage no. of pitedefined pockers


proviles
aue - util, Lanq, io, qwt(Absttece
CDme
Ssme of
of he packages
ndo Toolkit), iavex, sug net, sql, applet
CxYz>olod
Cpaakee
Dotepc: Notepad. Nokpad

package tolen; paage Colon packege Colo

class public class ieen public class


Bue
public Reol

void pubte void disp?0) Rubtic voicd disp3C)


pubtit displt)

[Link]-printla(*Gaen [Link] paiott»("3u


[Link] pinta("ked"3

Notepad.4

impott Colon.¥ ; pob impent Cclen.


impent [Link]
Re

publ cleis A impent [Link]

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

» lt is a piocess of convefina a datatype nto an otha

CGn be done acetomatica mcoua l

) 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

s done a Let omathcal

ti) Dasutowing castina manual)


Cmenua
dciatpe fo a er dataiype
Conveting
o
hghe
koor as nar casting

Tis eell als


o
calleo
as expiGt ConveTSI0n Cc Stin

down.
- t is done anualy Pt

Widening c) chat n lon1 {Loc doub e


e =
shont
bqtc

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

»(i) Unchecked Exceptions

hese ae the excaptions which are not checked duu


duig
Ccmptlation

Kun tme ex cephons 4he undhecked Cxceptions

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

lo Iava, when exceph0n ocCuts an except0) object

is CeateA,
Caich
his block is sed to handle Ahe exceptho 4hros
Ane 1 block

proidos he sol tetiono he exception object

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

When excephon ob ect is -{hrcown ne catch

to anoihea catch Ahen 1s known as


bLock bleck it

ROthoin exception
4. throws
handle the eeeption
eKeeption
used to
thtows' keyuond is

whott a 4u-catch block


than RNceptioo
Ahrows can speci4
ne ch
Oc prroviding
blocks

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

he no finaly beck foloss he 1- catch block

thtow and thrtows


#Deifeence Between
throw hrows
throw TLequreS t-catch -hcews doesn't

btock to
btock handle exception eaich block to handle
excepthon

a. Forn each anol exce- 2. More


evet than one exceptions
phon we need a sepaat can be
specitied witho
Catch block, that maans to
ty catch block
handle multiple exeption
4ha4 no. of catch biock is

eqrcod.
3. We ate alloued to how 3. We
o one exceptioDn
can

ceptans sin1 thnows


deelace
mekiple

Can be throw
kessond tha
he
. thtotw

method
is used wihin the L theus
nethed.

is used with the


method
nata
class
A
petbiestatic
vod moin(Stringt 3 asg9)

nt [Link] (argsLo])
int y Iotcqc. pazselnt Cangs l1 1D;

int Z /
[Link] in
"
Result: "+ z);

catth CArithmetic Exception K)


[Link] printlo C" Denominato must od be zIo."J

Handting multiple ezceptions

forn block we Co pi0nde. multple, catch


cstnqle
for hendlng mltipe. exceptions.
block

Class A

publc SHatid void


main (Sting ajd 1)

int
[Link](at1slo3)
int
Tolegei .parse Int (angsl:1);

[Link] tn C "Result+z)

catch Ardthmeticfxception k)

[Link] Denomineto con be o ):


3
catth(Nunbenformatfzcoption t)
"Ptoide inteqoa dota ."):
[Link](

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

1 Tenm'na ton Can't e

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

mplenentation otheows' Kegoa


class A

statio void
dispCint int )thtnus Atiihmeiic xop.
ptblie
th0n, Munbea totumatfrcoptio

tnt 2 /
Hste)otet-printloC
3

Result: "+7)

statit main (Sttin oqsl 3)


puble void

i41
dispC do, 5),
dispC10,o)

Cach CAruithmetic fxcoption a


Sy stem:[Link]" Exception teund. ") ;?
IlinIN UEaUittsaiaam 2itTiili!
yGinelly
Sinal

.
[Link] ln "finalby blockis exeutef."J;

block con be kept af the end f all abe ve


this
excmples
Cinsida Ahe ma'y) cie,

thro)
class A

Static votd dispC int a)


publie

f Cac18)
thow new Acthmetctxe ption
"Not eligi
ble foa vote..");

3
else

[Link] ("figibte foa votc "


3

publ'c static vo2 main Srtinl 1a)


AispC13);

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

To creat multiple thceads Java providecs Theao


class and Runnable intentace
PCoqacm to exe cetion of hreas
e ass A extends Thkaed

pubSc void Aunt

C"Threood: Run"):
[Link]

closs

public Static void man(Staina


At new A
tstatC);
)

Pcogran fo ezeuttio ofmalsiple hrea


class Ti e24ends Theod
publte
void run()
[Link]
(""meod1 Runnin"

dass TR extcnds Thead


pubtc void run)
htesd3 Rumio1
[Link]

T3 Thaeao
closs exttnds
void nt)

)
puble

[Link] l Thnead3 unim "

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

to exe cute echid thaecs usi


ehild gtaric) unction, T
functio autonaticall invokeshe
StatC
Afte sendim sgna o exeute the child thcead, he
will not wait or ihe exe ccetion of child tha
ntn theecd

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

class T1 eztends Thread


pubUe void runt)

Spsten. [Link]" e adi Reunnio


[Link] T exienels Thread

pubtc void tun)


("xead2 Rnnin
[Link] paiottn

class T3 etends heo.d


Runt)
pubtc void

[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);

Syslen. [Link] laPionit ef heof3: [Link])

ecution o thead using Kunnab l into

class

pubtic
A implemets
Void

[Link]
tunt
prúnt
)
Runoable

hread Runnina ";


:
B
class
Static d ma'n
CStinn

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

Ccote object of he heod elass 4 pass th


ciccted in Step3 as Co to
th
objec

. had
Sovoke

class
O
eass

objece
al
Constaucdon

the siaai() tnction u sina


usi hreed

CY CLE OF ATHREAD
LIFE

NFUBORN
stop
stact
Runnabu
unt

(Runing )
i2ldt)
(Runncble Stopt
Dead

Suspendi)
skopt
Casunc
notidyt
C
/Stbpl
)
wait C)

Suspendad

Duni the ite-time ot a thuoad, he haead enieu

into the gtates


folloing
1. ew borty State 3. Scspended Shate
Runnabla Stat 4 (Dead stat
Mew-bot state
nedborn
the oebOtn at
cxeate, a isin
inthe stat
Ohen a heued is
have an
doesnt have
his thacedhe siae, the theead doesn
Jo

tt Runnable state
when aa-ha ead is in tnna ble State
slate, *
4 has

64aics i ( readj (unnabte)


ii) run unnrim ) he KOSOutes
To aeady olatc he hLcd has a

except
he poce sso
stal hae thneod
has poceison (CPU) aby

all he esoun ces:

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.

the tondi tion


o supend ion S
hadae
he
COadyta-le.
o ts nof romoved ha
onditio Spensto
he ead oes
o daad sfate

Dea
iv staHc

Gcnexall1 a had is deodsiatt, who it is

Completl eetutrod.
lass T1 extends Thre ad

psblic
void uun)

Sor Cint i O i<8 it+)

[Link] eadi exeuetina):


f Ci 4
ieldc);

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)

don C int k0; k<3; ktt)


[Link] ln "ThacodH3 exee4io
s Ck 3)
seep Crens )
Latch CExeeptien E)
[Link].
printlo Exception fand ");

dass T

public Static void


man(.Sring oq)
TL K1 =new TiC);
TR K2 Oew TO
T3 K3 new T3
[Link] C)
K Stout

[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

thcead complatcs HS eecution

Applet
a of
Applet is special pe Pejtam that is
embede

in he wep p to
nami COntcnt

Tt r eens inside Ahe boSRA and wonks at elient

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

port jav awt.


tmpor
o

java, applet.
** ;
Apple+_

class A eettnds Appltt


public

pubtic void paint (Graphics K),


[Link] SinnC"Hello kOorld", 10, Loo);:

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

Applet fe sele descabes h


how &the applet is
he
[Link], stated, ndod destood duiog dhe etie
Stopped
du
execeetion of he pplieation,

The deffeccn siages ohe a pplet fe celk


yele
ae
aA
.
.
meohoneo as tolle tos

3. Born Tnitiali sation Statc

slate
Runnia
3. Tdle State

De ad stak

1.- Bon/oitialisatioo state

entens into the


Apple Born St ate whon tt is finst
initiaized.

tis achieveobyinit() meihod of Applet,


class

Stat
Runoio
Apples ntCs into he unning statc when he sscm
calls taatC) meahod of
Apple class

3 Tdle State

An applet enteis to the idle S1ate ho tis stop


pedfrum unni1
his is achieve.d whele celina
eclin the StopC method
TinTitriutrAt
erolicit

Stoptng occu automaticalA when we leave the

.
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

he applet te cycle deals with the methods


fola
feloir
C1) pablic void ènit ()
C2 pubtc votd StactC)

(3) pait Gnephics


Stop
S)

.
his
This
public void_ initC)

method is used
desto

to initialze an applet

Applet is cAeatc ustn his method

initinit C) metho atutomaAicc.l invokes stantC) method

public vo dstact):
his me-thoo is used to Stat he exe cction of ao

applet

StatC) tS similaA. maun ) a stand-


alone
applicatio

As the matn C) is sed tobegin he execution of


ajava similal statC) s used t bea:,

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

3. public void paint (Guaphics

his method is sed to dkaw GUI Compone ts Sach

as butons abels, «c2d auca


Te is used to deau D sha pes ceetana
cinele, oyal po0 et
his method uses graphics class ayas la b la in
awt
java. packaga

pube void sto pl)

meihod is used to stop the. exeeeetion


ot an
applet
his
button

S. public
mehos
is cicke

voiddestto)
is

. atetomatice celod uhen minimz

his method s used to cinload the apple om


drom

is
applet
memo

a
also called on onc oHhin he e yeef
applet

mpot [Link].*
impont [Link]. *5
pubLe cless A extods Applet

publc Void init()

[Link] C"Tnitializim")
pubte void tart()
C" Stated");
[Link]

Pabic void paint Gnephics

C Paintin1);
U
Systen. [Link]
30, 30)
.dnawSnioC"My Applet,

pubie void Stop ()

[Link]. ptinten
C Stoppina'):
3
void deshtey
pubtic

sten. [Link] ln Dastroin)

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)

) dra8ting This is use to dras Strdn on the app


et.

i) draRe c+C his methocis used to


dtau rcectonle

On he epplet. I 1akes aguments / parametens

henst 2 paccme4CAs indicate Coondinac ofAefe


com point
top-edt
The 3rd 4 4th Angum0 n4s pect he lenqth 4 wicth

of he aectane 20

.drawRe ct(10,
1o, 2o, 30) 3
Cnfnue

AWT C Abstract indow Toolk)


t Stands fon Absirac Windo Toolkit

Iis 0 Poto9minIn4edoce En
application
Components in JvA.
wi ndow
Tt c cao allow he

P mmens devel op based opplicati

Su ch
to Compenon-ts
be uses
as button Label. checkbo et

Java a koown S Qvo, aSt


pack
which
pitoides
sed to da -he GU Com ponents o e
applet
AWT class hiercanghy

Object

Component

Butto oLabucheckbol choteeLse Text Cemponent

Containes
Tezhea Tee Fiel

Oindew Panel

Applee

Frrame Diale

Layout
U Mana1en

layo huw

.
manage spec:dies Ccmpnents

Sed in applet OR eme


t helps
hetps
us to
Contro
he sitiuning Si2e ofthe
CeCoponents in GUT.

Some of he ast commenl used


cyOut mcncs
ment ione a folocUs

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');

Button b2new But1an C"Canat ");

Butten 63 ne& Butron "Abon")D;


Butto b = nea. Butte Re+nie");
TexiAnea t1 *o Texe Area (5, s) ;
add Cb1);
addb2)
addlb3)
add b1);
add lt1)D

OK anel Abenu Reecee)

)
mpot jayc awt ¥
impott jaC appltt, *
pubic elass A exttnds Applet

vo d nit
public

Set Layout (new BotdenLayout ()3


SonsSeul, [Link], 32);
setfont Cne Font

Button b1 = nes Button "oK");


netw utton C"Canul");
n
Button b2

Button b- Button ('Refbont ")


Button b1- nea Button (C" Retrtieve);
TextArea t1 new TextAraa (ss);
add

"
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

access o multple three ds Ho


an shane soure
nc'nt use to prev ent threod intendeen e &

pceveot COnsisten y prcblcm,

Hees ot suchito nisatio


1 Mutual aclusive

Snchrtonise. mathod

Snchrtunised 5lock

Statte Seynchrtar

.Cooperation 1nten-threa.d Communicotion)

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');

[Link] (K)3 natiun bjectt on k


He lla hell
[Link] (1)
tSubstdnaC3) lo

You might also like