0 ratings0% found this document useful (0 votes) 146 views58 pagesJava Programming Unit-1 Notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
| x Inkoduction +
communi caton bevviev, usect by us |
Sa Terms of progvamm’g
| * Laxguent Ot it
uvicale bleh each olher.
| te comm
| Language is a bavview pebweon human ga Syslem "|
applrcati Lsobtunre) »
obseck- dtewléd progvammiy (avguoy®
prouduvel
Assembly programm ay
OL
prgvammcay
Language
© Lowlevel pregvammd vg lavguoge
> Longuages bwodly clastidied as |
+ Middle level progvamming (angueye |
+ Mgh — level prgvammtog lauguage, |
> Fn \owlevel programming Lauguage » fe give inskaectfons 13 |
a machine, ule use Assembly Language « DE Comprises of
Mhemowics
gd middle level programming Laugued’ fee
> Next, ble uses
is “c’.
best Knaon enamele fi this
Communi calion. “The
dd prgvameivg language -
TE comet under poiduve Diente |
Tk seg Wall Shuctaxed glepr and proceduve. te puild a |
program, Ga fimgle Trac, tf i a collation cb danctione |
ov potaduver, Mott, if uses anges bled os thew ictontetet
Scanned with CamScanner> next, Ka Slavled using high level programming language!
AR Commun AM, the bast encmple fo thes qava-
cbyek Biented progvamnaiug longuag? +
fueliave Bienlad
Te comes unde
| -® Differences bebwoen procelue Sriewled | $
| and objet Bieutad progva mming
| procecluve dienlad obyet Buienlad
Progyawon wg lavgueye proqvammiug (anguage
+ Tr matuly fous on “procatc’, | Tt mainly fours on "data",
DL users tap dew Approach |. Gt ‘user bottom-up apprach:
+ Each funtion consiceved at f+ Each class Contideved
| @ Sepavale module » a Sepovate Module , Uthat
| Claw is collection of Moltheds.
|
2 U ceerw't Support soal-time |= Gh is suilable far ott
eupplrcottons . WGpes ok applicalions.
[+e ie daffealt te debug om [> Gt te enip te dabuy ond
| applicadtin and extend any enland any application,
appliicadion +
+ Tt doewh prvide ony © ak provides seuumily
- Secunily ‘
beg fxr Jove!
+ bss seutabilily 5 + Move. 7etabilily
> Top-down approach is alto called a Slop -wise approach.
dn pont ob °C’, thes approach ferck programmer hat te eile
a code 4a main function, Ta Mat , they wtill call Sub fanchala.
<> ello cup appmath stovtr (With [ma level Systm , then th
looks: fA hegh fevel Syclem. Sy this, farsle programme Nos fe
SUIT code FA modules, then they book 4a ilagvastion ob
medules - ;
Scanned with CamScanner% ove Cops Concepl’ t-
> obyeck Means o-
lable ete.
> obged tented
te design a progvam using Classes ond obsess.
> De implifros ML Softeoave develop menk o
by providing gome feativer a Concept»
The programming
| oS am absack, is en
| bauguege«
> Smalllalk and qava ave Considevad os Mie Fre
dented programming languoge :
> The follasing awe the Concept BV)
obsek —Riewled proqvarming.
* objet
» class
© Abstraction
‘encapsulation
+ Inhevilauce |
«poly withphison
« obgec! ir
“5 Aa obsede
table, caw, doz and obe- j
> obgedls oxo
Feelnology »
Stand wald enbly such’ as pen, choir,
programming ig a methoddogy & povadin
ud moin tenance
longuoge Uthewe everyting is sepresentad
cum as uly object -diewted progvamming
aly obsed--
denlives @) prncgal
ica punt watd enklg Sich os pen chad
kay te understanding obset ~Bienlicd
> oops Stands fa obget Stiented progvamnming System, |
Scanned with CamScannerSin geval, a swat wAld object have stale ond bohaviov «
4B enample, a pen has stcle Ceder, companyname, modal )
awd behavior ( itwiking , dvauuing)+ &° Molav bites, dont
Tn adunve-, The object's Slate 1s represented by voruablet aud
behavior 1s maprasented by methods.
Ded" “pn object fh a Soffwave bundle A veoriables
and xtated Methods.’
Example +-@ obget + cat
Slate + clo, rmmke
Behavior: climb Wilt)
@® obget + House
slate. Cowen location, color
Bohavny ; Closefopen moin deor .
dla don, Accelevate ae
« clase s+
a class is a collection of Similar obyedt. In
jects oe the Same tind]
the
steal wild, yor oflin have many ob
Fa enomple, Your bicycle we quit one a wany bicycles fy
the wall.
Sin lev ob obget —Buenlid , We
In Soy Wak your breyele
wh obgeeli Knaon ot
obgeck ig am iwolana ch MH close
bicycles.
bette 7 A class is a bluepyie polalype, Mat
dafnes thaWaviebles and The meth
Te all obyedi ob a Same kind.
ods common
Examples © obgedt: Pyke
clase + Byket That fame
®@ objet: POY + Each dog
clay + poge and methods Uke bavierg 0, hang
chsrauhnics «
hove Some vertebles
Scanned with CamScannerAbstraction is the concept ob hiding the imleynal details
oud descabing tigi WM Simple Tevms+ Fev enample: phone call,
wle doatk Kneo the intemal procascings
Lois “Uding tntawnal deleils aud Stastny pondowably iy
Knaan ag absivactons Leb us take the enample ob a cay, ile.
Kuno That if accelevalor prosted , Spend Utill Meveate. bub
don't Knao the iwevnal procelt hav spead will be. inc weated
+ Encapsulation 2
Encapsalohon ts the Fechwigre used fe tmdoment
abs\yauton ‘1 object~Stiented progvomming +
Delt “winding code ond dala legethey wnle a Sagle
unit ib Known 2s encapsulahion”
ith de yedlecivas
por evample, capsule, tt is coveppad with defevent Meine
> A gave clas ie He example oh en copulation.
o& tapping
> Sa Sienple. blade, En cops lation is a process
code ond data ints Single unit, Leb ut take an example ob
a HR Mo company. tele Communi cole Trngh He ade directly
Oi ce twlavtace heve-
pithy the dapayimenks. HR i aking of public ¢
° Inheritance t-
The process by which one class acqusves Me properties
and -fundinelitver of another class is Knacn inhevi lance «
dete “When one obyedk acqunet all (he properties aud
behovtors c& anolher Cpavert) obgek ic Rnaon a4
Whew tance".
4 Th prided Code suwabilllG, Ce is used fe achieve
|___aeanfime _palymtiphicm
Scanned with CamScannerFa cramp, A cheld thheviti the properties ob ih paveul-
ramet Sq object —Suertad Tencindogy , mountain bites,
racing bikes and landem biker ave all Jub clases & the
Bicyele Supev class
J aot velit
> Each Subclast howl? the propertes aud fund
ob Super claih "Bigele! Capt Spend, Codamee,bmbied 9°
+ poly maphitm t-
pdyrmdphi.smm ic (a conceyl bhave an obyede behaves
diferent) Mm diffevant stheadionss eve <7 two types
polymdphtinn - compile time and sunkme palymirphes ma -
LDL" * then one task 1s peelamusd by doffevenk wmye
Fan 05 pgp"
eg. Shape & rneckéngle
te man usalees, sh
FR enarasle, Te daw Somathing oe
Exemplt: Te Same Men
gum and bwds Hy,
age 'Move’,
Scanned with CamScanner% lhal is gave s-
ova is a prograrming language ond a plakfdim.
sousvad awcl obged-- Siena
[oqava is a high level, Yobush,
| PYOgYo mming language +
eo and ie
> deve is a high Level modem programming languag
TH wot
| va tas
| was inhoduad by “sun MicroSystems"
developed by a lzam under games Gosling",
| A Soffwou
[> plakfam is nothing bul any hardwerie
envionment tn uthich a progvan dans. Since Kove aan
ite con yuwktme environmenk be Re CIONe Ruvkime Env!
~ronmenk)
se Wheve stova is used?
According tp Sun, 3 pilion davicel Wun Tava. Theve
owe many Kype de applications Mak com be created Using
qova proqvammivy. Some. dy them ave as —follevs:
© slindslone | Application +
Te is algo Knaun as dosetoe apyicakion Gi) Llinda
based application, An oppbicakion that We need to inckall on
every racine such: as, media playey, antivirus and eke.
> AWT and swing ave used ty gave. fi cvanking THs Apply.
|e Web Application
An applicadion Mat runs On the Sewer side ond
|
| cvale dynamic poge , is cabled blob applicakOn. fg: ivetc. col
> Sevelt sp, Sadi iss ledrndlegies ave used 40 creating!
| Web aprliealtons in qova.
| + Enlevpdse Apalicakion.s
| Lam applicalion thak i cistabubed i mabive, such
| as banteng applications ofc. “ELS is used 4a thi appltachny
Scanned with CamScanner| a err
+ Mobile Apdicakion : |
An application tab “u created 42 mobiles. | |
> cserentlh andyoid and dave ME ave bed fr Creaking
Mobile appi'cations-
|
x Histary ob Jove 2-
> Teva am members (Tames Gosling, Milce Sheriden,
and patrick Naughton), initaled the qove language progek-
in sume lag] 4a digital davices such as geb-tap boxed
falevistong ete-
> The Small team dy sun engineers called as
i “Gveon Team”
\
_> pivehly, it was called “ eqreantalk” by Jomet
Gpsleng and File extension wos at".
| > alley thak, if war celled
dy strength and choo-Le
a, evonce, Germany
*ook". lbhy Oak 7
wy aso vaktonal |
dak is a Symbol
loo oe many countries like U'S-
ond ele.
| wrova” be caute
> In (94s, Oak was ~enamed of I
i
| ib was alveody a byademork
3 The lam gathevsd to choose >
ttords bleve “ dynamic", “wevolutionary u
by Cak Techudlegics *
new Name.
The Suggested ‘silk’
“galt”, “punt ete-
> According te Jamet
along With sik" since
qocling “ava was one ds the
gova was $2 Wie,
top choices
most of laam members predewred Jono.»
_s gava & om land de Indonesia Ulbove dayst
coffee wos producad Cealled gava coffee)+
> Notice Mat aya ts Jest a name +
> originally daveloped by James Gosling of sun
mierosyslame ond released in tqqs.
\
Scanned with CamScanner% fFealives dy ove (on Jove buzzwords t-
There ave many -foalberes oy soya
also knoon as Java buzzwords +
the feabinres of Java given bela
according te
> fyntey is bosed on © ™
> removed Mmomy confusing >
opevalo
foxen tod obgeds
ad cette
2-9, Explaik pointers,
> no need te Temove UMVe
prove ic aulomabic gevbage colle
> Tk eliminates Hi complexi
Gave has been made Simple.
> obgek- dienlad program vg Coors)
oftware davelopmenk
triak giwaplity
providing Some concopts 2 rubs +
M5 The bosic Comcast A OOP me?
aoe x Abshavtion
x closs En cnpslelivo
a Suber tance
» poly morphism
“hey one
o Simple. 2 portable
@ obseck-orientad @ Dynamic
« plakform inde pendewt- 1 Taley preted
+ Secured 2 High performance
¢ Robust « mulk tended
2 Avchitediave neutral » Disibuted
gun, Java longuage Is Simple
wd rarely used feabirss!
1 overloading eke |
Bon i Tove.
Keg oe Cond cat theres
+ Objet Bienleds
5 obgeck -Buewtad moons vte Sganize our Sofware
as a combination de detlevenk Wee dy obgedi Chak
coufains both dela aud behaviowy
io mefhodoloy:
and wointenane by
becouse;
|
bocowmte |
|
CamScanner| * plablam independents
\ |
3 A platddm is the bevduore & Saflware environ!
emenk in which o pryvom Yuns- |
|
|
3 There ave Luo Gout de plakefdms s Sof faradte - base
and hewdonye based: Gave provides Soffasove-brted plabfben-
5 mwa code can be van on Mubliple plab}awac
eq. Ulindass, Linux, Mac los and ete.
sqavo code is compiled by Me compiler ama
Convevtad inte byle code. This byle code is a plakfdm wde-
pendent cae -
+> Tr is achieved by IvM CTove virlel Machine),
“the philosophy dy gave “able once, Run paynihere QueRA-
. Seurveds
3 qova is Seumed becaxse Seve dost ne use enplel:
de tay volo |
porulevs andl All dove Programs runs Msi
machine Sandbox «
> gova uses the public Key encryphon System
| da prvicky seen:
| @ Robust:
> Robust Simply Meant Showy » Jave. is nobus
Programming language because
& Tove uses Skwug Memory Manogement,
x Treva ave Lock oe portend tak ovoid Security problem.
y Theve is antonadic gerrbege collectton fm Java.
exception haudling aud fe checeing
Mechanism tn qoNa-
x Theva is
> all these potalr Maket cava rrobust+
es] |
Scanned with CamScanner+ AYchilectine - Newel:
> Theve 1s no imple mentation dependent fealieves
eg, Size de primitive lYypes is fred +
> Iq 'c! programming, ink cola Wype ocempies
a bytes dy wamoy f81 32-bit avehiledione and 4 byles
avehitadbou » Buk ‘gave’, TF cee
ds memory fa bie pik
b avchitectous.
bytes ch Memory fa both 32 aud 64 bi
© portable:
gave is portable becavte We may Ory Th:
gava bytecode ts any plakfam.
is Witten in ANST CIT clear
> gava compiley
poatabilily bounrchary «
eum on ONY hood
> The gavo progyame co
-wone environment.
eo DyMamics
Sava We considered te be more dynamic than
C oor Ctt Since if te designed to adapt 4% on evolving
environment +
+5 ava programs can Cavey Otensive amanank de
syun—kme iWbdenakon lak Con be used to vewrhy aud
noidve accesset to doyets on Yun-Hene.
+ Dilevpvelad
“> gave bye code ix Wronclated on tredtly te wobivel
Mocking inshuctons avd ind Steed onywhere’ |
> gave byte cole com be iWarpeled on any systeon
tak provides a qovo vivlial Machine (avm)-
CamScanner
6MR ee eg Mae RP gee le SO ep
|
+ High pevddimance 2
Stith tee ese ob gust D_ Time compilers, Tava,
enables high peddmance-
> Tova t¢ faslev than Frodalonel wWevpreladion.
> gusl-Ty-Time LIT) compiley ravsleles gave
bale code divedtly whe nakive modstne code 4a Ved
high Spezd pereddman ce ¢ |
|
+ Multi thyeaded : |
suaol- wold |
“Sqava wos designed fo meet the
meal .To accomplish ths, Tavo- supports mult =
bosle pryrany
|
|
|
Saquive
Wrsaded pre
hak do many things simultaneously +
> A Wayead ic lke a Separate proven, Ne
gvamening, Wwhicl attans you b
eaktyy |
concurrently»
he main odvontage
Ik doesn'k occupy memory far each trvesd, 1k Shaves |
|
dh mull thweding i thal
a common Memory avea-
* Dishrbuled :
> grava is designed Fe He dists buled environment |
a te iWlernek. We can cveale distibulest applications wm |
ova + |
> We moy access files by calling the mattrods 4rom
any Machine on Te qwlawek«
> Java's wemole method iwocokion CRMT) moke_
|
disabled progvams possible +
Scanned with CamScannera
.
*
« Simple gave prmians:-
emewle a avo
Gove. applications ond appleli.
3 dn ths Cechfon, le Cor diseuss how to enews
geve ‘proven ond What ave Te auguivewens [6
progvaw)s
~> por executing amy Jove progam, You need fo
Gasall Te Idk (Save Development Ki).
Get pot de Te Adk/bin diveddy.
Creat We Javo prgvam .
compile ond run the Java Progyant:
Install Wee SDK:
Tpke ~ Tova Development kak
> Tk is o6oflware davelopmewk enveonmerk fot
> Tpk dudes
= ava compiler (gavec)
Tt Framslates te Soute
= Tava debugzing leol (Idb)
used te Men Java progvey
Corte te byle code.
ce is
= Java Runtime Envivenment CTRE)
TL provides on envionment fo TM any |
Tove. progvam ak ony plalfae.
= Tove Aychiving taal (Sev)
Tk is used te debulz tte gave Apdy
Mregh nekwodk lite Sor enliasone
> spk tc ovatleble fa ree at our ovacke + com |
unde Java spks ouch tools —> Java SE-
> Dowload — the lala apk and total ibe
> On bidet, Te Tok will be installed by defauth
Atyedksy te progvam piles \Tava\ Jdk bt x os
Scanned with CamScanner
Orwe Sk path db the TAK/bin drolay:
The path is rapived Te
yaova eke
pe sak 4a usivg Tools
uch as Savac
por Sabtng The pevmonent path ob IDK , You need
to dollao these sleps?
« Gots Mycompulr prpertics
environment Vervables >
> odvonted toh >
yews tab eh user Vvooumble —>
_> wale path oe bin
|
|
|
|
|
ale path’ in Netable Mame
| dddev’ Veoiable Value 2 OK ok DOK.
>the path of bm fader ts loow bite
bin”,
ava \ idk xxN
* ci\ program Files S
installed , opew The come
370 vedy that sdk is properly
prompt (pe “davac’ awk press ‘entey".
x Create [he deve. progvand:
| 370 Creal Tava pwgvam open ony edildy such
|
| as nolepad.
> Type The Saute code.
class Somele
£
public stadve void main C Shang orgs)
Syelenm cst: oon Ci yetlo Seve'd;
1
> Saye tes fle a Gample «gana,
ve coupile aud Tuan the cia, prOavaN
Command is wed
5 7 compile ‘gavac’
da ox: gavac Sample ave
ple dete “faonles class"ile
> To crete 'geva’ Command's
Aden gava Somple
> ue get ote * Hello gov’,
Scanned with CamScannerTn The obeve Java progyam let's Seo What Is the Meaning
cy class, public, static void, main, sting LI, Syslenascuk pallets
eo class is a Keyword is wed to daQare a clats in qava
© public Keyword i an accest modifier usbich Xepretor
ig, ik means ib is yisibl? te oll.
visib
o Stake is a Keyword, Wwe declare ony method as
stake, ik is Enmon as Stafic wethed, The core adve
cnlage de stibic method is trek Mave is no nead To
crane cbgack te invoke the stale method «
o void ic the mtotiwn type ob the wnethod, tk means TE
doasntt Melarn any value
3 main ts a mated pr Mapee sent clindap ob Ue
Prgvam, THe main method exewbd by Mi vm.
© Stinger avg ik ured ta command line arguments, |
© System souls piinthh O is used prnk staloment.
—Syslam Th Bo clots, uthich belongs te
Tavaslong package.
oul: Ue ison oukput Stream obser, winic
is a member ob Sytem class,
~prindy Ot Sk i o method Supported by
te caput Sheeom obgeck “out!
Th ts wrd fe dicplay any bead
ce output on the Screen.
gave ile is compiled oy ava Compiler
> at We time ,
conagtle: Sime we bytecode Class fle).
and converte the qava code.
> at yuntime, clacs le is comyertid inthe maditne
undsvitomdible Dusters +
Scanned with CamScannerx gave, commenti z-
not
> The comments ave gfalamenti “Thal ove
eneeatid by tke Compiler and tatenprler
> The Comments can be cused te provice inbdwehion,
emplanation awl Wide progam
Geet ch commenti ‘\n gava+
Code +
“Weve ave thyoe
1. Single Line, Comment
2. Mall! Line comment
B» Dommmenativn commen
1s Single. Line Commenks
Tag ig used bo comnnenk only one lines
syolay ¢ ;
Syne t nss ic Single Une comment
2+ Muli Ling commaouk:
stig ic used fo comment multiple lines o code.
Syuloxt /x
WS
i
mult Me
commen
*/
Comment?
whic Ue uled be
e create dowmentason APT, Jo we
Soalex: [R*
8. Document
craaks dotumenlatin APL.
ad te use javadoc
a
teol .
*/
Creal WIML Files 48 your program
> The javadoc lool
wrth explanation.
Scanned with CamScanner% Delo types in Tavot-
> Dols Kees represent The different values te be
elie th Te vowiable -
~> Tova defines eight data lyoes. Mose ave
| oO
+ byle
+ Shot Abaqer group
2 ink
» long
+ Hook cloakiy~ print grouP
= double
s chav § chavadey ver
© Boolean } Bodlean grou?
Datatype Default Size Range
wyle \ bgle cae te 12
Short cya yos te 82,36
ink 4 byte “uga yazeus fb DIGayereur
long & byle na, 225 292, 086 864,26 sok FFa--Bea|
Hoa ube [aed te as el i
double & kyle 3-4 OF te aux oF
chor a byle o te 65,526 |
Boolean \_ bik penis |
% Vorriables $-
Voriable is a Name
le can able
Theve. ave three Wypet 4 vodables |
> Local venable
> Tnslance Voviable
> sladic verviable
eee ink n= 10}
I wheve
fo Store the value 42 the poriolay progvam.
he memory locoton, in Mak
a ic Vodable name
_~ Scanned with CamScanner> Local vouabl
A Voriable dtce
is called local Variable»
it declawed inside Thr wethed
> Unslance variable?
A vavieble Which dedlavad Wside. TH class bak
instance voviable Dt nde dace
cubicde the welhod, is called
exvad as stabic.
> stedic voviables
A Vos
able thok declared 08 slekie is called
cholic varoble + Tt Cawnot be locel-
called as concent.
It aluoays have 24) Wes
Examples
class — Vexrdemo =
L
We = $0; I inslane vonable-
ctakic wk m= 10; If Stecte Variable
void mainsc> |
L |
tak neds I local vomable
q |
to
* conslawk:-
> There Oe ceyevol Values i Te ssh world vokich)
|
i
1
will never Change, these ome
eq pr(am) volves is Btyranmd a doy wt
> A conslawk in gova 1s uted te map er attign an
enack and unchanging valu To a vorioble-
5 goa doesnd devel) Support couslanli, Havever,
o. stake -fimal Variable is effeckvely a constant.
Example: public stadte dinal we MAX _MALUE =25;
|
|
Scanned with CamScannerThe scope and Lifetime eb Vovhablet t-
> Gach Vomable in modern progvamming language
hess «6 a name
ean oddvess
oa. Toe
5 Ta coalition to above properties, each vordoble
ako Wok; 6 a scope
ea Lyolime
«© Scopes
>The Scope oo Veviable if the loceHons| places | range]
tra pagvam Where The Yowoble is accessible [visible-
> We can datave vorables Wuitain
> Block ie bagun wtth an opening curly
endad by a closvy curly brace:
> one block evel to one
fables aye. visiable ts
> & scope delaymines thal vo"
also dalermines tar ligebsme
ony Hock
brace ond
yew Scope in Jove.
other port dy you™ proyram and
ch tide obsets-
o Lijetimes
> The Lifetime cb a vor
able is the location Lie place)
\uhove tke voviable enielr,
The Lfekima oufert fe tL amour dime 0 |
Vowiable enisle.
> Voriables axe created when their Scope is enlaved
and deshoyed when Mhely Scope is lef. THis meant Mat
a venable dedavad with in a mallied Mill wet hald Hiei
Volues outscde the method «
> Variable: ave created anal destayeel lahile the |
Prgram is syumni'ng. |
Scanned with CamScannerx operators =
An operator iso Syribol thak is used to
perfaim operations, These ave many Bee dr opevelows in
gava Such as
« Prathmelic opevalovs
+, #1 tt
« Relational operators
+ logical opevalars
aa, i}, ! &
a alb|azb | arb arb
+ Bikwise opevalevs | 0 |o ° } O
Bp — Bitwise AND oll o 1 !
+ giksise 8 FLYOT © ! \
‘ Vit 1 Hi O
A = Bihatse endunver
as a001000 » bE2
eu Leth shih)
2
. azeb 01109000
>> - Rigi suet. G55 b —— go000!0
. Assign mew operalors
ate, ce ee, ey Te
« conditvonal aperalor
emp] voluel ¢ value 2
> Opnyalor ecastence. & hievarchy :-
Opevolers precadence- bikestse enduiveoe] A
ea Snr ye Mitaes belwee ov |} a
pede cet enpr, —eupy ease es
se eta | [Mogicel 08 WW
additive = ime 7
seit P55 >? avgamenk [>
vyelational 4, &, =
qeu§ (==!
|
Scanned with CamScanner%& Expvassion id
ca construe made up ch variables,
yocaktons ,Wihich ave conducted
fn expression f
Operates and method in
that evolule: tea |
according to the Sytlax de the languog?,
Single value «
Exarnplecs ink Marks =25 5
ink Extmarks= FS
iW total = 9 |
|
Total = marles + Exkmavks 5
% Type. conversion, and Casking t-
+ Type conversion 2 -
TE converte the One dole joe nls another.
Th both one compakiable, then Jove compiley will perder
aubomalically «
a ink who look,
a tak inte dotle-
tha lYpe conversion
Aad enample convert ay
converting,
extn . .
ink (100) or fples 100
bong A= 7 Kk value 100
Hoa t= L; af volue (007°
bul- tom
> Type conver som is done by Java Compi lev
ember we can Blane Large dela pe ihe the chev.
+ Type cashing:
Lihen a user ean convert Whe One higher dab
Igpe inte tower dali. Kjpe tran Tht called at Me Nye
casting.
Te both ave IGpes, la muste
Incompet able.
Wpe casting.
Scanned with CamScannerExample
double d= 10-04%) ae. 3 -walua®” “pict
tong (= Clenade ee
int f= CHHLG i value 10
muster Type convevston ts lone by compiler and
Type costing ts done by user
Example :—
class, Type Conversio)
ae static Vord Main (shivgl] 2795)
f
ink x= 104;
tok y;
yeu
Syslam route pintly Ch y vols ie Yay);
r i Oey value is toro
class Type Costivg
public stalic void wain CSMvgC4 ange)
duble d=lo.o't)
long L= Clovg Jd
te t= Cenk) Le tie a
system - ouk- paintly C'd value is rd’
System souks pavdly OL vebae ia
! yclein. cubs pvintly vada 1 4 OL
t a- dd value ig 10-04
J ~ value ig to
— — tively 10
Scanned with CamScanner% Enumevalid lps?
fm enum lp
a ig a Spetial datalype Wak conlaing
foud sak ob conslantt,
Gn qava programming, you define an enum (yee
by using tee © enum’ Keyword «
Examples
public enum Doy f
Sunday, Monday , tuesday,
Friday, Saliavdoy
efledkussday , Thuvidey|
I
. %
You Sheutd use enum Weer ony teme yo neod to *opre
—bouk a dived Seb ob constant +
agra :~
public class EnumExample f -
enum Day f
sundoy, Monday, Thusiday, Klednerday , Thursday , Fvidoy
Salievday
4
public Stafic vord main (thing lJ avgt)
Day yeslérdey = Day + Thuvsdory }
Dey today = Day + Frday ;
Day mera = Day sabia
Syslog outs prnthy U'teday is" +lokoy) 5
Sysfem wont» pankla (“Tomar bill be! + Yomerrnd))
system sou partly UY yeslerclay ws" + yesterday) «
D
4 PY today ig pday
I
Tomonod Kill be Sarde
yutlerdany Wat Thuvidey
Scanned with CamScanner* condi{fonal slofements :-
Theta ave uted te cheer the condition and
ad on Condition.
eneculi he 2e0 vb Sllemenlt bos
condetonol Slafemounl
me qave Supporti fallaoing
> ay-else Statements
> éuitch Statement |
> T-elso glatement :-
| Th statewenk
Checkt boolean condition + Fre or false «
dif elemonk | Java.
is used Ie Tesh Te condition, Ue
Theva ave Various lypet
«Tp efatiment
1d -elge Statement
1 dp eke -if ladder.
= Lp -else STatemeuk +
+ dy stakamont:
sla | ip Ccondilion) site
{ i} (condition)
Node te be enoralad £
1} I code if coudetion 1s Bee
i
else
op else - tt lodder : i
Syndaxl yy (cowddton 1) Neode if cond’ icfobe
L . }
Heade + condetonl te Rue
t
elce if Ceonditon2)
t
code if conden & Fue
t :
t
Teode tall covdstiny ove false.
i
1 rere
Scanned with CamScannerExample? Demonstrali if -elte statement .
| public class hele Demo
|
| on shake void main (ShAvg I vgs)
L
ink Marks = 65
char grade
iL Crmarrs > = 70) |
|
: grode= ‘A's
#
else tf Cmaves > = 80)
‘ te
grade = 8
?
else of (waves >= 70)
Pears ‘e's
i
alee. 1 Cmarts > = 609
c tate
gvade = 'D'S
3
else if Comers >= 50)
* ode ates
&
Ase
a eet Fat
j 7 acl ow vedo.\'
gystam oak pants ("Qvede Wo +g )'
i
i _
cubpe - Jovae GP Elia DemaJove
gave TE\edemo
gvade is Cy
Scanned with CamScanner| > Switch -case staleme
The gwitch-cate Slatement ‘tecki the volue th given
and vthen ao match
Variable against o list & case values
that case
is found a block of slalemonti asotialad With
| ty ensested .
Syulax'- | siteh Cenpyesson)
i case volusl: statements »
byeak;
cate Valuer: Slabemants;
bok:
aufeull: statewnenl;
-case Stalemewk.
Examples- pemonstrala — gustteln
public class guitehDemo
{
public gtatic void main CSHvglI avgs)
ink day? 2!
Switch Cday)
ae 1: Gyclavn cous piantly CY Sunday") > bveeks
case 21 Syslo ots print C Mondey") 5 bvaatc’
cate 11 Syslem-ouk. pantly Citusidoy ') 5 break)
case Ut System-out. prinkly C* nlednesdoy")) breaks
cate © 1 Syslem-oub.priatly Ctmuvicley")) brea
cate. 61 £7 sTam outs pant pidayt)s byeak
cata 31 Syélem. outs pankly U taliedoy"); breatt;
Aafaull: system uk. print (' Duvabid choice");
2 taondey
Scanned with CamScanner¥% Loop Stolemenls 3-
she Java supporls -following looping Slaléwouls.
Those ave « ttle loop
2 do-tthile loop
+ for loo
+ ul, lop:
he qava while loop is usel ‘to Hevale a pavt ob
The program Bevevol Himes. Dr the number dy ilevetfon is
nd fined , ik is oucommendled fo Wwe chile loop:
uthile. Ccondction)
_Syalase
t
Icoda [te be eneculia
fs
* Do-while loop:
sg nde Frmed owl yom
Tb Te number dr Wevelton
tee loop at least once, aL ig Recommended
must have te enousté
te use do-while loop:
cyan
Icode to be enouicl
Jrokile Ceonditon) ;
+ fa loop : :
vokton is dared, This recommended
De te number & it
to use fi loop:
eve one
+ Sivaple fa loop
+ por-each loop
+ labeled loop
thvee joes ak 4 loop fn gave.
Scanned with CamScanner+ Simple for lwoP :
Syales far Cintializalion , condction ; ine Hew)
t
Ncode te be eneuid
$
+ focaach loop :
Syole' | for (Type var: owe)
Utode te be ences
J
« Labeled fer loop:
Syne [abebname ¢
facinthalizction » condchony tnev/deev)
L
Neode to be ene!
i
catid
Examples t~_pdhile.
public class WhleExaweple
{
pebliic static void motn (Shing ta age)
fos
int tel
while (t= 10)
t .
systena vooks pant, C07
(ety
Scanned with CamScannerExamples Doo utile
public clots Donthile. Examaple
£
public static Vord main (Ss hg (I avg’)
{
ink tet; i
dof a
System -out> pomtln (05 |
'
tte; ° |
{ plbile (6 <= 10)
4
Ppt st a]
Example: Fo
public close forexample
public stakte vord main C Stivg CF avai)
t ~
dacik (U jzzto; ++)
{ , ca
‘\ , e
syslom woul pant ach IS
i
4 lo
J
% Breok and Conkinue Slalewnenl 2-
3 The Slalementi breote aud coniuue alley Mme nbumal
conte Plas of Compound staamonkt «
> The break glale ment immediately qumps te
ck the appropwiale comprund taka menk{Loot)-
> The continua stalamenki’ immadiately gumps fo (he
next ilavakiow Cif any) of the ageropriale loop -
Te end
Lh
Scanned with CamScannerbveak 3-
Lthen a break Slatémenk
loop, the loop it ferminalid and pr
wg the \oop.
ie encruwleved side a
gram conbel Segumes
ab the next slalement -follast
_dgnlaw!- — byeale 5
Examples
public. class Brealeemo
{
public stale void main (Sting (1 avgs)
Aaicint i2t; (4 toy ttt)
if Cis=5)
L aie
break; I Fermanate loop if tf s
J
cyclemsouk. pinta (1);
j
systenn- aut. pinkln C' Loop 4g over." )5
oukpuk ens qavac Break Demo gave.
Cio Tava Breatc Demo
\
2
3
4
Loop is over.
> Sn gimple words, the break keyuatd ts used ty breake
Csfoppivg) a loop eneustion .
Scanned with CamScanner+ Continue t+
When a continue stokemeul is encountered inside
the ely ob 0 loop, emaining stalewenbi ove sipped . ond
loop procaeds with th Next ilevolion.
-Sywloxs — Conlinue ;
Examples
public class
public Stabte void main (shi ng Ly avg)
i
dacink iy testo; 4)
{
Cen 2 =70)
Conbnues [steep meee gtatement ib i HN
5
Syshain cons paakly COS
§
i
f
wubpuk! C:\> qovac Continue Demos seve
CAND devo. CowdinusDewe
1
Dypanw
> Sa Simple eahdi, The continue Keyota is used te Seep |
the parbreulay macuy sion only ma loop enoukn.
Scanned with CamScanner
|
|
|
|
|X Simple gove. Gardalone pagrame >-
t. cibonacci Sees in goo
class pibonecci 1
i |
public stake void main ( Sting avg) }
f |
| ink miso, M2=1, n2, 1, Counk 2107 |
| |
Systewseub paaklnng © "4N2)) I paning 0 avd!
Ao (hers be counk 5 44)
{ 1
Nae m4 N27 |
Syslem euks pane(" "4n3)!
We Nay |
n= "3; |
5 ote? Ol 2as 8 132134 |
|
: | |
3 ; |
| |
2. prime Number |
| closs primenum { |
| public. Stekte void main (Shing argst}) |
| _||
| t jak numett; int nun 2GAligy -porscak Lo
ink dlog= 05
Aa int (225 tenums Ut) i!
i4 Cnum-/.i == 0) |
Gysltvq. cabs panily (mum eis neta prime’): |
gabut i ig a pame Numbey
ee |
i4bg == 0) — =
3 ntly(num 4% is a paime somber’);
easton ——|—_4. Syystawn seat pinta Ce |
Scanned with CamScanner+ palindrome urbe
-— ee
class patindame
f
public stale void main (S447 ovgst 1)
£
ier, Sumac, Temp; 4
ik ne USUI ne Tlie goes Covegs6o))
Yomp =)
vihile (n> 0)
ee Nt lo,
sume (sum x10) 415
nen/io;
t
if Clawap == S40)
t Syston vouds pat WC" pabindvome number "J
4
else
t .
cystem oul» pala CU Nok poclindsn me MY
i ukpal
3 ° palindome Nuvabey
$
ty. Fadioiad -
class podeiol
§ public stakte vord main (Sting avgsC 3)
i fink if faut =)
ine nume 5) I n=
Aa ier; (ez num; (44)
Inligev pawsens Cavs L03) 5
© a eda;
j
sytem soubspintla CRAUGAeL oh enum et Atal)
3! pulpul- padlowel & 5 is 12°
Scanned with CamScanner4
Class
fem chong uw)
publ lake void main (Shing ang¢Cl)
{
int gum=o,%, lemp;
ink ne 1685 0 ne Gnlagey + pavseliak (avgs (03) ;
Yemp =;
While (n> 0)
ye W110
sums gum 4 CYIEICT);
Me M/io;
j
14 ( temp == 94m)
( system souks patty ("fem shong member ") 5
j
else
{
Syston. out>printla C! not a Aon stony Member")
fa ortel” — Avastony Number
Fo
Scanned with CamScanneroy
ik
3 pretest
dic cer ssad haw lo
Theva ave
out ch similar Roe fb valust
3 de can be achkevad by spevol fend de dala
ehrudieve Knaon at avvayt+ F
we fw acray Sa collecHda ole eimiler | dle clowendy ot
Beatle elements. We
can shove only fined eek
array
dedave vovieblos
5 THI new, We have
velue-
a single
which Can slove
wish to geve *
a pavlt catay data joe,
tee gilraktons Wheve We wight
iM a, Variable +
a data Shudiye Wheve We Slave
dr efemonls in on ONVAY™
based , first element ok The
us
> Aewoy in qova W index
is shoved ab oCzeve) index
jndek
awe
Fe
TET Ti
T EJ |
aovey eng is B
Advawkigos de_anoy t
> coda lopimiiditen : Tf yrs! ee code optimized, ble caw
wabive. % sort mee data easily.
bla com gek any data located ak any
> Random acess ¢
index pasition »
Disadvauloga dy avvay ¢
do alementi in)
> tire Liwk + wo cam slave only Pred side
Whe away . Ut cloesn'l | gra tke sine ok
rrankme. Te Slve. TEs poblem , cotledton
Hramawerk Wo used tn qove.
sco Wypot oh) acraye!
Thre one.
dimensional avvay
Single
mull, dimensinel avray
Scanned with CamScanner+ Single dimensional avray ¢
Ak is an array with only one dienension (CO inden +
dt can be Vigualized as a Sing yao of clu
peclavohion t
‘Dalle Variable (1 = new Aalalgpe [se];
pert ve fiom Tralvabia boo
or) 5 2 Fatale ston
tory datalgpe venable (1 =
dolalgpe Vawable( 12 F chock, eleweatae>- wy
Vaviable = New dalalgpe (sire)!
xt ink market] = new ine (S32
@) (ay ink wwe Lae £4s, eAe,eent
ine marks C15
marks = new Ink (51)
Example t
class Single Davray - ~
public cake void moan (sting args Ly)
i
ink marke {2 new tae (D7)! Dectavaton
martes fo) = 605 il Indhaliaekion
warks CI = S85
ink mores (=
marks 22 = 70 tor)
marks 080) 7 8° { 0,se,30,80.78.21l)
ar yi
wrowes (42> 78.
roves LS3 > BU
UI pravking vobuss in 8ey
HB Cink (20, Le tenes + longth 5 C44)
gystonn » ou. prt (rnaries C1 J
4
4
7 ads 60
st
70
20
2
af
Scanned with CamScanner+ Mall; dimensional array 2
Tk ig an avvay with two of move dimension’ bi indaies.
Gt can be Visuabinad os a mahin dy raat aud colts
dota S
tdi take a -hor- dimensional avray, Sn this coe
mohix om)
doved ‘Ww tno and column bated “inden Calco Kant Ca
Sold AR array declavaltyn (tus)
dalalype vevable (JL) = new dalatipe Lreod] Loot
Cov) (on dalalgpe variable C301 =
Dolaljpe voriable LIC) ; [hese d lence} f
Variable = new databjpe [xaos] Ceol?
BE ie mares t3L7 = new ie Ce) Ley;
con toy NE mete tata =
iWe mark! C102! Lue ert Laer Hd 5
mares = new it Cafes
cxanaplt.
class TexoDawray
5
ublic slakte void Main ( Shing avgsll)
p i “y
{
ine marke (] CL] = wee int (s} Le];
marks (6) Lal = 48!
marks LOT Cy = $25
mart Col (23 = 63),
In pediavig § Grshialiereg 2D owvey.
sie smoot (162 2
(OD, $f4e,62,68, 65) 66,319 $69,28,89, 65.64,
36}, 138,68, 66,98 95,03)
Ue S2 63 6S 66 9)
67 38 3 bs OH AG
3% 63 65 FQ V5 EL
wmarcks C2] C41 = 985
maves (27 6S] = $23
I prnbug 2-D ayyay
y te wBlace legit 14 f
Se mBustia- lengths J L
leystevys ook PIU (Manes (13.2 ah 5
cystem souk pathy 05
Scanned with CamScannera Console input and _outpat Con) contole class t+
Ta this, He leava about ova sto Console. clas. “This
clase provides convenient metfinds fo naadivg inp ond
Slanslavd ghveams Ckeybord ond dlicplay) in
under
whiting output te
ute’ conse clas comet
* jova.- io” packet
command Line Consele) progyans.
ug voeliod,
2
> the Conte clacs povicies -fllast
thase ve
spanbE() - bhi a dmaltad Shing To contele's oukpak
slfeom.
stoodlLineC) = Reads « single (ne & Faule feam contele!s
input sheam.
a pasword -tom conde.
ditabled «
cans
+ wack Password C2 ~ Reosls
Sheaamg Ulith echolag
Example”
import javaiowk 5 d/pactey®
class Conteleioem?
t
public slate void main sting ays)
Sys lea « consdled
uy viame’
Conde c=
"Vs Wf consele aakpub
co pont} C' ewer 9
Shang vame = ce eodlineQ) I conse tnpule
ce pitt CY enley yout Company Mame & ;
Lin et) 5
ghing Crowe = coveod
coprint} (" Congrati /-5 wo", Name)’
cepvintt CO yar one The Emplyee oly Company + 78") Crome);
qavec ConteleioDemo-Jev>
fe
qova Consele‘cDemo
Eley yy name }
Enler Your Compony, nome } TKRCET
Congrall madbu
Sane ave The Conployee of Compony 3 THRCET
Scanned with CamScanner
Medhu% Sconney class
“5 The Scanney class comes undey gave vil package + And
ik te used fo geting Mpuk dom seve
> System & a clase im the java lomg packed? - ts cit
hat Wvee pyedefined Vaviables + in, oul and ert:
ain -efers te clivdard Inpuk Stream (key bord)
= out Yefeys te Slandard oukpuk Skream (mower)
+ eee, Vetere te Slandavd evrov oukpuk sheeaw (oanili)
objed Avariable 16
3 Ta Scanney Class Uses Systema vin.
get tapuk trom Keyboard ( Slindard inpuk Steam)
The Seamer Class have follaving Methods
enextLinet) - db polawns Mae impuk at a shivg ,
a nextTat = Ue eel Re inpuk os an iwlejer.
srerteloakty - Te eee The input at a Flook-
snextLowgt) - De vebivat He impule at a lov.
ak guliwnt the inpok at a Short.
«next Short O
~ ak mabint The inpuk of 0 double.
eo MexkDarble Od
class ScannerDemo {
public stakre void main Hing avg 3) {
Scamney sce New Ceauney ( System «ind 5
System souks prntla Ciewldy your mamer ") >
Chang name = SC+ next Lined;
system souks pantla Cealiv yoy oge t
ie age = See MextTnt 0;
System outs pantln (" Hai” +name) }
cystem souk pada C yeu age is” page)
Fo gatos wee canbe
qovo ScawnerDemo
Eww you Mome
Modhu
enliv your og
10,
Ha, your at 6 30
Scanned with CamScannerx classes and_obieeli t-
qova is an obge “friewtad pragvammiyg languoge +
classed aud obyeti one basic buildivy blocks oop:
x Classes t-
A class 1 plaepink 0 prlslgps
all abe’
tras common poperties.
snathod , con shuuly
2 A class ingava
block , class and inlerlace + |
|
Syvlax te _daaye o class
class
i
Uvtavielles dudavedton
Maltiods declavativn
5
common f0
Vaables and waethods
ok obgecti that
cer) on clas eo STP
an contain: dala. membey.
+ a class can be dedaved 9 o¥
by the ome o ee clad that ye
os the! clase bendy - conti Tog differouk
Levelim aud Methods daclavabion-
x Obgerli s-
An obsack iso tobbypoare
wolalad Methads Anokyed- fon
able accor vowables
pundle A vewables awd
using obged, We can
hat claw 4
Sprbsx to dedlave an_obgeel~ |
olga name = new clasi-named))
clays—vame
or)
Su gener, Syntax is
Whe Bre ts nome & chy, deca a clan
., e
pe bse name F
i oa
Scanned with CamScanner> The keyword “ww? is used allocalé mowmery al
vuntime «
+ Taskince Variable? wae
pn Varable that “u cvealed intide the clas to te
the method, is Knaon os intlance vowieble + Gaslince variable doew'l-
gee memory af compile time «Tk gel mem ak vandione whe
obsel- is Crmalad« That is Why th is Rneon at milance vaviable
Examde o& cbtul: ond class :
class Shadewk
: |
ink = S12 pdaks Meeker (ols intherre vores
Stang name "Madhu" |
public shake void waain Chg ages) oneal
dell
t ay an else A Hate
a . gadeukOo; Here's
sledank oe we Sie |
i
ewe
cystem souks pinta (5154
system souk pintle CS ‘mawe);
ie age 302 TN 5 spleced vonebles
hang, boranch eNCSE's
cyysfom ouk- pivlla Cyr age i” 49925
syste souks pind Cv yar byancls 62° a branch);
3 opp: owe Sted -ser8
i Jove ghudeul:
yew Bue 1S SR!
yar nome if Medi
yar age HS
yoy brawl iy CSE
This enample, Kle have craolih 0 Skident class That have
mo. ble ove creokivg) tht obsect
Sin
jon dala members id aud na
kta aiddewk class by few, Kupuord avd pindtng: the objec.
Volua.
|
Scanned with CamScannerbe: A java method i a colledion ob slatewenki that ave
| graiped lagether to perfdm an optvalion.
> None of the melheds can po decavad ouside the Clats-
| > all melfiods have a name that slarle With a lnoer cate |
| Chavauav+ |
|
| > 4q geva, Methods ave used to,
| + Make He Code reusable.
+ Simplidy the code.
+ Tep-clnon programming.
of methods, Thase Ove |
= gave suport lee Spe
« Dasleace methods :- These ov usad to oceets /mani pulale
| che inslance vavables ant alsa, access
class vawablet-
wethelt:- “These ave used le access elas Variable:
aud urbit
| + class
uuless
bub cannot access Me tnshvee variables
They use an object 4dr thal puvpote:
Syntax fa Method peclavakion
Cmodikers] velaen ljpe wethod name (paramedir- LX)
t
Slatements (it / meted beely
I
in Me above, Synlex, ,
Facled ,
modifiers Coptional) deftones Wee SCOPE Cpublee , profects
*
afoul or privele). seed)
se -rebicen ype = Ub can be either void Gif no value 5 Ye
ipa value & galiamed>
az method-name — THe maoltiod Name mut be © valid Tave
letter);
tdentekev. (method name slavli KUT lower case
Scanned with CamScanner~
Pavameley Lisk +
elev Lisk t You can pass one of were values te
a
Methed by listing the valuet th pavan theses follno ing method vee.
* MM
Melfnd ly : tye. method Indy ctafines what Ma mother coed
Adith the efalomonl.
Examgle.t-
The -follaoing example bran atiala’t Waa te elsttnts. mnathed
aud hao te call Hk
inapork Jovan toe 5
pallic clase MaxNumber
public stabie void main (SHavg avgtt)
Contcle c= System~ conde
ce painkt Cienley forth number sa")
ine a= Sabiger porto CO wood Line)
Coprmbh "Eker Second number 0");
int b= dutager: pooteTok Ce nensdllia 002)
ink mone = Max Rancho’ Co bd)
} System souks pinkly C'Maxiwum Number pe amore)
public stale int mow punckon Cink 1, tek ne) |
is
ink won;
bow > ne)
wan= MN; ofp: tavec ox wumlbey Tava
eee jove Max umoey
man = M5 Euler forst Number
. co
retin many Cte gicawd unenbey
i cl
J Morimuwe Numbbev 16 © Se.
Scanned with CamScannerExampet A method wlith void -vetium lipe.
import gava-to.% >
Public clase Cade
{
peblic stakte void main (Haug avg)
{ |
Contole C= Gystam » Consde 3 7 |
wares tH bl 0 ts too");
Coprinkd Center yur
int works = Solr. pousetik Cevrendtines?
qvede (maves);
}
public state void guade Cink (wromes)
t
th Chmaves >= V0)
Cysteons cub parntla C Grade A")
else iA (bmaviet >= 40)
Sy slew souks prntla Co Gvade
else id (tmarks >= $0)
System ouks pinky (" Gyrade 6°)
else
Cytlem . oubs prinla U Gyaske BD");
j
t hy Sever Grade -"jeve
Bl"):
Yova Grede
Caliv Your mower tw be 0 fe (09
aL
Grade 4
wl Gh a method is dedawd uring slasle Keywerd , Gen
to wed Yo weal an objut to occase rh. ofeverce, ule
cout Sijeek- aud Then acces melhods by wing That object.
Scanned with CamScannerExanaple? The fellasins
gq ehample Sh at 7 F
obj Creadion. mt wnatiad calling wait an
imparlL java. lo.xs
class Cale
5
public static void main (Sug avgsC3)
f
Coke chy = news Calecds Mobyut coretion A clots Lele
Conde c= System. contdetr;
Copinkt(" Ewe divtk numabev")/
int x= Tuliqer passeDa Certo Line?
c-parkt" Elev gecomd number")
ink y= Salagey - pose TC evyead Linens
obj. SumOUY4)S
bjs SubC%Y);
}
Vid sum (tuk a, ink b)
Fe atam outs pitl (sum ft (atb))}
on cub Cink a, tae bd
ot + Carb}
syslom soul pantly C'seb is
Ne
javoc Cale «108
\g
javo Cale
coker Sivek numloet
2o
erkev tecond numer’
Si
bom OS
cub bt SF
Scanned with CamSc:|
% Mattiod ovevleoding :-
ws TH a class Wave mubleple welled! by fame viame bol
ditfeven’ pave mealévs, it is Knnon as Metheel overloading.
Iq gova bthenevey @ method K being called, fevsk Te
name sf the method & matched and then, Te Mumbey ond
WWpe ob avgumenti passed le that mefheds ave matched
> Method overloadivg & a daotive teal allaas a class
te have tan ov moe Melkeds having Same wae bub differve
Povamelévs «
thee ove foo differnnk emmys oh walked everlooding
+ Mathod overloading by Changi data Ijpe ob oxqumentt
+ Melkod overloading by ehauging no ot agqunenlt
Example t- an
Method overloading by Chavgiy dala Gre ah avquinent
close Colaale
‘ tk b)
void gum tek @,
‘ . /
System souk prainthy (sum 1S 24 Cath);
i
Void sum C4tlool- 0, Hoa b)
t
“eystzon vous poll (hsum ot" $ Carb))s
a etre void motw (Stang avgitl3)
vane eat enews Calebelecr,’
col. suet Ce, 035 Usam ok % tat b) fy mel
cole cum CUGh, &&4); Hi gamCllod @ , He
$m eve colenlete stove
t jovo Colwtelé
Sum in
sum it GY
tod 4 called.
abby eollad,
Scanned with CamScannerExample:
Matted overtoasing by chonging no. of ovquraoul,
class “Caleum i
{
void cum ink a, int b)
f
System cout» pantlr Cat b)s
I
Void sum (int a, iwt b, take)
{
system souk pity Carb+e);
}
public slate vod main (sting ovgs(2)
i
Calsum obj = new calsume)!
bjs Sum(ty, 10,10), I) sava) wtih 1 povaradlens
nj. Sum (20/2005 1 fare) plite 2 povernelers
i op: jovec Caksum. jova
1} ee
deve Calsavn
30
uo
x Constructor
is
at
5 conskulor
uted to dikichee the objet. ovo consteadtoy invokad
tre time oh object creation ,
> u Consuls the values ie provides data fa the
objet hak is Hthy Ue ic Kaan as Condurdsy.
to i
> condrudtey name
>
> gave conshudlors ave the
intkaliaed object.
Theva. ave bavically too males defined 48 the consteuley
muct be same as tks class name.
Constutéy must have wo enplct vation (ype.
Scanned with CamScanner
ip java ie april [pe of welhiod thal |
methods rbhich ave und |
|Thee ave hao ljpet eb Constant
+ Defoullk consruto
+ povamelanzed conthuctor
# Defoutt concludes t-
A conthudor hak Move
defaatt conseuddv » Hs iced
om objad
Exaraple 1
class Defaulkconsl>
is Known of
no pavamld
t Values fo
te pravidat default
{
Defautkconly oo constructor wnelhod
Defoull Concho
: v
system outs pantl, Default Cons jurlor wathed called”)
}
public slakic void wnain (Stang avg)
t .
Defeulk Contly dex new? DefaudlCousl 0);
| } oubpek yavec DefoullConslr- Jove
| i ove Defaullconch
| fw method called «
+ pavamelavinad cons lfult
5 ® pave melavired conshu
poromalays. (0) 6 Contactor tak have pavomalevt iy Knaon
ot pavameleri xen Conshudtsr -
> Tes isuted fo provide diferent values fe the
disud object.
Ga The cfollosing — enample,
gfedewlit class tak haya fun pavamelove.
der ya conshudloy, thak has
te have. evaatad The conchcley ad |
|
Scanned with CamScannerSr
a\itindsks Gia
(
ink ids
Stang mame;
Student (ink i, Siwy ¥) I! povomelvibel coushuclow
{
ide ty
Name =
f
votd — desplay 6) I/ Method
I
system souk pantle ( ida "“tname)?
!
public stale void main ( SMvg avgslt)
{
Ckdanls c= new Sladeuls (9:1, "Mache";
Stadenli so = new stadewls (sir, Heal):
Sh. display ory |
Sr + daspley |
i outpules> javor eladewly java
4 jova shudents
S21 Modhy
cin Haw
% Conchudloy overlooding +-
Conskudr overloodivg is a lechnique ‘w java in
which a class can have any number che Con ateutlovec
thal deter ‘in pavamelow lists.
tha Compiloy diftevertiafes these constnadors by
fang ints accounl the number oh pavamelert in the list
avd thay [ype
)
Scanned with CamScannerExanaglt,
class sum
int a,b,c) ccaslof
SumCint x, ink y) Zvteth 2 poverre
c
a:X)
bey
: tebe wtith +
Gum Cink x, ity, ind 2) reavslet
i
a=x*}
b-¥;
cees
4d
void desploy cd
! '
Sy slew souk, ponte (gum t+ (at btO);
!
public slakie void woin ( Stang
i
Sura
avge(3)
gee meus Samat lO U1"
ty pith 2
w cum (10,20/2¢) * I
Sum Sze he
Sf. disployi!
ca. digplay 02.
{
J
oubpel’s javoc Sawn. Jove
fava Sun
Gum ‘wo 2t
iy 60
Sum
J site 2 pavers
aun
Msi
:
|
|
|
pent
Scanned with CamScannerTreve ave Smo diteventss bebsoen constructors ond methels,
Those one,
Constructoy Method
% Conckudey Is used fo inthe | Method is usecl te expose
(ae voles fe an obsect. bebavioy oe om obgect.
x Conthuddy must nd have | Method must have velirn
vretiasn ype - tGoe
% Consdvuddy ts invoked tel | x Mathed is Ravarad enphatly
cidly
% consuddy ame must be | * Malked nome may or Mey
Same os’ the chur name, | nor be Same os claw nome -
% ovo Gorbage calledion 2
ecloveneed obyeeti. Goxrbage|
ad memory automat
To Jove, garbage means Unr
colledion is process ob dashed The Umut
cally
Ta other whde, Ht is a way te dechey Tre unused
obs +
se do So We were Using deers fundon wc language aud
dobtet> ™ Ct** Ral, Java it is perfdmed aulemahially .
fo gave. provided bulla, Memory Manag ments
An obged com be Unsqevented in follesing Nays
> By mulllig the se fevoree
example Employee = New Emyloyee 0 7
es Mul 5
> By assigning a vederente te anothev
ape new Employees
Example t~ Employee
tre new Employee 01;
empbyer
Qo én
Scanned with CamScanner| put void finite t)
By java, The garbage colledlov cb vm colle: only those
obsechi Thal ave
Crealad ony obsede piithek ew, Yor Can use finalize Mellie
moving obseds),
ovalad by new Keywords $0 1 you have
fo portion cleanup processing (dashoying
fivolinn ©, method !
sus Method tvoked each time bee the obseck}
motied i used te dos bry ing
it garboge cotlecton « Tis
the objects Whack awe ict colialied by” ners” Kaywrd
{geo wolfed +
The gee) wethed is ved te invoke Me gar bose
etub thes wethod
Called to porBu cleanup pro Casting
tL peed Te gaxboge.
guevanlie trot gym bt
dots net
Collation. UE only agusit ts te WM a gavboae
collection.
Exon
class — Garbage Demo
i n
syslimn cout pinky Cobyek is garbage dled")
}
public gladre ved main ( Sing argil
{
jose bagedewne gis new Gavbagedeme CY,
Gorbosp. bere gee New Garbage deme Os
gi- null, i
gee nul) wap jovoe barcbaqe DP wy Jove
Lystern © COS fove Gerhart
oby ty gavbaqe cotledod
; obedt |t gavage call ced
_
Scanned with CamScanner% Shing class 3-
Generally, Shing ie & Sequence oh chavadévs. Buk in java,
obyet’ that repwtenk a Sesuence ch chayadlers.
Stang is an
is used te creole shing objets
> The Jove loug. Sting clase
2m gova, An array eb charadeys works Some as Jeva Shiv.
Pa example!
chert) ch={'m' ‘a, ‘al thud:
Shing $= new sting (ch);
is same att
Shing s= "Madhu"
> In Jona, Shing is an okjeck if can be croalad by using joves
larg. Shing class.
Thee ave -fiso aye te wale Shing objet
x By shing Llevel +
gore Shing Glee 6 cvrated by using double qieles
& Shing $= “tdelome" >
When we crake a Shing Uli), He IvM checks Te Shing
in tke pool %
conslank pool -fivah, if the Shing abcady enisli
cedevence fo the pooled inslana is rwbivned «
Th Shing doesn’ enist fw Te pool, a Mew Shing inslance is
cusalad and plocad iw the pool
4a chample? Shing St * Welcome"
dang S2=* Weleoma's fill wet_cysale. nev intknk,
ole j= ghing obsets ave stowed fn &
¢ showy wee
“welemne”
peal memory area knaon a!
constant pools Tk ts am contlaut
toble te dome Ging bliml.
sheng conliek
note" A heap is a general term used
te Ud) omy Mewory that is allocalad dynamically
ond vaudomly. (at ig allocated by 0-6) -
Weap Mendy
Scanned with CamScannerStang sane Giug ("welcome");
Ga this case, JVM Will Cyeele a new
by uting “new” Kayword +
shay obgect ‘w
heap memory awd the litera ydeleome” visit be placed * Mae Mig
comslank pool.
Example $-
Class Sting Example
{
public ctakte void main Coang axgs tl)
t
Shing S1= wezava® + fjewestng 0 ching by Jove Sag Ulead
choy cht) PES TE Wg she
Shing ($2.2 new Shing coh); Idonerting chav avey to shiny
ghing St = Rees Shang Cenawmple J; Cranking Sang by new Kegel
systim souk. panty (81);
sy stom routs privtle (52);
gy slann « auke pinky C5
; autpul- jovar hingéxawaple Jove
fove hing exemple
jeva
hangs
example «
Ty Tova, cing obyet is Immutable That meant once a
ghivg object ts cranlad it Cannd bo alleved.
Scanned with CamScannerIn qova, Shing class proviclas a lot ds methods fe perfdm
opevatinns on shingt Such at compmyec), Comcake>, equals),
Sp\itO>, leugthe, vepla CoC? anol eke+
¥ chav ALO)
This method reberns a chav vile Tay Tee. SVE index
Mumbeyvs The inter Starr dam 0 Grov)-
Syule~ chav Ab (iat index)
> Th obit char value+
Eramle Shag Mame = mad hu" 5
Char ch= Name+ chavht (ee)
So. P (ch);
oy
oh nokia
& Loncak:
caso shang And
wis mathed is uw te combme
Combed Shing:
sywlox t~
Geamdet shang siz‘ youn MOG
gis concal (* is teamutable ');
concak (orang 2)
sie
sop C55
lps save Shing 1S rmulable
x conkains O.* ;
mis matted Searcher The Sapernee oh chavoulevs in Tit
ching Cb relat fue Uf Sequaine & thay Values ove
in ta given Sting cotherustie suaboms fobse-
syubxt— confains C chor Sean)
exomsle? hang names” Madhur Nosd ~rabtrecka” ¢
S.0+p (Mame+ cowkaimt rnoias
co: PL NAMe: cowaint Co eddy )5
ely ree
dabse
Scanned with CamScanner* equoltt
this method fs uxd te Compares the fus0 given Stivgs,
Th both ove cpusl ik ralim ue cthenwite th gullies false
Syulax- equals Conother shing)
colt? hing siz “madhu"j
Shing SL “madhu"s
Shag S12 MADHU"S
S-0-P (ste equal (s2))5
Boone (Sle eguals( $29);
StF Wwe
false
% Length 0!
lengthot
shic walked is wed & dod the length de hig, De
gullies count & tala) numbers ch Chowarlers +
Syalan t= tak lenglh O)
Bromfe: hing She Madhu"
shiny Sie “Tadhwdla"
siorp (Slelemgth0;
Gore C $2 lengthO;
oy
4
% Substing O'
ais melted sabia a. part oh the shaig, Gb ts wed
to ontrack some pant ob given Sng
gyNlac “subshing Cink slavtinden)
ond
Subshing (int clastinden, Ik evdivden)
cramer shang t= “Madhu; :
SOP (stesubsming (2) 4)) 5
Sop C AU, Sub Shug 09) 5
Slt! dhu
hu
Scanned with CamScanner| ax stavketaith OO
ans method checks
Th vations fue if TH Starts
Ro
if thas Shing glare with given |
Lu th given prden else
prefen +
rates dese
gyal stintaluith (sting pred) |
Whee predin jy Sepuence ct chayadlars. |
Examplet — ghing ste “Madhu t
SOP cst. stavtinith Cma"))2
sore (St sladrwih var) |
SE ae |
False |
% endcftith 0! |
ee i ive de
vig method checks He THs ching wh with ral
n e.
Gk valins true iF TS andy with given pea clse rete
_syitanrs endsntith Cobind pret)
tkeve puter WS Segueue de thavadert- |
exomple!- ghing S12 “Modhu" !
sap CS ands ith Che);
Sor P CSI ends pita Caw);
cle rut
fale
* weplace OF
chic walked is ur 18 moploee ald chavadive WHT
new chovadavs Tao given shang +
dldchav, chor newocher)
syufew yeplace Ceher
exambet- shang siz “ gova is am oop’:
SOP CSterveplae (to? st Db
Sion p (Stevaplate C“és", “Was"))?
is in cop
divi
Tova wor on COP
Scanned with CamScanner|
| # ddecatot
This method vebwns tader ag
oy subshing. Db ib is net found, if
~.
counter stavls from 20v0-
rven Clrevodey value
ubierny -\, The Madox
ink Asomindon )
inden of (Shing Subthog) |
|
syntax: tent (chor Ch)
indexOf (chav iy
index af (Shing Subshing
Example?
Example shing = "Yes madhu" 5
S.0:p (&- indenod Cs'yy ait grakesnns
geoep ($+ indenod C'S", 4905 1
SOP Cor iwdecaf ChE te
SsorP CS:
% te Lowey Case O+~
de Lowey Case
state method
lovey case
Example!
op
we te Uppey Cose 0 *-
hs
giver shang tats upper
Spo
Example
method
se und to convert
\ettews
Syntax t
toLowey Case OO
shang vame=" MAdhu"
S.0+p (name teLowsey Cos
mad hu
y cose. lather «
AoUppev Coase
shang names “ modhu" 3
S.0.8 (name « touppey C
MADHUe
inden ot (MS, USS UE velo -f
ie ued te convert all Chevadivs “in
ink damnivden) |
1 xdlovy ©
selene 2
gwen sting Wo
2095
ostOL
Scanned with CamScanner