6_Object-oriented-using-java.pdf object oriented programming concepts

harinipradeep15 41 views 238 slides Aug 29, 2024
Slide 1
Slide 1 of 496
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170
Slide 171
171
Slide 172
172
Slide 173
173
Slide 174
174
Slide 175
175
Slide 176
176
Slide 177
177
Slide 178
178
Slide 179
179
Slide 180
180
Slide 181
181
Slide 182
182
Slide 183
183
Slide 184
184
Slide 185
185
Slide 186
186
Slide 187
187
Slide 188
188
Slide 189
189
Slide 190
190
Slide 191
191
Slide 192
192
Slide 193
193
Slide 194
194
Slide 195
195
Slide 196
196
Slide 197
197
Slide 198
198
Slide 199
199
Slide 200
200
Slide 201
201
Slide 202
202
Slide 203
203
Slide 204
204
Slide 205
205
Slide 206
206
Slide 207
207
Slide 208
208
Slide 209
209
Slide 210
210
Slide 211
211
Slide 212
212
Slide 213
213
Slide 214
214
Slide 215
215
Slide 216
216
Slide 217
217
Slide 218
218
Slide 219
219
Slide 220
220
Slide 221
221
Slide 222
222
Slide 223
223
Slide 224
224
Slide 225
225
Slide 226
226
Slide 227
227
Slide 228
228
Slide 229
229
Slide 230
230
Slide 231
231
Slide 232
232
Slide 233
233
Slide 234
234
Slide 235
235
Slide 236
236
Slide 237
237
Slide 238
238
Slide 239
239
Slide 240
240
Slide 241
241
Slide 242
242
Slide 243
243
Slide 244
244
Slide 245
245
Slide 246
246
Slide 247
247
Slide 248
248
Slide 249
249
Slide 250
250
Slide 251
251
Slide 252
252
Slide 253
253
Slide 254
254
Slide 255
255
Slide 256
256
Slide 257
257
Slide 258
258
Slide 259
259
Slide 260
260
Slide 261
261
Slide 262
262
Slide 263
263
Slide 264
264
Slide 265
265
Slide 266
266
Slide 267
267
Slide 268
268
Slide 269
269
Slide 270
270
Slide 271
271
Slide 272
272
Slide 273
273
Slide 274
274
Slide 275
275
Slide 276
276
Slide 277
277
Slide 278
278
Slide 279
279
Slide 280
280
Slide 281
281
Slide 282
282
Slide 283
283
Slide 284
284
Slide 285
285
Slide 286
286
Slide 287
287
Slide 288
288
Slide 289
289
Slide 290
290
Slide 291
291
Slide 292
292
Slide 293
293
Slide 294
294
Slide 295
295
Slide 296
296
Slide 297
297
Slide 298
298
Slide 299
299
Slide 300
300
Slide 301
301
Slide 302
302
Slide 303
303
Slide 304
304
Slide 305
305
Slide 306
306
Slide 307
307
Slide 308
308
Slide 309
309
Slide 310
310
Slide 311
311
Slide 312
312
Slide 313
313
Slide 314
314
Slide 315
315
Slide 316
316
Slide 317
317
Slide 318
318
Slide 319
319
Slide 320
320
Slide 321
321
Slide 322
322
Slide 323
323
Slide 324
324
Slide 325
325
Slide 326
326
Slide 327
327
Slide 328
328
Slide 329
329
Slide 330
330
Slide 331
331
Slide 332
332
Slide 333
333
Slide 334
334
Slide 335
335
Slide 336
336
Slide 337
337
Slide 338
338
Slide 339
339
Slide 340
340
Slide 341
341
Slide 342
342
Slide 343
343
Slide 344
344
Slide 345
345
Slide 346
346
Slide 347
347
Slide 348
348
Slide 349
349
Slide 350
350
Slide 351
351
Slide 352
352
Slide 353
353
Slide 354
354
Slide 355
355
Slide 356
356
Slide 357
357
Slide 358
358
Slide 359
359
Slide 360
360
Slide 361
361
Slide 362
362
Slide 363
363
Slide 364
364
Slide 365
365
Slide 366
366
Slide 367
367
Slide 368
368
Slide 369
369
Slide 370
370
Slide 371
371
Slide 372
372
Slide 373
373
Slide 374
374
Slide 375
375
Slide 376
376
Slide 377
377
Slide 378
378
Slide 379
379
Slide 380
380
Slide 381
381
Slide 382
382
Slide 383
383
Slide 384
384
Slide 385
385
Slide 386
386
Slide 387
387
Slide 388
388
Slide 389
389
Slide 390
390
Slide 391
391
Slide 392
392
Slide 393
393
Slide 394
394
Slide 395
395
Slide 396
396
Slide 397
397
Slide 398
398
Slide 399
399
Slide 400
400
Slide 401
401
Slide 402
402
Slide 403
403
Slide 404
404
Slide 405
405
Slide 406
406
Slide 407
407
Slide 408
408
Slide 409
409
Slide 410
410
Slide 411
411
Slide 412
412
Slide 413
413
Slide 414
414
Slide 415
415
Slide 416
416
Slide 417
417
Slide 418
418
Slide 419
419
Slide 420
420
Slide 421
421
Slide 422
422
Slide 423
423
Slide 424
424
Slide 425
425
Slide 426
426
Slide 427
427
Slide 428
428
Slide 429
429
Slide 430
430
Slide 431
431
Slide 432
432
Slide 433
433
Slide 434
434
Slide 435
435
Slide 436
436
Slide 437
437
Slide 438
438
Slide 439
439
Slide 440
440
Slide 441
441
Slide 442
442
Slide 443
443
Slide 444
444
Slide 445
445
Slide 446
446
Slide 447
447
Slide 448
448
Slide 449
449
Slide 450
450
Slide 451
451
Slide 452
452
Slide 453
453
Slide 454
454
Slide 455
455
Slide 456
456
Slide 457
457
Slide 458
458
Slide 459
459
Slide 460
460
Slide 461
461
Slide 462
462
Slide 463
463
Slide 464
464
Slide 465
465
Slide 466
466
Slide 467
467
Slide 468
468
Slide 469
469
Slide 470
470
Slide 471
471
Slide 472
472
Slide 473
473
Slide 474
474
Slide 475
475
Slide 476
476
Slide 477
477
Slide 478
478
Slide 479
479
Slide 480
480
Slide 481
481
Slide 482
482
Slide 483
483
Slide 484
484
Slide 485
485
Slide 486
486
Slide 487
487
Slide 488
488
Slide 489
489
Slide 490
490
Slide 491
491
Slide 492
492
Slide 493
493
Slide 494
494
Slide 495
495
Slide 496
496

About This Presentation

java concepts


Slide Content

Object Oriented Programming
Concepts
PreparedusingfollowingResources:
➢Herbert Schildt, “Java: The Complete Reference”,Tata McGrawHillEducation
➢E Balagurusamy, Programming with Java -ATata McGraw Hill Education
➢https://www.geeksforgeeks.org/java/
➢https://www.javatpoint.com/java-tutorial
➢https://www.tutorialspoint.com/java/index.htm
➢https://www.w3schools.com/java/
By: DIVAKARA .N

•Background
•Programming Paradigms
•Concepts of OOPL
•Major and Minor elements
•Class, Object and relationships among objects
•Encapsulation
•Polymorphism
•Inheritance
•Message passing
•Difference between OOP and other conventional
programming
•Advantages, Disadvantages and Applications

Background:
•Theprocessproblemsolvingusingacomputeris
complicatedprocessrequiringcarefulplanning,
logicalprecision,persistenceandattentionto
detail.
•Aprogrammersprimarytaskistowritesoftwareto
solveaproblem.
•Manyprogrammingmodelshaveevolvedtohelp
programmersinbeingmoreeffectivesuchas
Modular,Top-down,Bottom-up,Structured,
Object-Orientedprogramsetc.

Programming Paradigms:
•All computer programs consists of two elements:
Codeand
Data
•Aprogramcanbeconceptuallyorganisedaround
itscodeorarounditsdata.
•MajorProgrammingParadigmsare:
ProcedureOriented
ObjectOriented

Programming Paradigms: … POP
•Theinterdependentfunctionscannotbeusedinother
programs.Asaresult,evenforasimilartaskacross
programs,theentirefunctionhastoberecoded.This
madeprogramdevelopmentamorecomplextask.
•Achangemeansrewritinghugeportionsofthecode.
Asaresultofthis,softwaremaintenancecostsarevery
high.
•Thisapproachfailedtoshowthedesiredresultin
termsbugfree,easy-to-maintainandreusable
programs.

Programming Paradigms: … OOP
•Anapproachthatprovidesawayofmodularizing
programsbycreatingpartitionedmemoryareaforboth
dataandcodethatcanbeusedastemplatesfor
creatingcopiesofsuchmodulesondemand.
•OOPisaprogrammingmethodologythathelps
organizingcomplexprogramsthroughtheuseofthe
threeprinciples–Encapsulation,Polymorphismand
Inheritance.
•OOPenablesyoutoconsiderareal-worldentityasan
object.
•OOPcombinesuser-defineddataandinstructionsinto
asingleentitycalledanObject.

Programming Paradigms: … OOP…
Itisawellsuitedparadigmforthefollowing:
•Modellingtherealworldproblemascloseas
possibletotheperspectiveoftheuser.
•Constructingreusablesoftwarecomponentsand
easilyextendablelibraries.
•Easilymodifyingandextendingimplementations
ofcomponentswithouthavingtorecodeeverything
fromscratch.

Concepts of OOP Languages
•Classes
•Objects
•Encapsulation
•Polymorphism
•Inheritance
•DynamicBinding
•MessageCommunication

Concepts of OOP Languages…
Classes:“Anuser-defineddatatype/ADT”
•Ablueprintusedtoinstantiatemanyobjects.
•Definessetofdatamembers(States/Attributes)andsetof
methods(Behaviors).
•Atemplateforanobject/Collectionofobjectsofsimilar
type.
•Nomemoryisallocatedwhenaclassiscreated.Memory
isallocatedonlywhenanobjectiscreated,i.e.,whenan
instanceofaclassiscreated.

Concepts of OOP Languages…
Classes:…
•Eg:AClassofCarsunderwhichSantroXing,AltoandWaganR
representsindividualObjects.InthiscontexteachCarObjectwill
haveitsown,Model,YearofManufacture,Colour,TopSpeed,
EnginePoweretc.,whichformPropertiesoftheCarclassandthe
associatedactionsi.e.,objectfunctionslikeStart,Move,Stopform
theMethodsofCarClass.

Concepts of OOP Languages…
Objects:“Instances”
•ThebasicBuildingBlocks/Run-timeEntitieshavingtwocharacteristics:Stateand
Behavior.
•AnObjectisacollectionofdatamembersandassociatedmemberfunctionsalso
knownasmethods.
•Eachinstanceofanobjectcanholditsownrelevantdata.
•Memoryisallocatedonlywhenanobjectiscreated,i.e.,whenaninstanceofa
classiscreated.
•Eg:Employeeemp1;emp1=newEmployee();OR
Employeeemp1=newEmployee();

Concepts of OOP Languages…
Encapsulation:“WrapsDataandMethod”
•ThemechanismthatbindstogetherCodeandtheDatait
manipulates.
•Keepsbothsafefromoutsideinterferenceandmisuse.
•Thewrappingupofdataandmethodsintoasingleunit
calledclass,accessistightlycontrolledthroughawell
definedinterfaces.

Concepts of OOP Languages…
Polymorphism:“abilitytotakemorethanoneform”
•Afeaturethatallowsoneinterfacetobeusedforageneral
classofactions.
•Itallowsanobjecttohavedifferentmeanings,depending
onitscontext.
•“OneInterface,MultipleMethods”todesignageneric
interfacetoagroupofrelatedactivities.
•Eg:Coffeedayvendingmachine

Concepts of OOP Languages…
Polymorphism:…

Concepts of OOP Languages…
Inheritance:“TheIdeaofReusability”
•Theprocessbywhichoneobjectacquiresthepropertiesofanother
objectORtheprocessofforminganewclassfromanexistingclassor
baseclass.
•Supportstheconceptsofhierarchicalclassifications.
•Inheritancehelpsinreducingtheoverallcodesizeoftheprogram.

Concepts of OOP Languages…
Dynamic Binding: “Associated with the concept of
Inheritance and Polymorphism”
•Atrun-timethecodematchingtheobjectundercurrent
referencewillbecalled.

Concepts of OOP Languages…
MessageCommunication:“Arequestforexecutionofamethod”
•Objectscommunicatewithoneanotherbysendingand
receivinginformation.
•Amessageofanobjectisarequestforexecutionofa
procedure/methodthatgeneratesdesiredresult.
•Eg:student1.examResult(4JC10CS901);

Difference between OOP and other conventional programming
Procedure Oriented Object Oriented
Emphasisisonprocedureratherthan
data,characterisesaprogramasa
seriesoflinearsteps.
Emphasisisondata,dataishiddenand
cannotbeaccessedbyexternalfunctions.
Process-centric approach Data-centric approach
Programsarewrittenaround“Whatis
happening”–Codeactingondata.
Programsarewrittenaround“Whois
beingaffected”–Datacontrollingaccess
tocode.
Programs are divided into smaller
parts called functions/modules.
Programs are divided into objects, may
communicate with each other through
methods.
Function can call one from anther and
difficult to separate due to
interdependency between modules.
Objects are independent used for different
programs.
Follows Top-down approach in
program design.
Follows Bottom-up approach.
Eg: Basic, Pascal, COBOL, Fortran,
C, etc.
Eg: Smalltalk, C++, Objective C, Ada,
Objective Pascal, Java(Pure OOL), etc.

Advantages and Disadvantages
Advantages:
Simplicity:softwareobjectsmodelrealworldobjects,sothe
complexityisreducedandtheprogramstructureisveryclear.
Modularity:eachobjectformsaseparateentitywhose
internalworkingsaredecoupledfromotherpartsofthe
system.
Modifiability:itiseasytomakeminorchangesinthedata
representationortheproceduresinanOOprogram.Changes
insideaclassdonotaffectanyotherpartofaprogram,since
theonlypublicinterfacethattheexternalworldhastoaclass
isthroughtheuseofmethods.

Advantages and Disadvantages
Advantages:...
Extensibility(Resilience–Systemcanbeallowedtoevolve):addingnew
featuresorrespondingtochangingoperatingenvironmentscanbesolved
byintroducingafewnewobjectsandmodifyingsomeexistingones.
Maintainability:objectscanbemaintainedseparately,makinglocating
andfixingproblemseasier.
Re-usability:objectscanbereusedindifferentprograms.
DesignBenefits:Largeprogramsareverydifficulttowrite.OOPsforce
designerstogothroughanextensiveplanningphase,whichmakesfor
betterdesignswithlessflaws.Inaddition,onceaprogramreachesacertainsize,
ObjectOrientedProgramsareactuallyeasiertoprogramthannon-ObjectOriented
ones.

Advantages and Disadvantages…
Disadvantages:
•Size:Programsaremuchlargerthanotherprograms.
•Effort:Requirealotofworktocreate,codersspentmoretime
actuallywritingtheprogram.
•Speed:Slowerthanotherprograms,partiallybecauseoftheirsize
alsodemandmoresystemresources.
•Notallprogramscanbemodelledaccuratelybytheobjectsmodel.
•Oneprogrammer'sconceptofwhatconstitutesanabstractobject
mightnotmatchthevisionofanotherprogrammer.
However;manynoviceprogrammersdonotlikeObjectOriented
Programmingbecauseofthegreatdealofworkrequiredtoproduce
minimalresults.

Applications:
•User-InterfaceDesign(CUI/CLI,GUI...WIN),Games,CAD/CAM/CIMsystems
•Real-TimeSystem
•SimulationandModeling
•Object-OrientedDatabase
•ArtificialIntelligenceandExpertSystems
•NeuralNetworksandParallelPrograms
•DecisionSupportandOfficeAutomationSystem
Asoftwarethatiseasytousehardtobuild.OOPchangesthe
waysoftwareengineerswillThink,Analyse,Designand
Implementsystemsinthefuture.

Overview of Java
PreparedusingfollowingResources:
➢Herbert Schildt, “Java: The Complete Reference”,Tata McGrawHillEducation
➢E Balagurusamy, Programming with Java -ATata McGraw Hill Education
➢https://www.geeksforgeeks.org/java/
➢https://www.javatpoint.com/java-tutorial
➢https://www.tutorialspoint.com/java/index.htm
➢https://www.w3schools.com/java/
By: DIVAKARA .N

•The History and Evolution
•Overview and basic concepts
•Features, Advantages and Applications
•Java Development Kit (JDK) and JVM
•Simple Java programs
•Data types and Variables, dynamic initialization , the scope and
lifetime of variables
•Type conversion and casting
•Operators and Expressions: Operator Precedence, Logical
expression, Access specifiers
•Control statements & Loops and
•Arrays

The History and Evolution:
•Javaisablendofthebestelementsofitsrichheritage
combinedwiththeinnovativeconceptsrequiredbyits
uniquemission.
•AlthoughJavahasbecomeinseparablylinkedwiththe
onlineenvironmentoftheInternet,itisimportantto
rememberthatJavaisfirstandforemostaprogramming
language.
•Computerlanguageinnovationanddevelopmentoccursfortwo
fundamentalreasons:
▪Toadapttochangingenvironmentsanduses
▪Toimplementrefinementsandimprovementsintheartofprogramming

The History and Evolution: ...
•JavaisrelatedtoC++,whichisadirectdescendantofC.
•MuchofthecharacterofJavaisinheritedfromthesetwo
languages.
▪FromC,Javaderivesitssyntax.
▪Object-orientedfeatureswereinfluencedbyC++.
Bytheendofthe1980sandtheearly1990s,object-orientedprogrammingusingC++
tookhold.Indeed,forabriefmomentitseemedasifprogrammershadfinallyfound
theperfectlanguage.BecauseC++blendedthehighefficiencyandstylisticelements
ofCwiththeobject-orientedparadigm,itwasalanguagethatcouldbeusedtocreate
awiderangeofprograms.

The History and Evolution: ...
•However,justasinthepast,forceswerebrewingthatwould,once
again,drivecomputerlanguageevolutionforward.Withinafew
years,theWorldWideWebandtheInternetwouldreachcritical
mass.Thiseventwouldbringaboutabruptlyanotherrevolutionin
programming.
•JavawasconceivedbyJamesGosling,PatrickNaughton,Chris
Warth,EdFrank,andMikeSheridanatSunMicrosystems,Inc.in
1991.Itwasinitiallycalled“Oak”butwasrenamed“Java”in1995.
•BillJoy,ArthurvanHoff,JonathanPayne,FrankYellin,andTim
Lindholmwerekeycontributorstothematuringoftheoriginal
prototype.

The History and Evolution: ...
•OriginalimpetusforJavawasnottheInternet!Instead,theprimary
motivationwastheneedforaplatform-independent(i.e.,
architecture-neutral)languagethatcouldbeusedtocreatesoftware
tobeembeddedinvariousconsumerelectronicdevices,suchas
microwaveovensandremotecontrols.
•Goslingandothersbeganworkonaportable,platform-independent
languagethatcouldbeusedtoproducecodethatwouldrunona
varietyofCPUsunderdifferingenvironments.
•JavawasnotdesignedtoreplaceC++.Javawasdesignedtosolvea
certainsetofproblems.C++wasdesignedtosolveadifferentsetof
problems.

The History and Evolution: ...
•Today,withtechnologysuchapartofourdailylives,wetakeitfor
grantedthatwecanbeconnectedandaccessapplicationsand
contentanywhere,anytime.BecauseofJava,weexpectdigital
devicestobesmarter,morefunctional,andwaymoreentertaining.
•Today,JavanotonlypermeatestheInternet,butalsoistheinvisible
forcebehindmanyoftheapplicationsanddevicesthatpowerour
day-to-daylives.
•Frommobilephonestohandhelddevices,gamesandnavigation
systemstoe-businesssolutions,Javaiseverywhere!

The History and Evolution: ...
•ThefirstversionofJavaDevelopmentKit,TheJDK1.0wasreleasedonJanuary
23,1996.FromthefewhundredclassfilestheJDK1.0had,ithasnowgrown
dramaticallyintomorethan3000classesinJ2SE5.0,J2SE6,...
•NowJavaisextensivelyusedtoprogramstandaloneapplicationstoMultitierweb
applications.
➢JDK 1.0 (January 23, 1996)
➢JDK 1.1 (February 19, 1997)
➢J2SE 1.2 (December 8, 1998)
➢J2SE 1.3 (May 8, 2000)
➢J2SE 1.4 (February 6, 2002)
➢J2SE 5.0 (September 30, 2004)
➢Java SE 6 (December 11, 2006)
➢Java SE 7 (July 28, 2011)
➢Java SE 8 (March 18, 2014)

The History and Evolution: ...Brief Summary
•In1990,SunMicrosystemsinitiatedateamtodevelopsoftwarefor
consumerelectronicsdevicesheadedbyJamesGosling.
•In1991,theteamannouncedthe“Oak”fromC++
•In1992,GreenProjectteambySundemonstratedtheapplicationto
homeappliances.
•In1993,Transformationoftext-basedinternetintoagraphical-rich
environment.(Applets)
•In1994,HotJava–webbrowsertolocate&runapplets
•In1995,OakrenamedasJava.
•In1996,LeaderasGeneralPurposeProgrammingLanguage/
OOPL.

Overview and Basic Concepts:
•OriginallydevelopedbySunMicrosystems,initiatedbyJamesGosling.Withthe
advancementofJavaanditswidespreadpopularity,multipleconfigurationswere
builttosuitevarioustypesofplatforms.Ex:J2EEforEnterpriseApplications,
J2MEforMobileApplications.SunMicrosystemshasrenamedthenewJ2
versionsasJavaSE,JavaEEandJavaME,respectively.
•JavaisguaranteedtobeWriteOnce,RunAnywhere.
•Javaiseasytolearn.Javawasdesignedtobeeasytouseandisthereforeeasyto
write,compile,debug,andlearnthanotherprogramminglanguages.
•Javaisobject-oriented.Thisallowsyoutocreatemodularprogramsandreusable
code.
•Javaisplatform-independent.

Features: -The Java Buzzwords
ThekeyconsiderationsweresummedupbytheJava
teaminthefollowinglistofbuzzwords:
Simple,Secure,Portable,Object-oriented,
Robust,Multithreaded,Architecture-
neutral,Interpreted,Highperformance,
DistributedandDynamic

Features: -The Java Buzzwords...
•Simple:Javawasdesignedtobeeasyfortheprofessionalprogrammertolearnand
useeffectively.ItcontainsmanyfeaturesofotherLanguageslikecandC++and
JavaRemovesComplexitybecauseitdoesn’tusepointers.
•Secure:JavaachievedprotectionbyconfininganapplettotheJavaexecution
environmentandnotallowingitaccesstootherpartsofthecomputer.
•Portable:Thesamecodemustworkonallcomputers.Beingarchitectural-neutral
andhavingnoimplementationdependentaspectsofthespecificationmakesJava
portable.
•Object-oriented:InJava,everythingisanObject.Javacanbeeasilyextended
sinceitisbasedontheObjectmodel.

Features: -The Java Buzzwords...
•Robust:Javamakesanefforttoeliminateerrorpronesituationsbyemphasizing
mainlyoncompiletimeerrorcheckingandruntimechecking.Alsoautogarbage
collectionmechanism.
•Multithreaded:Enablesustowriteprogramsthatcandomanytasks
simultaneously/concurrently.Thisdesignfeatureallowsdeveloperstoconstruct
smoothlyrunninginteractiveapplications.
•Architecture-neutral:AcentralissuefortheJavadesignerswasthatofcode
longevityandportability.Itfollows'Write-once-run-anywhere'WORAapproach.
Toagreatextent,thisgoalwasaccomplished.
•Interpreted:Javaenablesthecreationofcross-platformprogramsbycompiling
intoanintermediaterepresentationcalledJavabytecode.Thiscodecanbeexecuted
onanysystemthatimplementstheJavaVirtualMachine(JVM).

Features: -The Java Buzzwords...
•Highperformance:Javabytecodewascarefullydesignedsothatit
wouldbeeasytotranslatedirectlyintonativemachinecodeforvery
highperformancebyusingajust-in-time(JIT)compiler.
•Distributed:Javaisdesignedforthedistributedenvironmentofthe
InternetbecauseithandlesTCP/IPprotocols.AlsosupportsRemote
MethodInvocation(RMI)featureitenablesaprogramtoinvoke
methodsacrossanetwork.
•Dynamic:Itisdesignedtoadapttoanevolvingenvironment.Java
programscancarryextensiveamountofrun-timeinformationthat
canbeusedtoverifyandresolveaccessestoobjectsonrun-time.

Advantages:
•WriteOnce,RunAnywhere-Youonlyhavetowriteyour
applicationonce--fortheJavaplatform--andthenyou'llbeableto
runitanywhere.Javasupportisbecomingubiquitous.
•Security-Allowsuserstodownloaduntrustedcodeoveranetwork
andrunitinasecureenvironmentinwhichitcannotdoanyharm:it
cannotinfectthehostsystemwithavirus,cannotreadorwritefiles
fromtheharddrive,andsoforth.Thiscapabilityalonemakesthe
Javaplatformunique.
•Network-centricProgramming-Javamakesitunbelievablyeasyto
workwithresourcesacrossanetworkandtocreatenetwork-based
applicationsusingclient/serverormultitierarchitectures.“The
networkisthecomputer”

Advantages: ...
•Dynamic,ExtensiblePrograms-Javaapplicationcandynamicallyextend
itselfbyloadingnewclassesoveranetwork.
•Internationalization-Javauses16-bitUnicodecharactersthat
representthephoneticalphabetsandideographiccharactersetsofthe
entireworld.
•Performance-TheVMhasbeenhighlytunedandoptimizedin
manysignificantways.UsingsophisticatedJITcompilers,Java
programscanexecuteatspeedscomparabletothespeedsofnativeC
andC++applications.
•ProgrammerEfficiencyandTime-to-Market-Javaisanelegant
languagecombinedwithapowerfulandwell-designedsetofAPIs.

Applications:
✓Standalone/Desktop/Console–basedApplications
▪StandaloneCUI/GUIbasedapplications
✓WebApplications
▪AppletsandServlets
✓DistributedApplications
▪Databaseapplications
✓Client/ServerApplications

DIFFERENCES BETWEEN C , C++ AND JAVA
•CUsesheaderFilesbutjavausesPackages
•CUsesPointersbutjavadoesn’tsupportspointers.
•Javadoesn’tsupportsstorageclasseslikeauto,externaletc.
•TheCodeofCLanguageisConvertedintotheMachinecodeafterCompilationButinJava
CodeFirstConvertedintotheBytesCodesthenafteritisconvertedintotheMachineCode.
•C++supportsOperatorOverloadingbutjavadoesn’tSupportsOperatorOverloading.
•InC++MultipleInheritanceisPossiblebutinjavaAClassCannotInheritthefeatures
fromthetwoclassesinotherwordsjavadoesn’tsupportsMultipleInheritanceThe
ConceptofMultipleInheritancesisIntroducedintheFormofInterfaces.
•JavaUsesimportstatementforincludingthecontentsofscreeninsteadof#include.
•JavaDoesn’tusesgoto.
•JavaDoesn’thaveDestructorlikeC++InsteadJavaHasfinalizeMethod.
•JavaDoesn’thaveStructureUnion,enumdatatypes.

DIFFERENCES BETWEEN C++ and JAVA
C++andJavabothareObjectOrientedLanguagesbutsomeofthefeaturesofbothlanguages
aredifferentfromeachother.Someofthesefeaturesare:
•Allstand-aloneC++programsrequireafunctionnamedmainandcanhave
numerousotherfunctions,includingbothstand-alonefunctionsandfunctions,
whicharemembersofaclass.Therearenostand-alonefunctionsinJava.Instead,
thereareonlyfunctionsthataremembersofaclass,usuallycalledmethods.Global
functionsandglobaldataarenotallowedinJava.
•AllclassesinJavaultimatelyinheritfromtheObjectclass.Thisissignificantly
differentfromC++whereitispossibletocreateinheritancetreesthatare
completelyunrelatedtooneanother.
•Javadoesnotsupportmultipleinheritance.Tosomeextent,theinterfacefeature
providesthedesirablefeaturesofmultipleinheritancetoaJavaprogramwithout
someoftheunderlyingproblems.
•Javadoesnotsupportoperatoroverloading.

JavaRuntimeEnvironment(JRE):
•Thesmallestsetofexecutablesandfilesthatconstitutethe
standardjavaplotform.
•Itprovidesthelibraries,theJVM,andothercomponentsto
runappletsandapplicationswrittenintheJava
programminglanguage.
•Inaddition,twokeydeploymenttechnologiesarepartof
theJRE:JavaPlug-in,whichenablesappletstorunin
popularbrowsers;andJavaWebStart,whichdeploys
standaloneapplicationsoveranetwork.

JavaDevelopmentKit(JDK):
•TheJavaDevelopmentKit(JDK)isapackagethatincludesalarge
numberofdevelopmenttoolsandhundredsofclasses,JavaStandard
libraryAPIsandmethods.
•TheJDKisdevelopedbySunMicrosystem's.itcontainJREand
developmenttools.
•JDKprovidestoolsforuserstointegrateandexecuteapplications
andApplets.
•Eg.javac,java,javap,jdb,javah,javadoc,appletviwer…

JavaDevelopmentKit(JDK):...
•javac-TheJavaCompiler,itcompilesJavasourcecode
intoJavabytecodes.
javacfilename.java
•java-TheJavaInterpreter,itexecutesJavaclassfiles
createdbyaJavacompiler.
javaclassfilename
•javap-TheJavaClassFileDisassembler,Disassembles
classfiles.Itsoutputdependsontheoptionsused.
javap[options]classfilename

JavaDevelopmentKit(JDK):...
•jdb-TheJavaDebugger,helpsyoufindandfixbugsin
Javalanguageprograms.
jdb[options]
•javah-CHeaderandStubFileGenerator,producesC
headerfilesandCsourcefilesfromaJavaclass.These
filesprovidetheconnectivegluethatallowyourJavaand
Ccodetointeract.
javah[options]classfilename

JavaDevelopmentKit(JDK):...
•javadoc-TheJavaAPIDocumentationGeneratorGenerates
HTMLpagesofAPIdocumentationfromJavasourcefiles,parses
thedeclarationsanddocumentationcommentsinasetofJavasource
filesandproducesasetofHTMLpages.
javadoc[options][package|source.java]*
•appletviewer-Theappletviewercommandallowsyoutorun
appletsoutsideofawebbrowser.
appletviewer[options]filename.html[URLs]

JavaDevelopmentKit(JDK):...
The Java Programming Environment
Java Source
Code
Text
Editor
HTML Filesjavadoc
Java class file / Bytecode
javac
java
Header Filesjavah
jdb
Output

JavaVirtualMachine(JVM):-‘Simulatedcomputerwithinthecomputer’
•JVMisthevirtualmachinethatruntheJavabytecode.It's
alsotheentitythatallowsJavatobea"portablelanguage"
(writeonce,runanywhere).Indeedtherearespecific
implementationsoftheJVMfordifferentsystems
(Windows,Linux,MacOS,..),theaimisthatwiththesame
bytecodetheyallgivethesameresults(i.e.JVMis
platformdependent).

Basic Structure of Java programs:
Documentation Section
Package Statements
Import Statements
Interface Statements
Class Definitions
main methodclass{
//Definitions
}

Simple Java programs:
/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java program.");
}
}

Simple Java programs: ...
EnteringtheProgram:
•Formostcomputerlanguages,thenameofthefilethatholdsthesourcecodetoa
programisimmaterial.Forthisexample,thenameofthesourcefileshouldbe
Example.java.
•InJava,asourcefileisofficiallycalledacompilationunit.Itisatextfilethat
containsoneormoreclassdefinitions.TheJavacompilerrequiresthatasourcefile
usethe.javafilenameextension.
•InJava,allcodemustresideinsideaclass.Byconvention,thenameofthatclass
shouldmatchthenameofthefilethatholdstheprogram.
•Youshouldalsomakesurethatthecapitalizationofthefilenamematchestheclass
name.
•TheJavaiscase-sensitive.Theconventionthatfilenamescorrespondtoclass
namesmayseemarbitrary.However,thisconventionmakesiteasiertomaintain
andorganizeyourprograms.

Simple Java programs: ...
CompilingtheProgram:
•TocompiletheExampleprogram,executethecompiler,javac,specifyingthe
nameofthesourcefileonthecommandline,asshownhere:
C:\>javacExample.java
•ThejavaccompilercreatesafilecalledExample.classthatcontainsthebytecode
versionoftheprogram.TheJavabytecodeistheintermediaterepresentationof
yourprogramthatcontainsinstructionstheJavaVirtualMachinewillexecute.
Thus,theoutputofjavacisnotcodethatcanbedirectlyexecuted.
•Toruntheprogram,youmustusetheJavaapplicationlauncher,calledjava
C:\>java Example

Simple Java programs: ...
CompilingtheProgram:...
•When the program is run, the following output is displayed:
This is a simple Java program.
•WhenJavasourcecodeiscompiled,eachindividualclassisputintoitsown
outputfilenamedaftertheclassandusingthe.classextension.Thisiswhyitisa
goodideatogiveyourJavasourcefilesthesamenameastheclasstheycontain-the
nameofthesourcefilewillmatchthenameofthe.classfile.Whenyouexecute
javaasjustshown,youareactuallyspecifyingthenameoftheclassthatyouwant
toexecute.Itwillautomaticallysearchforafilebythatnamethathasthe.class
extension.Ifitfindsthefile,itwillexecutethecodecontainedinthespecified
class.

Simple Java programs: ...
ACloserLookattheFirstSampleProgram:
Example.javaincludesseveralkeyfeaturesthatarecommontoallJavaprograms.
Theprogrambeginswiththefollowinglines:
/*
ThisisasimpleJavaprogram.
Callthisfile"Example.java".
*/
•Thisisacomment.Likemostotherprogramminglanguages,Javaletsyouentera
remarkintoaprogram'ssourcefile.Thecontentsofacommentareignoredbythe
compiler.Instead,acommentdescribesorexplainstheoperationoftheprogramto
anyonewhoisreadingitssourcecode.
•Inrealapplications,commentsgenerallyexplainhowsomepartoftheprogram
worksorwhataspecificfeaturedoes.

Simple Java programs: ...
ACloserLookattheFirstSampleProgram:...
•Java supports three styles of comments.
•// Single line comment
•/* and end with */ A multiline comment
•/**documentation*/calleddoccomment,theJDKjavadoctoolusesdoc
commentswhenpreparingautomaticallygenerateddocumentation.
•Any comments are ignored by the compiler.
•class Example {
•This line uses the keyword classto declare that a new class is being defined. The
entire class definition, including all of its members, will be between the opening
curly brace ({) and the closing curly brace (}).

Simple Java programs: ...
ACloserLookattheFirstSampleProgram:...
public static void main(String args[]) {
•The main( ) method, at which the program will begin executing. All Java
applications begin execution by calling main( ).
•Thepublickeywordisanaccessspecifier,whichallowstheprogrammerto
controlthevisibilityofclassmembers.Whenaclassmemberisprecededby
public,thenthatmembermaybeaccessedbycodeoutsidetheclassinwhichitis
declared.
•Theoppositeofpublicisprivate,whichpreventsamemberfrombeingusedby
codedefinedoutsideofitsclass.

Simple Java programs: ...
ACloserLookattheFirstSampleProgram:...
public static void main(String args[]) {
•Inthiscase,main()mustbedeclaredaspublic,sinceitmustbe
calledbycodeoutsideofitsclasswhentheprogramisstarted.
•Thekeywordstaticallowsmain()tobecalledwithouthavingto
instantiateaparticularinstanceoftheclass.Thisisnecessarysince
main()iscalledbytheJVMbeforeanyobjectsaremade.
•Thekeywordvoidsimplytellsthecompilerthatmain()doesnot
returnavalue.

Simple Java programs: ...
/*
Here is another short example.
Call this file "Example2.java".
*/
class Example2 {
public static void main(String args[]) {
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("The value of num * 2 is ");
System.out.println(num);
}
}

Two Control Statements:
•TheifStatement:Syntacticallyidenticaltotheifstatementsin
C,C++,andC#.Itssimplestformisshownhere:
if(condition) statement;
•Here,conditionisaBooleanexpression.Ifconditionistrue,thenthe
statementisexecuted.Ifconditionisfalse,thenthestatementis
bypassed.
Example: if(num < 100) System.out.println("num is less than 100");
•Java defines a full complement of relational operators which may be
used in a conditional expression. Here are a few: >, < and ==

Two Control Statements:
•TheifStatement:...

Two Control Statements: ...
•TheforLoop:Javasuppliesapowerfulassortmentofloop
constructs.Perhapsthemostversatileistheforloop.Thesimplest
formoftheforloopisshownhere:
for(initialization; condition; iteration)
statement;
•Initsmostcommonform,theinitializationportionoftheloopsetsaloopcontrol
variabletoaninitialvalue.TheconditionisaBooleanexpressionthatteststheloop
controlvariable.

Two Control Statements: ...
•UsingBlocksofCode:Javaallowstwoormorestatementsto
begroupedintoblocksofcode,alsocalledcodeblocks.Thisisdone
byenclosingthestatementsbetweenopeningandclosingcurly
braces,itbecomesalogicalunitthatcanbeusedanyplacethata
singlestatementcan.
•Eg:

Two Control Statements: ...
•UsingBlocksofCode:...

Lexical Issues :
•Javaprogramsareacollectionofwhitespace,identifiers,literals,
comments,operators,separators,andkeywords-Theatomic
elementsofJava

•Whitespace:Javaisafree-formlanguage.InJava,whitespaceisa
space,tab,ornewline.
•Identifiers:Usedforclassnames,methodnames,andvariable
names.Anidentifiermaybeanydescriptivesequenceofuppercase
andlowercaseletters,numbers,ortheunderscoreanddollar-sign
characters.Theymustnotbeginwithanumber,again,Javaiscase-
sensitive.,

Lexical Issues : ...
•Identifiers:...
✓AvgTemp,count,a4,$test,this_is_okareValid
✓2count,high-temp,Not/okareInvalid
•Literals: A constant value in Java is created by using a
literal representation of it. It can be used anywhere a value
of its type is allowed.
✓100, 98.6, 'X‘, "This is a test“
•Comments:Asmentioned,therearethreetypesof
commentsdefinedbyJava.

Lexical Issues : ...
•Separators:

Lexical Issues : ...
•TheJavaKeywords:50keywordscurrentlydefined,these
combinedwiththesyntaxoftheoperatorsandseparators,formthe
foundationoftheJavalanguage.Thesekeywordscannotbeusedas
namesforavariable,class,ormethod.
•Thekeywordsconstandgotoarereservedbutnotused.Intheearly
daysofJava,severalotherkeywordswerereservedforpossible
futureuse.
•Inadditiontothekeywords,Javareservesthefollowing:true,false,
andnull.ThesearevaluesdefinedbyJava.
•Youmaynotusethesewordsforthenamesofvariables,classes,and
soon.

Lexical Issues : ...
•TheJavaKeywords:...

•The History and Evolution
•Overview and basic concepts
•Features, Advantages and Applications
•Java Development Kit (JDK) and JVM
•Simple Java programs
•Data types and Variables, dynamic initialization , the
scope and lifetime of variables
•Type conversion and casting
•Operators and Expressions: Operator Precedence,
Logical expression, Access specifiers
•Control statements & Loops and
•Arrays

Data types and Variables
•TheJavaisastronglytypedlanguage,partofJava’ssafetyand
robustness.
•First,everyvariablehasatype,everyexpressionhasatype,and
everytypeisstrictlydefined.
•Second,allassignments,whetherexplicitorviaparameterpassingin
methodcalls,arecheckedfortypecompatibility.
•Therearenoautomaticcoercionsorconversionsofconflictingtypes
asinsomelanguages.
•TheJavacompilerchecksallexpressionsandparameterstoensure
thatthetypesarecompatible.Anytypemismatchesareerrorsthat
mustbecorrectedbeforethecompilerwillfinishcompilingtheclass.

Data types and Variables ...
Thedomainswhichdeterminewhattypeofcontentscanbestoredina
variable.InJava,therearetwotypesofdatatypes:
•Primitive/Simpledatatypes:Defineseighttypesofdata:
byte,short,int,long,char,float,double,andboolean.
•Reference data types: or Abstract datatypes
arrays, objects, interfaces, enum, Srtingetc.

Data types and Variables ...
Type Length Min. Value Max. Value
byte 8bits-128 127
short 16bits-32768 32767
int 32bits-2,147,483,648 2,147,483,647
long 64bits-9,223,372,036,854,775,808 9,223,372,036,854,775,80
float 32bits-3.4Е+38 +3.4Е+38
double 64bits-1.7Е+308 +1.7Е+308
boolean 1bit Possible values ​​are true orfalse
char 16bitsUnicode / International character set

Data types and Variables:...
•Integers:Javadefinesfourintegertypes:byte,short,int,andlong.
Allofthesearesigned,positiveandnegativevalues.Javadoesnot
supportunsigned,positive-onlyintegers.Eg:intnum1,num2,...
•However,theconceptofunsignedwasusedtospecifythebehaviorofthehigh-
orderbit,whichdefinesthesignofanintegervalue.
•Javamanagesthemeaningofthehigh-orderbitbyaddingaspecial“unsigned
rightshift”operator.Thus,theneedforanunsignedintegertypewaseliminated.

Data types and Variables:...
•byte:Thesmallestintegertype,asigned8-bittype,hasarangefrom
–128to127.
•Usefulwhenyou’reworkingwithastreamofdatafromanetworkor
file.Eg:byteByte1,Byte2,...
•short:Asigned16-bittype,hasarangefrom–32,768to32,767.Itis
probablytheleast-usedtype.Eg:shorts1,s2;
•int:Mostcommonlyusedintegertype,asigned32-bittypethathas
arangefrom–2,147,483,648to2,147,483,647.
•Variablesoftypeintarecommonlyemployedtocontrolloopsandto
indexarrays.byteandshortvaluesareusedinanexpressionare
promotedtointwhentheexpressionisevaluated.Eg:intnum1,
num2,...

Data types and Variables:...
•long:Asigned64-bittype,usefulforthoseoccasionswhereanint
typeisnotlargeenoughtoholdthedesiredvalue.
•Thismakesitusefulwhenbig,wholenumbersareneeded.

Data types and Variables:...
•Floating-PointTypes:Alsoknownasrealnumbers,areusedwhen
evaluatingexpressionsthatrequirefractionalprecision.Thereare
twokindsoffloating-pointtypes,floatanddouble,whichrepresent
single-anddouble-precisionnumbers.
•float:Specifiesasingle-precisionvaluethatuses32bitsofstorage,
Singleprecisionisfasteronsomeprocessors,Usefulwhenyouneed
afractionalcomponent,butdon’trequirealargedegreeofprecision.
Eg:floathightemp,lowtemp;

Data types and Variables:...
•double:Uses64bitstostoreavalue.Doubleprecisionisactually
fasterthansingleprecisiononsomemodernprocessorsthathave
beenoptimizedforhigh-speedmathematicalcalculations.All
transcendentalmathfunctions,suchassin(),cos(),andsqrt(),
returndoublevalues.
•char:A16-bittype,therangeofacharis0to65,536.Javauses
Unicodetorepresentcharacters.Unicodedefinesafully
internationalcharactersetthatcanrepresentallofthecharacters
foundinallhumanlanguages.Itisaunificationofdozensof
charactersets,suchasLatin,Greek,Arabic,Cyrillic,Hebrew,
Katakana,Hangul,andmanymore.

Data types and Variables:...
•char:...AnEg
•boolean:aprimitivetype,forlogicalvalues.Itcanhave
onlyoneoftwopossiblevalues,trueorfalse.Thisisthe
typereturnedbyallrelationaloperators.
// char variables behave like integers.
class CharDemo2 {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}

Data types and Variables:...
•boolean:...

Data types and Variables:...
A Closer Look at Literals
•IntegerLiterals:Themostcommonlyusedtypeinthetypical
program.Anywholenumbervalueisanintegerliteral.Eg:1,2,3,
and42.alldecimalvalues,describingabase10number.
•Therearetwootherbaseswhichcanbeusedinintegerliterals,octal
(baseeight)andhexadecimal(base16).
•OctalvaluesaredenotedinJavabyaleadingzero.Normaldecimal
numberscannothavealeadingzero.
•Yousignifyahexadecimalconstantwithaleadingzero-x,(0xor
0X).Therangeofahexadecimaldigitis0to15,soAthroughF(or
athroughf)aresubstitutedfor10through15.

Data types and Variables:...
A Closer Look at Literals...
•IntegerLiterals:...
•Integer literals create an intvalue, which in Java is a 32-bit integer value.
•itispossibletoassignanintegerliteraltooneofJava’sotherintegertypes,suchas
byteorlong,withoutcausingatypemismatcherror.
•When a literal value is assigned to a byteor shortvariable, no error is generated if
the literal value is within the range of the target type.
•Anintegerliteralcanalwaysbeassignedtoalongvariable.However,tospecifya
longliteral,youwillneedtoexplicitlytellthecompilerthattheliteralvalueisof
typelong.Youdothisbyappendinganupper-orlowercaseLtotheliteral.For
example,0x7ffffffffffffffLor9223372036854775807Listhelargestlong.An
integercanalsobeassignedtoacharaslongasitiswithinrange.

Data types and Variables:...
A Closer Look at Literals...
•Floating-PointLiterals:Representdecimalvalueswithafractional
component.Theycanbeexpressedineitherstandardorscientificnotation.
Standardnotationconsistsofawholenumbercomponentfollowedbyadecimal
pointfollowedbyafractionalcomponent.Forexample,2.0,3.14159,and0.6667
representvalidstandard-notationfloating-pointnumbers.
•TheexponentisindicatedbyanEorefollowedbyadecimalnumber,whichcan
bepositiveornegative.Examplesinclude6.022E23,314159E–05,and2e+100.
•Floating-point literals in Java default todoubleprecision. To specify a float literal,
you must append an F or f to the constant.
•YoucanalsoexplicitlyspecifyadoubleliteralbyappendingaDord.Doingsois,
ofcourse,redundant.

Data types and Variables:...
A Closer Look at Literals...
•BooleanLiterals:Simple,onlytwologicalvaluestrueandfalse.
Thesevaluesdonotconvertintoanynumericalrepresentation.The
trueliteralinJavadoesnotequal1,nordoesthefalseliteralequal0.
InJava,theycanonlybeassignedtovariablesdeclaredasboolean,
orusedinexpressionswithBooleanoperators.
•CharacterLiterals:IndicesintotheUnicodecharacterset,are16-
bitvaluesthatcanbeconvertedintointegersandmanipulatedwith
theintegeroperators,suchastheadditionandsubtractionoperators.
Aliteralcharacterisrepresentedinsideapairofsinglequotes.

Data types and Variables:...
A Closer Look at Literals...
•StringLiterals:Specifiedbyenclosingasequenceofcharactersbetweenapairof
doublequotes.Eg:“HelloWorld”

Data types and Variables:...
•Variables:Thebasicunitofstorage,definedbythecombinationof
anidentifier,atype,andanoptionalinitializer.Inaddition,all
variableshaveascope,whichdefinestheirvisibility,andalifetime.
The basic form of a variable declaration:
type identifier [ = value][, identifier [= value] ...] ;
inta, b, c; // declares three ints, a, b, and c.
intd = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159;// declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

Dynamic initialization:
•Javaallowsvariablestobeinitializeddynamically,usingany
expressionvalidatthetimethevariableisdeclared.
•Eg:
// Demonstrate dynamic initialization.
class DynInit{
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Note:Thekeypointhereisthattheinitializationexpressionmayuseanyelementvalidatthe
timeoftheinitialization,includingcallstomethods,othervariables,orliterals.

The Scope and Lifetime of Variables:
•Javaallowsvariablestobedeclaredwithinanyblock.
•Ablockisbegunwithanopeningcurlybraceandendedbyaclosing
curlybrace.
•Ablockdefinesascope.Thus,eachtimeyoustartanewblock,you
arecreatinganewscope.
•Ascopedetermineswhatobjectsarevisibletootherpartsofyour
program.Italsodeterminesthelifetimeofthoseobjects.
•Manyothercomputerlanguagesdefinetwogeneralcategoriesof
scopes:globalandlocal.However,thesetraditionalscopesdonotfit
wellwithJava’sstrict,object-orientedmodel.

The Scope and Lifetime of Variables:...

The Scope and Lifetime of Variables:...
One last point:Although blocks can be nested, you cannot declare a variable to have the
same name as one in an outer scope. For example, the following program is illegal:
// This program will not compile
class ScopeErr{
public static void main(String args[]) {
intbar = 1;
{ // creates a new scope
intbar = 2; // Compile-time error –bar already defined!
}
}
}

The Scope and Lifetime of Variables:...
•InJava,thetwomajorscopesarethosedefinedbyaclassandthose
definedbyamethod.
•Thescopedefinedbyamethodbeginswithitsopeningcurlybrace.
However,ifthatmethodhasparameters,theytooareincludedwithin
themethod’sscope.
•Asageneralrule,variablesdeclaredinsideascopearenotvisible
(thatis,accessible)tocodethatisdefinedoutsidethatscope.
•Scopescanbenested.Forexample,eachtimeyoucreateablockofcode,youare
creatinganew,nestedscope.Whenthisoccurs,theouterscopeenclosestheinner
scope.Thismeansthatobjectsdeclaredintheouterscopewillbevisibletocode
withintheinnerscope.However,thereverseisnottrue.

Type Conversion and Casting:
•Youalreadyknowthatitisfairlycommontoassignavalueofone
typetoavariableofanothertype.Ifthetwotypesarecompatible,
thenJavawillperformtheconversionautomatically.
•Forexample,itisalwayspossibletoassignanintvaluetoalong
variable.
•Fortunately,itisstillpossibletoobtainaconversionbetween
incompatibletypes.Todoso,youmustuseacast,whichperforms
anexplicitconversionbetweenincompatibletypes.
•Let’slookatbothautomatictypeconversionsandcasting.

Type Conversion and Casting:...
Java’s Automatic Conversions -Widening Conversion
•Whenonetypeofdataisassignedtoanothertypeofvariable,an
automatictypeconversionwilltakeplaceifthefollowingtwo
conditionsaremet:
➢The two types are compatible.
➢The destination type is larger than the source type.
•Whenthesetwoconditionsaremet,awideningconversiontakesplace.
•Forwideningconversions,thenumerictypes,includingintegerandfloating-point
types,arecompatiblewitheachother.
•Javaalsoperformsanautomatictypeconversionwhenstoringaliteralinteger
constantintovariablesoftypebyte,short,long,orchar.
•However,therearenoautomaticconversionsfromthenumerictypestocharor
boolean.Also,charandbooleanarenotcompatiblewitheachother.

Type Conversion and Casting:...
Casting Incompatible Types -Narrowing Conversion
•Tocreateaconversionbetweentwoincompatibletypes,youmust
useacast.Acastissimplyanexplicittypeconversion.
(target-type) value
•Eg:inta;
byte b;
// ...
b = (byte) a;
•Iftheinteger’svalueislargerthantherangeofabyte,itwillbe
reducedmodulo(theremainderofanintegerdivisionbythebyte’s
range)

Type Conversion and Casting:...
Casting Incompatible Types -Narrowing Conversion…
•Adifferenttypeofconversionwilloccurwhenafloating-pointvalueisassignedto
anintegertype:truncation.
Automatic Type Promotion in Expressions
byte a = 40;
byte b = 50;
byte c = 100;
intd = a * b / c;
•Tohandlethiskindofproblem,Javaautomaticallypromoteseachbyte,short,orchar
operandtointwhenevaluatinganexpression.
•Asusefulastheautomaticpromotionsare,theycancauseconfusingcompile-timeerrors.
Forexample,thisseeminglycorrectcodecausesaproblem:
byte b = 50;
b = b * 2; // Error! Cannot assign an intto a byte!
byte b = 50;
b = (byte)(b * 2);
which yields the correct value of 100.

Type Conversion and Casting:...
Casting Incompatible Types -Narrowing Conversion…

Type Conversion and Casting:...
The Type Promotion Rules
•Javadefinesseveraltypepromotionrulesthatapplytoexpressions.
•Theyareasfollows:First,allbyte,short,andcharvaluesarepromotedtoint,as
justdescribed.Then,ifoneoperandisalong,thewholeexpressionispromotedto
long.Ifoneoperandisafloat,theentireexpressionispromotedtofloat.Ifanyof
theoperandsisdouble,theresultisdouble.

Operators and Expressions:
•Javaprovidesarichoperatorenvironment.Mostofits
operatorscanbedividedintothefollowingfourgroups:
arithmetic,bitwise,relational,andlogical.
Classification of Operators
(1) Arithmetic Operators
(2) Relational Operators
(3) Logical Operators
(4) Assignment Operators
(5) Increments and Decrement Operators
(6) Conditional Operators
(7) Bitwise Operators
(8) Special Operators

Operators and Expressions:...
•ArithmeticOperators:
TheBasicArithmeticOperators:addition,
subtraction,multiplication,anddivision
TheModulusOperator:Itcanbeapplied
tofloating-pointtypesaswellasinteger
types.
ArithmeticCompound Assignment
Operators:Usedtocombineanarithmetic
operationwithanassignment.
var=varopexpression;canbe
writtenasvarop=expression;
Increment and Decrement: ++ and --

Operators and Expressions:...
•The Bitwise Operators: Java defines several bitwise operators that can
be applied to the integer types, long, int, short, char, and byte. These operators act
upon the individual bits of their operands.
TheBitwiseLogicalOperators:&,|,^,and~
TheBitShift:<<,>>,>>>
value<<num,value>>num,
BitwiseOperatorCompoundAssignments:
a = a >> 4;
a >>= 4;

Operators and Expressions:...
•The Bitwise Operators: The Unsigned Right Shift
TheUnsignedRightShift/ShiftRightZeroFill:
Alwaysshiftszerosintothehigh-orderbit.For
example,ifyouareshiftingsomethingthatdoes
notrepresentanumericvalue,youmaynotwant
signextensiontotakeplace.Thissituationis
commonwhenyouareworkingwithpixel-based
valuesandgraphics.Inthesecases,youwill
generallywanttoshiftazerointothehigh-order
bitnomatterwhatitsinitialvaluewas.
value >>> num
TheLeftShift:Foreachshiftleft,the
high-orderbitisshiftedout(andlost),and
azeroisbroughtinontheright.,multiply
by2.
value << num
TheRightShift:Causesthetwolow-order
bitstobelost,divideby2.
value >> num
int a = -1;
a = a >>> 24;
Here is the same operation in binary form to further illustrate what is happening:
11111111 11111111 11111111 11111111 –1 in binary as an int
>>>24
00000000 00000000 00000000 11111111 255 in binary as an int

Operators and Expressions:...
RelationalOperators:Theoutcomeoftheseoperationsisaboolean
value.AnytypeinJava,includingintegers,floating-pointnumbers,
characters,andBooleanscanbecomparedusingtheequalitytest,==,
andtheinequalitytest,!=.Onlyinteger,floating-point,andcharacter
operandscomparedtoseewhichisgreaterorlessthantheother.
Eg:
int a = 4;
int b = 1;
boolean c = a < b;

Operators and Expressions:...
•Boolean Logical Operators: operate only on booleanoperands.

Operators and Expressions:...
•Short-CircuitLogicalOperators:&&and||
secondaryversionsoftheBooleanANDandOR
operators(&and|).
•The Assignment Operator:
var= expression;
•The?Operator:Javaincludesaspecialternary(three-
way)operatorthatcanreplacecertaintypesofif-then-else
statements.expression1?expression2:expression3
Eg:ratio = denom== 0 ? 0 : num / denom;

Operator Precedence:

Access specifiers:
•Encapsulationlinksdatawiththecodethatmanipulatesit.
However,itprovidesanotherimportantattribute:access
control.
•Throughencapsulation,youcancontrolwhatpartsofa
programcanaccessthemembersofaclass.Bycontrolling
access,youcanpreventmisuse.
•Eg:Allowingaccesstodataonlythroughawelldefinedsetofmethods,youcan
preventthemisuseofthatdata.
•Howamembercanbeaccessedisdeterminedbythe
accessspecifierthatmodifiesitsdeclaration.Javasupplies
arichsetofaccessspecifiers.

Access specifiers: ...
•Java’saccessspecifiersarepublic,private,protectedand
default.
•public:Membercanbeaccessedbyanyothercode.
•private:Membercanonlybeaccessedbyothermembers
ofitsclass.
•protected:Appliesonlywheninheritanceisinvolved.
•Whennoaccessspecifierisused,thenbydefaultthememberofa
classispublicwithinitsownpackage,butcannotbeaccessed
outsideofitspackage.

ControlStatements&Loops:
•ProgramminglanguageusescontrolstatementstoCause
theflowofexecutiontoadvanceandbranchbasedon
changestothestateofaprogram.
Three Categories
•Selection:Allowsprogramtochoosedifferentpathsof
executionbasedupontheoutcomeofanexpressionorthe
stateofavariable.Eg:ifandswitch
•Iteration:Enablesprogramexecutiontorepeatoneor
morestatements(formloops).Eg:for,whileanddo-while
•Jump:Allowsprogramtoexecuteinanonlinearfashion.
Eg:break,continue,andreturn.

Java’sSelectionStatements:
•Theifstatement:Java’sconditionalbranchstatement.Itcanbeused
torouteprogramexecutionthroughtwodifferentpaths.
•Thegeneralform:if(condition)statement1;
elsestatement2;
•Here,eachstatementmaybeasinglestatementoracompoundstatementenclosedincurly
braces(thatis,ablock).Theconditionisanyexpressionthatreturnsabooleanvalue.The
elseclauseisoptional.
int a, b;
// ...
if(a < b) a = 0;
else b = 0;
boolean dataAvailable;
// ...
if (dataAvailable)
ProcessData();
else
waitForMoreData();
int bytesAvailable;
// ...
if (bytesAvailable > 0) {
ProcessData();
bytesAvailable -= n;
} else
waitForMoreData();

Java’sSelectionStatements:...
•Nestedifs:Anestedifisanifstatementthatisthetargetof
anotheriforelse.Themainthingtorememberisthatan
elsestatementalwaysreferstothenearestifstatementthat
iswithinthesameblockastheelseandthatisnotalready
associatedwithanelse.
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)

Java’sSelectionStatements:...
•The if-else-if Ladder: A common programming construct
that is based upon a sequence of nested ifs is the if-else-if
ladder.
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;

Java’sSelectionStatements:...
•switch:Java’smultiwaybranchstatement,providesaneasywaytodispatchexecution
todifferentpartsofyourcodebasedonthevalueofanexpression,providesabetter
alternativethanalargeseriesofif-else-ifstatements.
•Thegeneralform:
Theexpressionmustbeoftypebyte,short,
int,orchar;eachofthevaluesspecifiedin
thecasestatementsmustbeofatype
compatiblewiththeexpression.(An
enumerationvaluecanalsobeusedtocontrol
aswitchstatement.Eachcasevaluemustbea
uniqueliteral(thatis,itmustbeaconstant,
notavariable).Duplicatecasevaluesarenot
allowed.thedefaultstatementisoptional.If
nocasematchesandnodefaultispresent,
thennofurtheractionistaken.

Java’sSelectionStatements:...
•switch:...

Java’sSelectionStatements:...
•switch:... Youcanuseaswitchaspartofthe
statementsequenceofanouterswitch.
Thisiscalledanestedswitch.Sincea
switchstatementdefinesitsownblock,
noconflictsarisebetweenthecase
constantsintheinnerswitchandthose
intheouterswitch.

Java’sIterationStatements:for,while,anddo-while,these
statementscreateloops.Alooprepeatedlyexecutesthesamesetof
instructionsuntilaterminationconditionismet.
while do-while for
while(condition) {
// body of loop
}
TheconditioncanbeanyBooleanexpression.Thebodyoftheloopwill
beexecutedaslongastheconditionalexpressionistrue.Whencondition
becomesfalse,controlpassestothenextlineofcodeimmediately
followingtheloop.Thecurlybracesareunnecessaryifonlyasingle
statementisbeingrepeated.Thebodyofthewhile(oranyotherofJava’s
loops)canbeempty.Thisisbecauseanullstatement(onethatconsists
onlyofasemicolon)issyntacticallyvalidinJava.
do {
// body of loop
} while (condition);
for(initialization; condition; iteration) {
// body
}

Java’sIterationStatements:...

Java’sIterationStatements:...for
•BeginningwithJDK5,therearetwoformsoftheforloop.Thefirstisthe
traditionalformthathasbeeninusesincetheoriginalversionofJava.Thesecondis
thenew“for-each”form.
•DeclaringLoopControlVariablesInsidetheforLoop:
for(intn=10; n>0; n--)
•UsingtheComma:
for(a=1, b=4; a<b; a++, b--)
•Some for Loop Variations:
booleandone = false;
for(inti=1; !done; i++) {
// ...
if(interrupted()) done = true;
}

Java’sIterationStatements:...for...
•Some for Loop Variations:...
booleandone = false;
for(inti=1; !done; i++) {
// ...
if(interrupted()) done = true;
}
// Parts of the for loop can be empty.
for( ; !done; )
for( ; ; ) {
// ...
}

Java’sIterationStatements:...for...
•The For-Each Version of the for Loop:
BeginningwithJDK5,asecondformofforwasdefinedthat
implementsa“for-each”styleloop.
•Aforeachstyleloopisdesignedtocyclethroughacollectionof
objects,suchasanarray,instrictlysequentialfashion,fromstartto
finish.Unlikesomelanguages,suchasC#,thatimplementafor-each
loopbyusingthekeywordforeach,Javaaddsthefor-eachcapability
byenhancingtheforstatement.
•Theadvantageofthisapproachisthatnonewkeywordisrequired,
andnopre-existingcodeisbroken.Thefor-eachstyleofforisalso
referredtoastheenhancedforloop.
•General form:
for(type itr-var: collection) statement-block

Java’sIterationStatements:...for...
•The For-Each Version of the for Loop:...Examples
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
intsum = 0;
for(int i=0; i < 10; i++) sum += nums[i];
Can be expressed as:
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
intsum = 0;
for(intx: nums) sum += x;
// Use break with a for-each style for.
class ForEach2 {
public static void main(String args[]) {
int sum = 0;
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// use for to display and sum the values
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
if(x == 5) break; // stop the loop when 5 is obtained
}
System.out.println("Summation of first 5 elements: " + sum);
}
}

Java’sIterationStatements:...for...
•The For-Each Version of the for Loop:...
•Iterating Over Multidimensional Arrays... Examples

Java’sIterationStatements:...for...
•The For-Each Version of the for Loop:...
•Applying the Enhanced for... Examples

Java’sIterationStatements:...for...
•The For-Each Version of the for Loop:...
•Nested Loops... Examples

Java’sJumpStatements:break,continue,andreturn.
•These statements transfer control to another part of your
program.
•Using break: Statement has three uses:
➢Terminates a statement sequence in a switch statement.
➢Used to exit a loop
➢Used as a “civilized” form of goto.
breakwasnotdesignedtoprovidethenormalmeansbywhicha
loopisterminated.Theloop’sconditionalexpressionservesthis
purpose.Thebreakstatementshouldbeusedtocancelalooponly
whensomesortofspecialsituationoccurs.

Java’sJumpStatements:...Usingbreak:...
•UsingbreaktoExitaLoop:forceimmediateterminationofaloop,bypassingthe
conditionalexpressionandanyremainingcodeinthebodyoftheloop.
•Using break as a form of goto: break label;
Javadoesnothaveagotostatementbecauseitprovidesawaytobranchinanarbitraryand
unstructuredmanner.Thisusuallymakesgoto-riddencodehardtounderstandandhardto
maintain.Italsoprohibitscertaincompileroptimizations.

Java’sJumpStatements:...
Usingcontinue:Causescontroltobetransferreddirectlytotheconditional
expressionthatcontrolstheloop.Sometimesitisusefultoforceanearlyiterationofa
loop.
Aswiththebreakstatement,continuemay
specifyalabeltodescribewhichenclosingloop
tocontinue.

Java’sJumpStatements:...Return
•Thelastcontrolstatementisreturn.Thereturnstatementisusedto
explicitlyreturnfromamethod.Thatis,itcausesprogramcontrolto
transferbacktothecallerofthemethod.

Arrays:
•Agroupoflike-typedvariablesthatarereferredtobya
commonname.
•Arraysofanytypecanbecreatedandmayhaveoneor
moredimensions.Aspecificelementinanarrayis
accessedbyitsindex.
•Arraysofferaconvenientmeansofgroupingrelated
information.
•Eg:
➢One-DimensionalArrays:Essentially,alistoflike-
typedvariables.
➢MultidimensionalArrays:Arraysofarrays.

One-DimensionalArrays:Alistoflike-typedvariables.
Tocreateanarray,youfirstmustcreateanarrayvariableof
thedesiredtype.
•General form: type var-name[ ];
•Eg:intmonth_days[];
month_daysisanarrayvariable,noarrayactuallyexists.Infact,thevalueof
month_daysissettonull,whichrepresentsanarraywithnovalue.
•To allocate memory for arrays, the general form:
array-var= new type[size]; or
type array-var[] = new type[size];
•Eg: month_days= new int[12];
•It is possible to combine the declaration of the array variable with the allocation of
the array itself, as shown here:intmonth_days[] = new int[12];

One-DimensionalArrays:...
// An improved version.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + "
days.");
}
}

MultidimensionalArrays:arraysofarrays
Eg: int twoD[][] = new int[4][5];
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

MultidimensionalArrays:...
Figure :A conceptual view of a 4 by 5, two-dimensional array

MultidimensionalArrays:...uneven/irregular
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
. . .
•Theuseofuneven(or,irregular)multidimensionalarraysmaynotbeappropriate
formanyapplications,becauseitrunscontrarytowhatpeopleexpecttofindwhen
amultidimensionalarrayisencountered.However,irregulararrayscanbeused
effectivelyinsomesituations.Forexample,ifyouneedaverylargetwo-
dimensionalarraythatissparselypopulated(thatis,oneinwhichnotallofthe
elementswillbeused),thenanirregulararraymightbeaperfectsolution.

•AlternativeArrayDeclarationSyntax:
type[ ] var-name;
intal[] = new int[3]; ORint[] a2 = new int[3];
char twod1[][] = new char[3][4];
OR
char[][] twod2 = new char[3][4];
int[] nums, nums2, nums3; // create three arrays
OR
intnums[], nums2[], nums3[]; // create three arrays
•Thealternativedeclarationformisalsousefulwhen
specifyinganarrayasareturntypeforamethod.

Introducing Classes
PreparedusingfollowingResources:
➢Herbert Schildt, “Java: The Complete Reference”,Tata McGrawHillEducation
➢E Balagurusamy, Programming with Java -ATata McGraw Hill Education
➢https://www.geeksforgeeks.org/java/
➢https://www.javatpoint.com/java-tutorial
➢https://www.tutorialspoint.com/java/index.htm
➢https://www.w3schools.com/java/
By: DIVAKARA .N

•ClassFundamentals
•Declaringobjects
•IntroducingMethods
•Constructors
•thiskeyword
•Useofobjectsasparameter&Methodsreturning
objects
•Callbyvalue&Callbyreference
•Staticvariables&methods
•Garbagecollection
•Nested&Innerclasses.

Class Fundamentals:
•ClassisthelogicalconstructuponwhichtheentireJava
languageisbuiltbecauseitdefinestheshapeandnatureof
anobject.Itdefinesanewdatatype.
•TheclassformsthebasisforOOPinJava.Anyconcept
youwishtoimplementinaJavaprogrammustbe
encapsulatedwithinaclass.
•Usedtocreateobjectsofthattype.Thus,aclassisa
templateforanobject,andanobjectisaninstanceofa
class.
•Thetwowordsobjectandinstanceusedinterchangeably.

Class Fundamentals: ...
•Whenyoudefineaclass,youdeclareitsexactform
andnature.Youdothisbyspecifyingthedatathat
itcontainsandthecodethatoperatesonthatdata.
Whileverysimpleclassesmaycontainonlycode
oronlydata,mostreal-worldclassescontainboth.
•Aclassisdeclaredbyuseoftheclasskeyword.

Class Fundamentals: ...A simplified general form
•Thedata,orvariables,definedwithina
classarecalledinstancevariables.The
codeiscontainedwithinmethods.
Collectively,themethodsandvariables
definedwithinaclassarecalled
membersoftheclass.Inmostclasses,
theinstancevariablesareactedupon
andaccessedbythemethodsdefined
forthatclass.
•Variablesdefinedwithinaclassare
calledinstancevariablesbecauseeach
instanceoftheclass(thatis,eachobject
oftheclass)containsitsowncopyof
thesevariables.Thus,thedataforone
objectisseparateanduniquefromthe
dataforanother.

Class Fundamentals: ...
NOTE:
•C++programmerswillnoticethattheclass
declarationandtheimplementationofthemethodsare
storedinthesameplaceandnotdefinedseparately.
Thissometimesmakesforverylarge.javafiles,since
anyclassmustbeentirelydefinedinasinglesource
file.
•ThisdesignfeaturewasbuiltintoJavabecauseitwas
feltthatinthelongrun,havingspecification,
declaration,andimplementationallinoneplace
makesforcodethatiseasiertomaintain.

Class Fundamentals: ... Introducing Access Control
•Java’saccessspecifiersare
public,private,andprotected.
Javaalsodefinesadefault
accesslevel.
•protectedappliesonlywhen
inheritanceisinvolved.

Class Fundamentals: ...
SimpleClass:...
class Box {
double width;
double height;
double depth;
}
Box mybox = new Box();
mybox.width = 100;

Class Fundamentals: ...
SimpleClass:...

Declaring objects:
•Obtainingobjectsofaclassisatwo-stepprocess.
➢Declareavariableoftheclasstype.Thisvariabledoesnotdefine
anobject.Instead,itissimplyavariablethatcanrefertoan
object.
➢Acquireanactual,physicalcopyoftheobjectandassignittothat
variable.(usingthenewoperator)
•Thenewoperatordynamicallyallocates(allocatesatruntime)memoryforanobjectand
returnsareferencetoit.Thisreferenceis,moreorless,theaddressinmemoryoftheobject
allocatedbynew.
•Thisreferenceisthenstoredinthevariable.Thus,inJava,allclassobjectsmustbe
dynamicallyallocated.
1.Box mybox; // declare reference to object
2.mybox= new Box(); // allocate a Box object
ClassNameObject_Name= newClassName(); OR
ClassNameclass-var= newClassName();
Box mybox= new Box();

Declaring objects: ...
A Closer Look atnew:operator dynamically allocates memory for an object.
General form: class-var= new classname( );
Note:Anobjectreferenceissimilartoamemorypointer.Themain
difference—andthekeytoJava’ssafety—isthatyoucannotmanipulate
referencesasyoucanactualpointers.Thus,youcannotcauseanobject
referencetopointtoanarbitrarymemorylocationormanipulateitlikeaninteger.

Declaring objects: ...
Assigning Object Reference Variables:
Box b1 = new Box();
Box b2 = b1;
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
REMEMBER Whenyouassignoneobjectreferencevariabletoanotherobject
referencevariable,youarenotcreatingacopyoftheobject,youareonlymakinga
copyofthereference.

Introducing Methods:
•Classes consist of two things: instance variables and methods.
General form:type name(parameter-list) {
// body of method
}
•Here,typespecifiesthetypeofdatareturnedbythemethod.Thiscanbeanyvalidtype,
includingclasstypesthatyoucreate.Ifthemethoddoesnotreturnavalue,itsreturn
typemustbevoid.Thenameofthemethodisspecifiedbyname.Thiscanbeanylegal
identifierotherthanthosealreadyusedbyotheritemswithinthecurrentscope.
•Theparameter-listisasequenceoftypeandidentifierpairsseparatedbycommas.
Parametersareessentiallyvariablesthatreceivethevalueoftheargumentspassedto
themethodwhenitiscalled.Ifthemethodhasnoparameters,thentheparameterlist
willbeempty.
•Methodsthathaveareturntypeotherthanvoidreturnavaluetothecallingroutine
usingthefollowingformofthereturnstatement:
return value;

Introducing Methods: ...
Adding a Method to the Box Class:

Introducing Methods:...
Returning a Value:
vol = mybox1.volume(); can be replaced by
System.out.println("Volume is " + mybox1.volume());

Introducing Methods: ...
•AddingaMethodThatTakesParameters:Parametersallowa
methodtobegeneralized.Aparameterizedmethodcanoperateona
varietyofdataand/orbeusedinanumberofslightlydifferentsituations.
Example:
int x, y;
x = square(5); // x equals 25
x = square(9); // x equals 81
y = 2;
x = square(y); // x equals 4

Introducing Methods: ...
•AddingaMethodThatTakesParameters:...
Note:Theconceptsofthemethodinvocation,
parameters,andreturnvaluesare
fundamentaltoJavaprogramming.

Introducing Methods: ... Recursion:
•Javasupportsrecursion.Recursionistheprocessofdefining
somethingintermsofitself.AsitrelatestoJavaprogramming,
recursionistheattributethatallowsamethodtocallitself.Amethod
thatcallsitselfissaidtoberecursive.

Introducing Methods: ... Overloading
•InJavaitispossibletodefinetwoormoremethodswithinthe
sameclassthatsharethesamename,aslongastheirparameter
declarationsaredifferent.
•Method overloading is one of the ways that Java supports
polymorphism.
•MethodoverloadingisoneofJava’smostexcitinganduseful
features.
•Javausesthetypeand/ornumberofargumentsasitsguideto
determinewhichversionoftheoverloadedmethodtoactually
call.Thus,overloadedmethodsmustdifferinthetypeand/or
numberoftheirparameters.

Introducing Methods: ... Overloading ...
classCalculation{
voidsum(inta,intb){
System.out.println(a+b);
}
voidsum(inta,intb,intc){
System.out.println(a+b+c);
}
publicstaticvoidmain(Stringargs[]){
Calculationobj=newCalculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
MethodOverloadingbychangingtheno.of
arguments

Introducing Methods: ... Overloading ...
MethodOverloadingbychangingdatatype
ofargument
classCalculation2{
voidsum(inta, intb){
System.out.println(a + b);
}
voidsum(doublea, doubleb){
System.out.println(a + b);
}
publicstaticvoidmain(Stringargs[]){
Calculation2obj = newCalculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}

Introducing Methods: ... Overloading ...
Method/ConstructorOverloadingby
changingnumberofargument

Introducing Methods: ... Overloading ...
Can we overload main() method?

Introducing Methods: ... Overloading ...
Method Overloading and Type Promotion: One type is promoted to
another implicitly if no matching datatypeis found.
bytecanbepromotedtoshort,
int,long,floatordouble.The
shortdatatypecanbe
promotedtoint,long,floator
double.Thechardatatypecan
bepromotedtoint,long,float
ordoubleandsoon.

Introducing Methods: ... Overloading ...
Method Overloading and Type Promotion:...

Introducing Methods: ... Overloading ...

Constructors:
•Itcanbetedioustoinitializeallofthevariablesinaclasseachtimean
instanceiscreated.Itwouldbesimplerandmoreconcisetohaveallofthe
setupdoneatthetimetheobjectisfirstcreated.Becausetherequirement
forinitializationissocommon,Javaallowsobjectstoinitializethemselves
whentheyarecreated.Thisautomaticinitializationisperformedthrough
theuseofaconstructor.
•Aconstructorinitializesanobjectimmediatelyuponcreation.Ithasthesamename
astheclassinwhichitresidesandissyntacticallysimilartoamethod.Once
defined,theconstructorisautomaticallycalledimmediatelyaftertheobjectis
created,beforethenewoperatorcompletes.Constructorslookalittle
strangebecausetheyhavenoreturntype,notevenvoid.

Constructors: ...
class-var= new classname( );
Box mybox1 = new Box();
•Whenyoudonotexplicitly
defineaconstructorforaclass,
thenJavacreatesadefault
constructorfortheclass.
•The defaultconstructor
automaticallyinitializesall
instancevariablestozero.
•Onceyoudefineyourown
constructor,thedefault
constructorisnolongerused.

Constructors: ...Parameterized Constructors

Constructors: ...Overloaded Constructors

Constructors: ...Overloaded Methods...

Constructors: ...Overloaded Constructors...
Java’s Copy Constructor

Use of objects as parameter &Methods returning objects
•Sofar,wehaveonlybeenusingsimpletypesasparametersto
methods.However,itisbothcorrectandcommontopassobjectsto
methods.

Use of objects as parameter &Methods returning objects
•Oneofthemostcommonusesofobjectparameters
involvesconstructors.
•Frequently,youwillwanttoconstructanewobjectsothat
itisinitiallythesameassomeexistingobject.
•Example….

Use of objects as parameter &Methods returning objects

Use of objects as parameter &Methods returning objects
•ReturningObjects:Amethodcanreturnanytypeofdata,including
classtypesthatyoucreate.

Callbyvalue&Callbyreference:
A Closer Look at Argument Passing
•In general, there are two ways that a computer language can pass an
argument to a subroutine: call-by-value and call-by-reference.
•call-by-value:Copiesthevalueofanargumentintothe
formalparameterofthesubroutine.Therefore,changesmadetothe
parameterofthesubroutinehavenoeffectontheargument.
•call-by-reference:areferencetoanargument(notthevalueofthe
argument)ispassedtotheparameter.Insidethesubroutine,this
referenceisusedtoaccesstheactualargumentspecifiedinthecall.
Thismeansthatchangesmadetotheparameterwillaffectthe
argumentusedtocallthesubroutine.
REMEMBER Whenaprimitivetypeispassedtoamethod,itisdonebyuse
ofcall-by-value.Objectsareimplicitlypassedbyuseofcall-by-reference.

Callbyvalue&Callbyreference:...
A Closer Look at Argument Passing ...
•InJava,whenyoupassaprimitivetypetoamethod,itispassedbyvalue.Thus,
whatoccurstotheparameterthatreceivestheargumenthasnoeffectoutsidethe
method.

Callbyvalue&Callbyreference:...
A Closer Look at Argument Passing ...
•The objects are passed to methods by use of call-by-reference. Changes to the
object inside the method do affect the object used as an argument.

thiskeyword:
•Sometimesamethodwillneedtorefertotheobjectthatinvokedit.
•thiscanbeusedinsideanymethodtorefertothecurrentobject.That
is,thisisalwaysareferencetotheobjectonwhichthemethodwas
invoked.Youcanusethisanywhereareferencetoanobjectofthe
currentclass’typeispermitted.
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
Instance Variable Hiding

thiskeyword: ...
Awordofcaution:Theuseofthisinsuchacontextcan
sometimesbeconfusing,andsomeprogrammersarecareful
nottouselocalvariablesandformalparameternamesthat
hideinstancevariables.Ofcourse,otherprogrammersbelieve
thecontrary—thatitisagoodconventiontousethesame
namesforclarity,andusethistoovercometheinstance
variablehiding.Itisamatteroftastewhichapproachyou
adopt.

Varargs:Variable-LengthArguments:
•BeginningwithJDK5,Javahasincludedafeaturethatsimplifiesthe
creationofmethodsthatneedtotakeavariablenumberof
arguments.Thisfeatureiscalledvarargsanditisshortforvariable-
lengtharguments.
•Amethodthattakesavariablenumberofargumentsiscalleda
variable-aritymethod,orsimplyavarargsmethod.
•Situationsthatrequirethatavariablenumberofargumentsbepassed
toamethodarenotunusual.
•Forexample,amethodthatopensanInternetconnectionmighttakea
username,password,filename,protocol,andsoon,butsupply
defaultsifsomeofthisinformationisnotprovided.

Varargs:Variable-LengthArguments:...

Varargs:Variable-LengthArguments:...
•Avariable-length argument is specified by three periods (...)
•Eg: vaTest( ) is written using avararg: static void vaTest(int... v) {

Varargs:Variable-LengthArguments:...
•Amethodcanhave“normal”parametersalongwitha
variable-lengthparameter.However,thevariable-length
parametermustbethelastparameterdeclaredbythe
method.
•Eg:Thismethoddeclarationisperfectlyacceptable:
intdoIt(inta, intb, double c, int... vals) {
•Remember, the varargsparameter must be last.
•For example, the following declaration is incorrect:
intdoIt(inta, intb, double c, int... vals, booleanstopFlag) { // Error!
intdoIt(inta, intb, double c, int... vals, double ... morevals) { // Error!

Varargs:Variable-LengthArguments:...

StaticVariables&Methods:
Understanding static
•Normally,aclassmembermustbeaccessedonlyinconjunctionwith
anobjectofitsclass.However,itispossibletocreateamemberthat
canbeusedbyitself,withoutreferencetoaspecificinstance.
•Tocreatesuchamember,precedeitsdeclarationwiththekeyword
static.Whenamemberisdeclaredstatic,itcanbeaccessedbefore
anyobjectsofitsclassarecreated,andwithoutreferencetoany
object.
•Instancevariablesdeclaredasstaticare,essentially,globalvariables.
Whenobjectsofitsclassaredeclared,nocopyofastaticvariableis
made.Instead,allinstancesoftheclasssharethesamestatic
variable.

StaticVariables&Methods:...
Understanding static...
•Methodsdeclaredasstatichaveseveralrestrictions:
➢Theycanonlycallotherstaticmethods.
➢Theymustonlyaccessstaticdata.
➢Theycannotrefertothisorsuperinanyway.(Thekeyword
superrelatestoinheritance)
•Ifyouneedtodocomputationinordertoinitializeyourstatic
variables,youcandeclareastaticblockthatgetsexecutedexactly
once,whentheclassisfirstloaded.

StaticVariables&Methods:...
Understanding static...

StaticVariables&Methods:...
Understanding static...
•Outsideoftheclassinwhichtheyaredefined,staticmethodsand
variablescanbeusedindependentlyofanyobject.
classname.method( )

Introducingfinal:
•Avariablecanbedeclaredasfinal.itpreventsitscontentsfrom
beingmodified.Thismeansthatyoumustinitializeafinalvariable
whenitisdeclared.
•Forexample:
final intFILE_NEW = 1;
final intFILE_OPEN = 2;
final intFILE_SAVE = 3;
final intFILE_SAVEAS = 4;
final intFILE_QUIT = 5;
•It is a common coding convention to choose all uppercase identifiers
for final variables.
•Variables declared as final do not occupy memory on a per-instance
basis. Thus, afinal variable is essentially a constant.

Garbagecollection:
•Sinceobjectsaredynamicallyallocatedbyusingthenewoperator,
youmightbewonderinghowsuchobjectsaredestroyedandtheir
memoryreleasedforlaterreallocation.Thetechniquethat
accomplishesthisiscalledgarbagecollection.
•Itworkslikethis:whennoreferencestoanobjectexist,thatobject
isassumedtobenolongerneeded,andthememoryoccupiedbythe
objectcanbereclaimed.
•Garbagecollectiononlyoccurssporadically(ifatall)duringthe
executionofyourprogram.Itwillnotoccursimplybecauseoneor
moreobjectsexistthatarenolongerused.

Garbagecollection:...
Thefinalize()Method:
•Sometimesanobjectwillneedtoperformsomeactionwhenitis
destroyed.
•Forexample,ifanobjectisholdingsomenon-Javaresourcesuchas
afilehandleorcharacterfont,thenyoumightwanttomakesure
theseresourcesarefreedbeforeanobjectisdestroyed.
•Javaprovidesamechanismcalledfinalization.Byusingfinalization,
youcandefinespecificactionsthatwilloccurwhenanobjectisjust
abouttobereclaimedbythegarbagecollector.

Garbagecollection:...
Thefinalize()Method:...
•Toaddafinalizertoaclass,yousimplydefinethefinalize()method.
TheJavaruntimecallsthatmethodwheneveritisabouttorecycle
anobjectofthatclass.Insidethefinalize()method,youwillspecify
thoseactionsthatmustbeperformedbeforeanobjectisdestroyed.
•Thegarbagecollectorrunsperiodically,checkingforobjectsthatare
nolongerreferencedbyanyrunningstateorindirectlythroughother
referencedobjects.Rightbeforeanassetisfreed,theJavaruntime
callsthefinalize()methodontheobject.
The finalize( ) method has this general form:
protected void finalize( ) {
// finalization code here
}

Garbagecollection:...
Thefinalize()Method:...
•Itisimportanttounderstandthatfinalize()isonlycalled
justpriortogarbagecollection.
•Itisnotcalledwhenanobjectgoesout-of-scope.This
meansthatyoucannotknowwhen—orevenif—finalize()
willbeexecuted.
•Therefore,yourprogramshouldprovideothermeansof
releasingsystemresources,etc.,usedbytheobject.Itmust
notrelyonfinalize()fornormalprogramoperation.

Nested&Innerclasses:
•Itispossibletodefineaclasswithinanotherclass;suchclassesare
knownasnestedclasses.
•Thescopeofanestedclassisboundedbythescopeofitsenclosing
class.
•Eg:IfclassBisdefinedwithinclassA,thenBdoesnotexist
independentlyofA.
•Anestedclasshasaccesstothemembers,includingprivate
members,oftheclassinwhichitisnested.However,theenclosing
classdoesnothaveaccesstothemembersofthenestedclass.
•Anestedclassthatisdeclareddirectlywithinitsenclosingclass
scopeisamemberofitsenclosingclass.Itisalsopossibletodeclare
anestedclassthatislocaltoablock.

Nested&Innerclasses:...
There are two types of nested classes: static and non-static
•Static:Astaticnestedclassisonethathasthestaticmodifier
applied.Becauseitisstatic,itmustaccessthemembersofits
enclosingclassthroughanobject.Thatis,itcannotrefertomembers
ofitsenclosingclassdirectly.Becauseofthisrestriction,staticnested
classesareseldomused.
•Non-static:Themostimportanttypeofnestedclassisthe
innerclass.Aninnerclassisanon-staticnestedclass.It
hasaccesstoallofthevariablesandmethodsofitsouter
classandmayrefertothemdirectlyinthesamewaythat
othernon-staticmembersoftheouterclassdo.

Nested & Inner classes: ... Inner/Non-Static classes

Nested & Inner classes: ... Inner/Non-Static classes...

Nested & Inner classes: ... Inner/Non-Static classes...
While nested classes are not applicable to all situations, they are particularly helpful
when handling events.
One final point: Nested classes were not allowed by the original 1.0 specification for Java. They were added by Java 1.1

The Stack class: An example...

The Stack class: An example...Modified

String Handling
PreparedusingfollowingResources:
➢Herbert Schildt, “Java: The Complete Reference”,Tata McGrawHillEducation
➢E Balagurusamy, Programming with Java -ATata McGraw Hill Education
➢https://www.geeksforgeeks.org/java/
➢https://www.javatpoint.com/java-tutorial
➢https://www.tutorialspoint.com/java/index.htm
➢https://www.w3schools.com/java/
By: DIVAKARA .N

•TheStringConstructors
•StringLength
•SpecialStringOperations
•CharacterExtraction
•StringComparison
•SearchingStrings
•ModifyingStrings
•StringBuffer
•conceptofmutableandimmutablestring
•Commandlineargumentsand
•basicsofI/Ooperations–keyboardinputusing
BufferedReader&Scannerclasses.

A Few Words About Strings –A brief overview:
•String,isnotasimpletype.Norisitsimplyanarrayofcharacters.
Rather,Stringdefinesanobject.
•TheStringtypeisusedtodeclarestringvariables.Youcanalso
declarearraysofstrings.
•AquotedstringconstantcanbeassignedtoaStringvariable.
•AvariableoftypeStringcanbeassignedtoanothervariableoftype
String.YoucanuseanobjectoftypeStringasanargumentto
println().
String str= "this is a test";
System.out.println(str);
•Here,strisanobjectoftypeString.Itisassignedthestring“thisisa
test”.Thisstringisdisplayedbytheprintln()statement.
•Stringobjectshavemanyspecialfeaturesandattributesthatmake
themquitepowerfulandeasytouse.

Overview:
•Asisthecaseinmostotherprogramminglanguages,in
Javaastringisasequenceofcharacters.But,unlikemany
otherlanguagesthatimplementstringsascharacter
arrays,JavaimplementsstringsasobjectsoftypeString.
•Implementingstringsasbuilt-inobjectsallowsJavato
provideafullcomplementoffeaturesthatmakestring
handlingconvenient.
•Forexample,Javahasmethodstocomparetwostrings,
searchforasubstring,concatenatetwostrings,andchange
thecaseofletterswithinastring.

Overview:...
•OnceaStringobjecthasbeencreated,youcannotchange
thecharactersthatcomprisethatstring.Youcanstill
performalltypesofstringoperations.
•Eachtimeyouneedanalteredversionofanexistingstring,
anewStringobjectiscreatedthatcontainsthe
modifications.Theoriginalstringisleft
unchanged(Immutable).
•Immutablestringscanbeimplementedmoreefficiently
thanchangeableones(Mutable).
•Javaprovidestwooptions:StringBufferand
StringBuilder.Bothholdstringsthatcanbemodifiedafter
theyarecreated.

Overview:...
•TheString,StringBuffer,andStringBuilderclassesare
definedinjava.lang,theyareavailabletoallprograms
automatically.Allaredeclaredfinal,(noneoftheseclasses
maybesub-classed)
•Onelastpoint:ThestringswithinobjectsoftypeString
areunchangeablemeansthatthecontentsoftheString
instancecannotbechangedafterithasbeencreated.
However,avariabledeclaredasaStringreferencecanbe
changedtopointatsomeotherStringobjectatanytime.

Overview:...
•Stringisasequenceofcharacters.
•JavaimplementsstringsasobjectsoftypeString.
•Itbelongstojava.lang(java.lang.String)
•OnceaStringobjectiscreated,itisnotpossibletochange
thecharactersthatcomprisethestring.
•Whenamodifiablestringisneeded,javaprovidestwo
options:
➢ java.lang.StringBuffer
➢ java.lang.StringBuilder

Overview:...
classSimple{
publicstaticvoidmain(Stringargs[]){
Strings = "SJCE";
s.concat("MYSORE");
// s = s.concat("MYSORE");
System.out.println(s);
}
}
Why string objects are immutable in java?
Becausejavausestheconceptofstringliteral.Supposethereare5
referencevariables,allreferstooneobject"SJCE".Ifonereference
variablechangesthevalueoftheobject,itwillbeaffectedtoallthe
referencevariables.Thatiswhystringobjectsareimmutableinjava.

TheStringConstructors:
•TheStringclasssupportsseveralconstructors.
•TocreateanemptyString,youcallthedefaultconstructor.
Eg: String s = new String(); //instance with no characters
•Tocreatestringsthathaveinitialvaluesbyanarrayof
characters,String(charchars[])
Eg:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
•Specifyasub-rangeofacharacterarrayasaninitializer
using,String(charchars[],intstartIndex,intnumChars)

TheStringConstructors:...
•specifyasub-range...
Eg:charchars[]={'a','b','c','d','e','f'};
String s = new String(chars, 2, 3);
•ToconstructaStringobjectthatcontainsthesamecharacter
sequenceasanotherStringobjectusing,String(StringstrObj)
// Construct one String from another.
class MakeString{
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}

TheStringConstructors:...
•EventhoughJava’schartypeuses16bitstorepresentthe
basicUnicodecharacterset,thetypicalformatforstrings
ontheInternetusesarraysof8-bitbytesconstructedfrom
theASCIIcharacterset.
•Because8-bitASCIIstringsarecommon,theStringclass
providesconstructorsthatinitializeastringwhengivena
bytearray.Theirformsareshownhere:
String(byte asciiChars[ ])
String(byte asciiChars[ ], intstartIndex, intnumChars)
•Here,asciiCharsspecifiesthearrayofbytes.Thesecondformallows
youtospecifyasub-range.
•Ineachoftheseconstructors,thebyte-to-characterconversionis
donebyusingthedefaultcharacterencodingoftheplatform.

TheStringConstructors:...
•8-bitASCIIstrings....
// Construct string from subset of char array.
class SubStringCons{
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
NOTE:Thecontentsofthearrayarecopiedwheneveryoucreatea
Stringobjectfromanarray.Ifyoumodifythecontentsofthearrayafter
youhavecreatedthestring,theStringwillbeunchanged.
YoucanconstructaStringfromaStringBufferbyusingthe
constructor,String(StringBufferstrBufObj)

TheStringConstructors:...
•TocreateanemptyString,youcallthedefaultconstructor,String();
String s = new String();
•Tocreatestringsthathaveinitialvaluesbyanarrayofcharacters,
String(charchars[])
•Tospecifyasub-rangeofacharacterarrayasaninitializerusing,
String(charchars[],intstartIndex,intnumChars)
•ToconstructaStringobjectthatcontainsthesamecharactersequenceas
anotherStringobjectusing,
String(StringstrObj)
•TheStringclassprovidesconstructorsthatinitializeastringwhengivenabytearray.Their
formsareshownhere:String(byteasciiChars[])
String(byte asciiChars[ ], intstartIndex, intnumChars)
•ToconstructaStringfromaStringBufferbyusingtheconstructor,
String(StringBufferstrBufObj)

StringLength:
•Thelengthofastringisthenumberofcharactersthatit
contains.
•Toobtainthisvalue,callthelength()method,shownhere:
intlength( )
Eg:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length()); // What is the Size?

SpecialStringOperations:
•Becausestringsareacommonandimportantpartof
programming,Javahasaddedspecialsupportforseveral
stringoperationswithinthesyntaxofthelanguage.
•OperationsincludetheautomaticcreationofnewString
instancesfromstringliterals,concatenationofmultiple
Stringobjectsbyuseofthe+operator,andtheconversion
ofotherdatatypestoastringrepresentation.
•Thereareexplicitmethodsavailabletoperformallofthese
functions,butJavadoesthemautomaticallyasa
conveniencefortheprogrammerandtoaddclarity.

SpecialStringOperations:...
StringLiterals:ExplicitlycreateaStringinstanceusinga
stringliteral.Thus,youcanuseastringliteraltoinitializea
Stringobject.
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc"; // use string literal
BecauseaStringobjectiscreatedforeverystringliteral,you
canuseastringliteralanyplaceyoucanuseaStringobject.
System.out.println("abc".length());

SpecialStringOperations:...
StringConcatenation:Ingeneral,Javadoesnot
allowoperatorstobeappliedtoStringobjects.The
oneexceptiontothisruleisthe+operator,which
concatenatestwostrings,producingaStringobjectas
theresult.Thisallowsyoutochaintogetheraseriesof
+operations.
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);

SpecialStringOperations:...
StringConcatenation:...
Onepracticaluseofstringconcatenationisfoundwhenyouarecreating
verylongstrings.Insteadoflettinglongstringswraparoundwithinyour
sourcecode,youcanbreakthemintosmallerpieces,usingthe+toconcatenate
them.

SpecialStringOperations:...
StringConcatenationwithotherDataTypes:
intage = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
•Thecompilerwillconvertanoperandtoitsstringequivalent
whenevertheotheroperandofthe+isaninstanceofString.
•Becarefulwhenyoumixothertypesofoperationswithstring
concatenationexpressions.
String s = "four: " + 2 + 2;
System.out.println(s); // Output: ...
String s = "four: " + (2 + 2); // Output: ...

SpecialStringOperations:...
StringConversionandtoString():
•WhenJavaconvertsdataintoitsstringrepresentationduring
concatenation,itdoessobycallingoneoftheoverloadedversionsof
thestringconversionmethodvalueOf()definedbyString.
•valueOf()isoverloadedforallthesimpletypesandfortypeObject.
•Forthesimpletypes,valueOf()returnsastringthat
containsthehuman-readableequivalentofthevaluewith
whichitiscalled.Forobjects,valueOf()callsthe
toString()methodontheobject.
•EveryclassimplementstoString()becauseitisdefinedbyObject.
•Formostimportantclassesthatyoucreate,youwillwanttooverride
toString()andprovideyourownstringrepresentations.
•ThetoString()methodhasthisgeneralform:StringtoString()

SpecialStringOperations:...
StringConversionandtoString():....
Box’stoString()methodisautomaticallyinvokedwhenaBoxobjectis
usedinaconcatenationexpressionorinacalltoprintln().

CharacterExtraction:
•TheStringclassprovidesanumberofwaysinwhich
characterscanbeextractedfromaStringobject.
•charAt():ToextractasinglecharacterfromaString,youcan
referdirectlytoanindividualcharacter.
char charAt(intwhere)
Eg: char ch; ch= “abc”.charAt(1); // b is extracted
•getChars( ): To extract more than one character at a time.
void getChars(intsourceStart, intsourceEnd,
char target[ ], inttargetStart)

CharacterExtraction:...
•getChars( ): ...
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end -start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
•getBytes( ) : Alternative to getChars( ) that stores the characters in an array of bytes. It
uses the default character-to-byte conversions provided by the platform.
byte[ ] getBytes( )
•mostusefulwhenyouareexportingaStringvalueintoanenvironmentthatdoesnotsupport
16-bitUnicodecharacters.Eg:MostInternetprotocolsandtextfileformatsuse8-bitASCII
foralltextinterchange.

CharacterExtraction:...
•toCharArray():ConvertsallthecharactersinaString
objectintoacharacterarray,itreturnsanarrayof
charactersfortheentirestring.char[]toCharArray()
•Thisfunctionisprovidedasaconvenience,sinceitis
possibletousegetChars()toachievethesameresult.

StringComparison:
•TheStringclassincludesseveralmethodsthatcompare
stringsorsubstringswithinstrings.
•equals()andequalsIgnoreCase():Tocomparetwo
stringsforequality.
➢equals()//case-sensitive
boolean equals(Object str)
➢equalsIgnoreCase()//ignorescasedifferences
boolean equalsIgnoreCase(String str)

StringComparison:...
•equals()andequalsIgnoreCase():...

StringComparison:...
•regionMatches():
➢ booleanregionMatches(intstartIndex, String str2,
intstr2StartIndex, intnumChars)
➢ booleanregionMatches(booleanignoreCase,
intstartIndex, String str2,
intstr2StartIndex, intnumChars)
•Forbothversions,startIndexspecifiestheindexatwhichtheregionbegins
withintheinvokingStringobject.TheStringbeingcomparedisspecified
bystr2.Theindexatwhichthecomparisonwillstartwithinstr2isspecified
bystr2StartIndex.Thelengthofthesubstringbeingcomparedispassedin
numChars.
•Inthesecondversion,ifignoreCaseistrue,thecaseofthecharacters
isignored.Otherwise,caseissignificant.

StringComparison:...
•startsWith()andendsWith():Specializedformsof
regionMatches().Thesemethodsdetermineswhetheragiven
Stringbegins/endswithaspecifiedstring.
boolean startsWith(String str)
boolean endsWith(String str)
boolean startsWith(String str, int startIndex)
Eg:
"Foobar".endsWith("bar")
"Foobar".startsWith("Foo")
"Foobar".startsWith("bar", 3)

StringComparison:...
equals( ) Versus==( )
•Theequals()methodcomparesthecharactersinsidea
Stringobject.
•The==operatorcomparestwoobjectreferencestosee
whethertheyrefertothesameinstance.

StringComparison:...
•compareTo():Itisnotenoughtosimplyknowwhether
twostringsareidentical.Forsortingapplications,youneed
toknowwhichislessthan,equalto,orgreaterthanthe
next.Astringislessthananotherifitcomesbeforethe
otherindictionaryorder.Astringisgreaterthananotherif
itcomesaftertheotherindictionaryorder.
intcompareTo(String str)

StringComparison:...
•compareTo():AnExmaple

SearchingStrings:
•TheStringclassprovidestwomethodsthatallow
youtosearchastringforaspecifiedcharacteror
substring:
oindexOf()Searchesforthefirstoccurrenceofa
characterorsubstring.
olastIndexOf()Searchesforthelastoccurrence
ofacharacterorsubstring.
•Thesetwomethodsareoverloadedinseveraldifferentways.
•Inallcases,themethodsreturntheindexatwhich
thecharacterorsubstringwasfound,or–1on
failure.

SearchingStrings:...
•Tosearchforthefirst/lastoccurrenceofacharacter,use
intindexOf(intch)
intlastIndexOf(intch)
•Tosearchforthefirst/lastoccurrenceofasubstring,use
intindexOf(Stringstr)
intlastIndexOf(Stringstr)
•Youcanspecifyastartingpointforthesearchusing
intindexOf(intch, intstartIndex)
intlastIndexOf(intch, intstartIndex)
intindexOf(String str, intstartIndex)
intlastIndexOf(String str, intstartIndex)
•Here,startIndexspecifiestheindexatwhichpointthesearchbegins.ForindexOf(),
thesearchrunsfromstartIndextotheendofthestring.ForlastIndexOf(),thesearch
runsfromstartIndextozero.

SearchingStrings:...AnExample

ModifyingStrings:
•BecauseStringobjectsareimmutable,wheneveryouwant
tomodifyaString,youmusteithercopyitintoa
StringBufferorStringBuilder,oruseoneofthefollowing
Stringmethods,Whichwillconstructanewcopyofthe
stringwithyourmodificationscomplete.
•substring():Toextractasubstringuse,substring().
•Ithastwoforms:
Stringsubstring(intstartIndex)
Stringsubstring(intstartIndex,intendIndex)
•Here,startIndexspecifiesthebeginningindex,andendIndex
specifiesthestoppingpoint.Thestringreturnedcontainsallthe
charactersfromthebeginningindex,upto,butnotincluding,the
endingindex.

ModifyingStrings:...Thefollowingprogramusessubstring()
toreplaceallinstancesofonesubstringwithanotherwithinastring:

ModifyingStrings:...
•concat():Toconcatenatetwostingsuse,Stringsubstring(),
performsthesamefunctionas+.
Eg:
String s1 = "one";
String s2 = s1.concat("two"); // String s2 = s1 + "two";
•replace( ):To replaces all occurrences of one character in the
invoking string with another character.
String replace(char original, char replacement)
Eg:Stringstr=“NEW".replace(‘E',‘O');
•Thesecondformofreplace()replacesonecharactersequencewith
another.Ithasthisgeneralform:
String replace(CharSequenceoriginal, CharSequencereplacement)
•ThisformwasaddedbyJ2SE5.

ModifyingStrings:...
•trim():returnsacopyoftheinvokingstringfromwhichany
leadingandtrailingwhitespacehasbeenremoved.
String trim( )
Eg:Strings="HelloWorld".trim();

StringBuffer:
•StringBufferisapeerclassofStringthatprovidesmuch
ofthefunctionalityofstrings.
•Stringrepresentsfixed-length,immutablecharacter
sequences.Incontrast,
•StringBufferrepresentsgrowableandwriteable
charactersequences.
•StringBuffermayhavecharactersandsubstringsinserted
inthemiddleorappendedtotheend.
•StringBufferwillautomaticallygrowtomakeroomfor
suchadditionsandoftenhasmorecharacterspre-allocated
thanareactuallyneeded,toallowroomforgrowth.

StringBuffer:...StringBufferConstructors
StringBufferdefines these four constructors:
•StringBuffer():Reservesroomfor16characterswithout
reallocation.
•StringBuffer(intsize):Acceptsanintegerargumentthat
explicitlysetsthesizeofthebuffer.
•StringBuffer(Stringstr):AcceptsaStringargumentthatsetsthe
initialcontentsoftheStringBufferobjectandreservesroomfor16
morecharacterswithoutreallocation.
•StringBuffer(CharSequencechars):Createsanobjectthat
containsthecharactersequencecontainedinchars.
•StringBufferallocatesroomfor16additionalcharacterswhennospecificbuffer
lengthisrequested,becausereallocationisacostlyprocessintermsoftime.Also,
frequentreallocationscanfragmentmemory.Byallocatingroomforafewextra
characters,StringBufferreducesthenumberofreallocationsthattakeplace.

StringBuffer:...
•length()andcapacity():Thecurrentlengthofa
StringBuffercanbefoundviathelength()method,while
thetotalallocatedcapacitycanbefoundthroughthe
capacity()method.intlength()
intcapacity( )
Sincesbisinitializedwiththestring“Hello”whenitiscreated,itslengthis5.Its
capacityis21becauseroomfor16additionalcharactersisautomaticallyadded.

StringBuffer:...Someusefulmethods
•charAt()andsetCharAt()
char charAt(int where)
void setCharAt(int where, char ch)
•getChars()
void getChars(int sourceStart, int sourceEnd,
char target[ ], int targetStart)
•append()
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)

StringBuffer:...Someusefulmethods
•insert()
StringBufferinsert(intindex, String str)
StringBufferinsert(intindex, char ch)
StringBufferinsert(intindex, Object obj)
•reverse():StringBufferreverse()
•delete()anddeleteCharAt()
StringBufferdelete(intstartIndex, intendIndex)
StringBufferdeleteCharAt(intloc)
•replace( ):
StringBufferreplace(intstartIndex, intendIndex, String str)
•replace( ): String substring(intstartIndex)
String substring(intstartIndex, intendIndex)

StringBuilder:
•J2SE5addsanewstringclasstoJava’salreadypowerful
stringhandlingcapabilities,calledStringBuilder.
•ItisidenticaltoStringBufferexceptforoneimportant
difference:itisnotsynchronized,whichmeansthatitis
notthread-safe.
•TheadvantageofStringBuilderisfasterperformance.
•However,incasesinwhichyouareusingmultithreading,
youmustuseStringBufferratherthanStringBuilder.

ConceptofMutableandImmutableString:
•Java'sStringisdesignedtobeimmutablei.e,once
aStringisconstructed,itscontentscannotbe
modified.
•TheStringswithinobjectsoftypeStringare
unchangeablemeansthecontentoftheString
instancecannotbechangesafterithasbeen
created.However,avariabledeclaredasaString
referencecanbechangedtopointatsomeother
Stringobjectatanytime.

ConceptofMutableandImmutableString:...
•TheStringBufferandStringBuilderclassesare
usedwhenthereisanecessitytomakealotof
modificationstoStringsofcharacters.(Mutable)
•TheString,StringBufferandStringBuilderclasses
aredefinedinjava.lang

Command-linearguments:
•Sometimesyouwillwanttopassinformationintoa
programwhenyourunit.Thisisaccomplishedbypassing
command-lineargumentstomain().
•Itistheinformationthatdirectlyfollowstheprogram’s
nameonthecommandlinewhenitisexecuted.
•Toaccessthecommand-lineargumentsinsideaJava
programisquiteeasy-theyarestoredasstringsina
Stringarraypassedtotheargsparameterofmain().The
firstcommand-lineargumentisstoredatargs[0],the
secondatargs[1],andsoon.
•REMEMBER Allcommand-lineargumentsarepassedasstrings.
Youmustconvertnumericvaluestotheirinternalformsmanually.

Command-linearguments:...Example
// Display all command-line arguments.
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}
javac CommandLine.java
java CommandLine this is a test 100 -1

BasicsofI/Ooperations:Keyboardinputusing
BufferedReaderclass
•InJava,consoleinputisaccomplishedbyreadingfromSystem.in.
Toobtainacharacter-basedstreamthatisattachedtotheconsole,
wrapSystem.ininaBufferedReaderobject.
•BufferedReadersupportsabufferedinputstream.Itsmost
commonlyusedconstructorisshownhere:
BufferedReader(Reader inputReader)
•Here,inputReaderisthestreamthatislinkedtotheinstanceof
BufferedReaderthatisbeingcreated.Readerisanabstractclass.
•OneofitsconcretesubclassesisInputStreamReader,which
convertsbytestocharacters.ToobtainanInputStreamReader
objectthatislinkedtoSystem.in,usethefollowingconstructor:
InputStreamReader(InputStreaminputStream)

BasicsofI/Ooperations:Keyboardinputusing
BufferedReaderclass...
•BecauseSystem.inreferstoanobjectoftypeInputStream,itcanbe
usedforinputStream.
•Puttingitalltogether,thefollowinglineofcodecreatesa
BufferedReaderthatisconnectedtothekeyboard:
BufferedReaderbr=newBufferedReader(new
InputStreamReader(System.in));
•Afterthisstatementexecutes,brisacharacter-basedstreamthatis
linkedtotheconsolethroughSystem.in.
•Reading Characters: To read a character from a BufferedReader,
use read( ). The version of read( ) that we will be using is
intread( ) throws IOException

BasicsofI/Ooperations:Keyboardinputusing
BufferedReaderclass...
intread( ) throws IOException...Example
// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead{
public static void main(String args[])
throws IOException
{
char c;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}

BasicsofI/Ooperations:Keyboardinputusing
BufferedReaderclass...
Declaration:publicclassBufferedReaderextendsReader
Class constructors
BufferedReader(Readerin):CreateanewBufferedReaderthat
willreadfromthespecifiedsubordinatestreamwithadefaultbuffersize
of8192chars.
BufferedReader(Readerin,intsize):Createanew
BufferedReaderthatwillreadfromthespecifiedsubordinatestreamwith
abuffersizethatisspecifiedbythecaller.

BasicsofI/Ooperations:Keyboardinputusing
BufferedReaderclass...

BasicsofI/Ooperations:
KeyboardinputusingScannerclass:
•ItisthecomplementofFormatter,readsformatted
inputandconvertsitintoitsbinaryform.
•Readalltypesofnumericvalues,strings,andother
typesofdata,whetheritcomesfromadiskfile,the
keyboard,oranothersource.
•Scannercanbeusedtoreadinputfromtheconsole,afile,
astring,oranysourcethatimplementstheReadable
interfaceorReadableByteChannel.

BasicsofI/Ooperations:
KeyboardinputusingScannerclass:...
The Scanner Constructors
•Scannerdefinestheconstructors,itcanbecreatedfora
String,anInputStream,aFile,oranyobjectthat
implementstheReadableorReadableByteChannel
interfaces.
•Eg:ThefollowingsequencecreatesaScannerthatreads
thefileTest.txt:
FileReaderfin = new FileReader("Test.txt");
Scanner src= new Scanner(fin);

BasicsofI/Ooperations:
KeyboardinputusingScannerclass:...
The Scanner Constructors...

BasicsofI/Ooperations:
KeyboardinputusingScannerclass:...
Scanning Basics
•OnceyouhavecreatedaScanner,itisasimplematterto
useittoreadformattedinput.Itreadstokensfromthe
underlyingsourcethatyouspecifiedwhentheScanner
wascreated.
•AsitrelatestoScanner,atokenisaportionofinputthatis
delineatedbyasetofdelimiters,whichiswhitespaceby
default.

BasicsofI/Ooperations:
KeyboardinputusingScannerclass:...
Scanning Basics...
In general, to use Scanner,follow this procedure:
1.Determineifaspecifictypeofinputisavailablebycallingoneof
Scanner’shasNextXmethods,whereXisthetypeofdatadesired.
2.Ifinputisavailable,readitbycallingoneofScanner’snextX
methods.
3.Repeattheprocessuntilinputisexhausted.
The following sequence shows how to read a list of integers from the keyboard.
Scanner conin= new Scanner(System.in);
inti;
// Read a list of integers.
while(conin.hasNextInt()) {
i= conin.nextInt();
// ...
}

BasicsofI/Ooperations:
KeyboardinputusingScannerclass:...
Scanning Basics...The Scanner hasNextMethods

BasicsofI/Ooperations:
Keyboardinputusing
Scannerclass:...
Scanning Basics...
The Scanner next
Methods

Inheritance
[Reusable Properties]
PreparedusingfollowingResources:
➢Herbert Schildt, “Java: The Complete Reference”,Tata McGrawHillEducation
➢E Balagurusamy, Programming with Java -ATata McGraw Hill Education
➢https://www.geeksforgeeks.org/java/
➢https://www.javatpoint.com/java-tutorial
➢https://www.tutorialspoint.com/java/index.htm
➢https://www.w3schools.com/java/
By: DIVAKARA .N

Reusable Properties
INHERITANCE:Superclass&subclassesincluding
multilevelhierarchy,processofconstructorcallingin
inheritance,useof‘super’and‘final’keywordswith
super()method,dynamicmethoddispatch,useof
abstractclasses&methods,Methodcallbinding,
Overridingvs.overloading,Abstractclassesand
methods,Constructorsandpolymorphism,Orderof
constructorcalls.

•Inheritanceisoneofthecornerstonesofobject-oriented
programmingbecauseitallowsthecreationofhierarchical
classifications.
•Usinginheritance,youcancreateageneralclassthat
definestraitscommontoasetofrelateditems.Thisclass
canthenbeinheritedbyother,morespecificclasses,each
addingthosethingsthatareuniquetoit.
•IntheterminologyofJava,aclassthatisinheritediscalled
asuperclass.Theclassthatdoestheinheritingiscalleda
subclass.
•Therefore,asubclassisaspecializedversionofa
superclass.Itinheritsalloftheinstancevariablesand
methodsdefinedbythesuperclassandaddsitsown,
uniqueelements.

•Inheritance Basics
•Toinheritaclass,yousimplyincorporatethedefinitionof
oneclassintoanotherbyusingtheextendskeyword.
•Thegeneralformofaclassdeclarationthatinheritsasuperclass:
classsubclass-nameextendssuperclass-name{
//bodyofclass
}
•Youcanonlyspecifyonesuperclassforanysubclassthatyoucreate.
Javadoesnotsupporttheinheritanceofmultiplesuperclassesintoa
singlesubclass.Youcan,asstated,createahierarchyofinheritance
inwhichasubclassbecomesasuperclassofanothersubclass.
However,noclasscanbeasuperclassofitself.

•Inheritance Basics ...

•Inheritance Basics ...
•MemberAccessandInheritance:Althoughasubclass
includesallofthemembersofitssuperclass,itcannot
accessthosemembersofthesuperclassthathavebeen
declaredasprivate.
REMEMBER Aclassmemberthathasbeendeclaredasprivatewill
remainprivatetoitsclass.Itisnotaccessiblebyanycodeoutsideits
class,includingsubclasses.

•Inheritance Basics ...More Practical Example

•Inheritance Basics ...More Practical Example
•Amajoradvantageofinheritanceisthatonceyouhavecreateda
superclassthatdefinestheattributescommontoasetofobjects,it
canbeusedtocreateanynumberofmorespecificsubclasses.Each
subclasscanpreciselytailoritsownclassification.Forexample,the
followingclassinheritsBoxandaddsacolorattribute:
•Remember:Onceyouhavecreatedasuperclassthatdefinesthegeneral
aspectsofanobject,thatsuperclasscanbeinheritedtoformspecialized
classes.Eachsubclasssimplyaddsitsownuniqueattributes.Thisisthe
essenceofinheritance.

•Inheritance Basics ...
•ASuperclassVariableCanReferenceaSubclassObject:
•Areferencevariableofasuperclasscanbeassigneda
referencetoanysubclassderivedfromthatsuperclass.
•Itisimportanttounderstandthatitisthetypeofthe
referencevariable—notthetypeoftheobjectthatitrefers
to—thatdetermineswhatmemberscanbeaccessed.That
is,whenareferencetoasubclassobjectisassignedtoa
superclassreferencevariable,youwillhaveaccessonlyto
thosepartsoftheobjectdefinedbythesuperclass,
becausethesuperclasshasnoknowledgeofwhata
subclassaddstoit.

•Inheritance Basics ...
•ASuperclassVariableCanReferenceaSubclassObject:...

•Using super
•Wheneverasubclassneedstorefertoits
immediatesuperclass,itcandosobyuseofthe
keywordsuper.
•superhastwogeneralforms.
oThefirstcallsthesuperclass’constructor.
oThesecondisusedtoaccessamemberofthe
superclassthathasbeenhiddenbyamemberof
asubclass.

•Using super ...
Using super to Call SuperclassConstructors
•A subclass can call a constructor defined by its superclass
by use of the following form of super:
super(arg-list);
•Here,arg-listspecifiesanyargumentsneededbytheconstructorinthesuperclass.
super()mustalwaysbethefirststatementexecutedinsideasubclass’constructor.

•Using super ...
Using super to Call SuperclassConstructors...
•Sinceconstructorscanbeoverloaded,super()canbecalledusinganyform
definedbythesuperclass.
•Theconstructorexecutedwillbetheonethatmatchesthearguments.

•Using super ...
Using super to Call SuperclassConstructors...

•Using super ...
Using super to Call SuperclassConstructors...

•Using super ...
Using super to Call SuperclassConstructors...
•Noticethatsuper()ispassedanobjectoftypeBoxWeight—notoftypeBox.Thisstill
invokestheconstructorBox(Boxob).Asmentionedearlier,asuperclassvariablecanbe
usedtoreferenceanyobjectderivedfromthatclass.
•Thus,weareabletopassaBoxWeightobjecttotheBoxconstructor.Ofcourse,Boxonly
hasknowledgeofitsownmembers.
•Whenasubclasscallssuper(),itiscallingtheconstructorofits
immediatesuperclass.Thus,super()alwaysreferstothesuperclass
immediatelyabovethecallingclass.
•Thisistrueeveninamultileveledhierarchy.Also,super()must
alwaysbethefirststatementexecutedinsideasubclassconstructor.

•Using super ...
A Second Use for super
•Acts somewhat like this, except that it always refers to the superclass
of the subclass in which it is used. This usage has the following
general form:
super.member
Here, member can be either a method or an instance variable.
•Thissecondformofsuperismostapplicabletosituationsinwhich
membernamesofasubclasshidemembersbythesamenameinthe
superclass.

•Using super ...
A Second Use for super ...
•Althoughtheinstance
variableiinBhidestheiin
A,superallowsaccessto
theidefinedinthe
superclass.
•Asyouwillsee,supercan
alsobeusedtocall
methodsthatarehiddenby
asubclass.

•Creating a Multilevel Hierarchy
•Buildshierarchiesthatcontainasmanylayersof
inheritance,usesasubclassasasuperclassofanother.

•Creating a Multilevel Hierarchy:...

•Creating a Multilevel Hierarchy:...

•Creating a Multilevel Hierarchy:...
Theentireclasshierarchy,includingBox,BoxWeight,andShipment,isshownallinonefile.In
Java,allthreeclassescouldhavebeenplacedintotheirownfilesandcompiledseparately.Infact,
usingseparatefilesisthenorm,nottheexception,increatingclasshierarchies.

•Inaclasshierarchy,constructorsarecalledinorder
ofderivation,fromsuperclasstosubclass.
•Further,sincesuper()mustbethefirststatement
executedinasubclass’constructor,thisorderisthe
samewhetherornotsuper()isused.
•Ifsuper()isnotused,thenthedefaultor
parameterlessconstructorofeachsuperclasswill
beexecuted.

Theconstructorsarecalledinorder
ofderivation,itmakessensethat
constructorsareexecutedinorderof
derivation.
Becauseasuperclasshasno
knowledgeofanysubclass,any
initializationitneedstoperformis
separatefromandpossibly
prerequisitetoanyinitialization
performedbythesubclass.Therefore,
itmustbeexecutedfirst.

Method Overriding:
•Inaclasshierarchy,whenamethodinasubclass
hasthesamenameandtypesignatureasamethod
initssuperclass,thenthemethodinthesubclassis
saidtooverridethemethodinthesuperclass.
•Whenanoverriddenmethodiscalledfromwithina
subclass,itwillalwaysrefertotheversionofthat
methoddefinedbythesubclass.Theversionofthe
methoddefinedbythesuperclasswillbehidden.

Method Overriding:...
Whenshow()isinvokedonanobjectoftypeB,
theversionofshow()definedwithinBisused.
Thatis,theversionofshow()insideBoverrides
theversiondeclaredinA.Toaccessthesuperclass
versionofanoverriddenmethod,youcandosoby
usingsuper.

Method Overriding:...
•Methodoverridingoccurs
onlywhenthenamesand
thetypesignaturesofthe
twomethodsareidentical.
•Iftheyarenot,thenthetwo
methodsaresimply
overloaded.

Dynamic Method Dispatch:
•MethodoverridingformsthebasisforoneofJava’s
mostpowerfulconcepts:dynamicmethoddispatch.
•Dynamicmethoddispatchisthemechanismbywhich
acalltoanoverriddenmethodisresolvedatruntime,
ratherthancompiletime.
•Dynamicmethoddispatchisimportantbecausethisis
howJavaimplementsrun-timepolymorphism.
•Animportantprinciple:Asuperclassreferencevariable
canrefertoasubclassobject.
•Javausesthisfacttoresolvecallstooverriddenmethods
atruntime.

Dynamic Method Dispatch:...
•Whenanoverriddenmethodiscalledthrougha
superclassreference,Javadetermineswhich
versionofthatmethodtoexecutebaseduponthe
typeoftheobjectbeingreferredtoatthetimethe
calloccurs.
•Thus,thisdeterminationismadeatruntime.When
differenttypesofobjectsarereferredto,different
versionsofanoverriddenmethodwillbecalled.

Dynamic Method Dispatch:...
•Inotherwords,itisthetypeoftheobjectbeing
referredto(notthetypeofthereferencevariable)
thatdetermineswhichversionofanoverridden
methodwillbeexecuted.
•Therefore,ifasuperclasscontainsamethodthatis
overriddenbyasubclass,thenwhendifferenttypes
ofobjectsarereferredtothroughasuperclass
referencevariable,differentversionsofthemethod
areexecuted.

Dynamic Method Dispatch:...

Dynamic Method Dispatch:...
Why Overridden Methods?
•OverriddenmethodsallowJavatosupportrun-time
polymorphism.Polymorphismisessentialtoobject-
orientedprogrammingforonereason:Itallowsageneral
classtospecifymethodsthatwillbecommontoallofits
derivatives,whileallowingsubclassestodefinethe
specificimplementationofsomeorallofthosemethods.
•OverriddenmethodsareanotherwaythatJavaimplements
the“Oneinterface,Multiplemethods”aspectof
polymorphism.

Dynamic Method Dispatch:...Applying Method Overriding

•Using Abstract Classes:
•Therearesituationsinwhichyouwillwanttodefinea
superclassthatdeclaresthestructureofagivenabstraction
withoutprovidingacompleteimplementationofevery
method.
•Sometimesyouwillwanttocreateasuperclassthatonly
definesageneralizedformthatwillbesharedbyallofits
subclasses,leavingittoeachsubclasstofillinthedetails.
Suchaclassdeterminesthenatureofthemethodsthatthe
subclassesmustimplement.
•Onewaythissituationcanoccuriswhenasuperclassis
unabletocreateameaningfulimplementationfora
method.

•Using Abstract Classes:...
•Youcanrequirethatcertainmethodsbeoverriddenby
subclassesbyspecifyingtheabstracttypemodifier.These
methodsaresometimesreferredtoassubclasser
responsibilitybecausetheyhavenoimplementation
specifiedinthesuperclass.Thus,asubclassmustoverride
them—itcannotsimplyusetheversiondefinedinthe
superclass.
•Todeclareanabstractmethod,usethisgeneralform:
abstract type name(parameter-list);
No method body is present.

•Using Abstract Classes:...
•Anyclassthatcontainsoneormoreabstractmethods
mustalsobedeclaredabstract.
•Todeclareaclassabstract,yousimplyusetheabstract
keywordinfrontoftheclasskeywordatthebeginningofthe
classdeclaration.
•Therecanbenoobjectsofanabstractclass.Thatis,an
abstractclasscannotbedirectlyinstantiatedwiththenew
operator.Suchobjectswouldbeuseless,becauseanabstract
classisnotfullydefined.Also,youcannotdeclareabstract
constructors,orabstractstaticmethods.
•Anysubclassofanabstractclassmusteitherimplementall
oftheabstractmethodsinthesuperclass,orbeitselfdeclared
abstract.

•Using Abstract Classes:...An Example
Abstractclassescan
includeas much
implementationastheysee
fit.
Althoughabstractclasses
cannotbeusedto
instantiateobjects,theycan
beusedtocreateobject
references,becauseJava’s
approachtorun-time
polymorphism is
implementedthroughthe
use of superclass
references.
Thus,itmustbepossibleto
createareferencetoan
abstractclasssothatitcan
beusedtopointtoa
subclassobject.

•Using Abstract Classes:...An Example

•Using finalwith Inheritance:
•The keyword final has three uses.
➢First, it can be used to create the equivalent of a named
constant.
➢The other two uses of final apply to inheritance.
Using final to Prevent Overriding
•Todisallowamethodfrombeingoverridden,specifyfinalasa
modifieratthestartofitsdeclaration.Methodsdeclaredasfinal
cannotbeoverridden.

•Using finalwith Inheritance:...
Using final to Prevent Overriding
•Todisallowamethodfrombeingoverridden,specifyfinalasa
modifieratthestartofitsdeclaration.Methodsdeclaredasfinal
cannotbeoverridden.

•Using finalwith Inheritance:...
Using final to Prevent Overriding...
•Methodsdeclaredasfinalcansometimesprovideaperformance
enhancement:Thecompilerisfreetoinlinecallstothembecauseit
“knows”theywillnotbeoverriddenbyasubclass.Whenasmall
finalmethodiscalled,oftentheJavacompilercancopythe
bytecodeforthesubroutinedirectlyinlinewiththecompiledcodeof
thecallingmethod,thuseliminatingthecostlyoverheadassociated
withamethodcall.
•Inliningisonlyanoptionwithfinalmethods.Normally,Java
resolvescallstomethodsdynamically,atruntime.Thisiscalledlate
binding.However,sincefinalmethodscannotbeoverridden,acall
toonecanberesolvedatcompiletime.Thisiscalledearlybinding.

•Using finalwith Inheritance:...
Using final to Prevent Inheritance
•Sometimesyouwillwanttopreventaclassfrombeing
inherited.Todothis,precedetheclassdeclarationwithfinal.
Declaringaclassasfinalimplicitlydeclaresallofitsmethods
asfinal,too.
•Itisillegaltodeclareaclassasbothabstractandfinalsincean
abstractclassisincompletebyitselfandreliesuponits
subclassestoprovidecompleteimplementations.

•The Object Class:
•Thereisonespecialclass,Object,definedbyJava.All
otherclassesaresubclassesofObject.
•Thatis,Objectisasuperclassofallotherclasses.This
meansthatareferencevariableoftypeObjectcanreferto
anobjectofanyotherclass.
•Also,sincearraysareimplementedasclasses,avariableof
typeObjectcanalsorefertoanyarray.

•The Object Class:...
•Objectdefinesthefollowingmethods,whichmeansthat
theyareavailableineveryobject.

•Additional Coverage:
•Inheritanceinjavaisamechanisminwhichoneobject
acquiresallthepropertiesandbehaviorsofparentobject.
•Theideabehindinheritanceinjavaisthatyoucancreate
newclassesthatarebuiltuponexistingclasses.Whenyou
inheritfromanexistingclass,youcanreusemethodsand
fieldsofparentclass,andyoucanaddnewmethodsand
fieldsalso.
•InheritancerepresentstheIS-Arelationship,alsoknown
asparent-childrelationship.IS-Aisawayofsaying:
Thisobjectisatypeofthatobject.

•Additional Coverage:...
•Theextendskeywordisusedtoachieveinheritance.
public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}

•Additional Coverage:...Example
publicclassAnimal{
}
publicclassMammalextendsAnimal{
}
publicclassDogextendsMammal{
publicstaticvoidmain(Stringargs[]){
Animala=newAnimal();
Mammalm=newMammal();
Dogd=newDog();
System.out.println(minstanceofAnimal);
System.out.println(dinstanceofMammal);
System.out.println(dinstanceofAnimal);
}
}

•Additional Coverage:...
Why use inheritance in java?
✓For Method Overriding (so runtime polymorphism can
be achieved).
✓For Code Reusability.
•Types:

•Additional Coverage:...Examples

•Additional Coverage:...Examples

•Additional Coverage:...Examples

Packages & Interfaces
PreparedusingfollowingResources:
➢Herbert Schildt, “Java: The Complete Reference”,Tata McGrawHillEducation
➢E Balagurusamy, Programming with Java -ATata McGraw Hill Education
➢https://www.geeksforgeeks.org/java/
➢https://www.javatpoint.com/java-tutorial
➢https://www.tutorialspoint.com/java/index.htm
➢https://www.w3schools.com/java/
By: DIVAKARA .N

Packages:DefiningaPackage,FindingPackagesand
CLASSPATH,AccessProtection,ImportingPackages.
Interfaces:DefininganInterface,Implementing
Interfaces,NestedInterfaces,ApplyingInterfaces,
VariablesinInterfaces,InterfacesCanBeExtended.

Packages:
•DefiningaPackage
•FindingPackagesandCLASSPATH
•AccessProtection
•ImportingPackages
Interfaces:
•DefininganInterface
•ImplementingInterfaces
•NestedInterfacesApplyingInterfaces
•VariablesinInterfaces
•InterfacesCanBeExtended

Basics:
•Packagesarecontainersforclassesthatareusedtokeep
theclassnamespacecompartmentalized.
•Eg:ApackageallowsyoutocreateaclassnamedList,
whichyoucanstoreinyourownpackagewithoutconcern
thatitwillcollidewithsomeotherclassnamedListstored
elsewhere.
•Packagesarestoredinahierarchicalmannerandare
explicitlyimportedintonewclassdefinitions.
•AJava’smechanismforpartitioningtheclassnamespace
intomoremanageablechunks.

Basics:...
•Thepackageisbothanamingandavisibilitycontrol
mechanism.
•Onecandefineclassesinsideapackagethatarenot
accessiblebycodeoutsidethatpackage.
•Alsodefineclassmembersthatareonlyexposedtoother
membersofthesamepackage.
•Thisallowsyourclassestohaveintimateknowledgeof
eachother,butnotexposethatknowledgetotherestofthe
world.

Basics:...
The benefits of organising classes into packages are:
•Theclassescontainedinthepackagesofother
programs/applicationscanbereused.
•Inpackagesclassescanbeuniquecomparedwithclassesin
otherpackages.Thattwoclassesintwodifferentpackages
canhavethesamename.Ifthereisanamingclash,then
classescanbeaccessedwiththeirfullyqualifiedname.
•Classesinpackagescanbehiddenifwedon’twantother
packagestoaccessthem.
•Alsoprovideawayforseparating“design”fromcoding.
•Packagesenablegroupingoffunctionallyrelated
classes.

Basics:...
The Java Foundation Packages
•Javaprovidesalargenumberofclassesgropedinto
differentpackagesbasedontheirfunctionality.
ThesixfoundationJavapackagesare:
•java.lang:Classesforprimitivetypes,strings,math
functions,threads,andexception
•java.util:Classessuchasvectors,hashtables,dateetc.
•java.io:StreamclassesforI/O
•java.awt:ClassesforimplementingGUI–windows,buttons,
menusetc.
•java.net:Classesfornetworking
•java.applet:Classesforcreatingandimplementingapplets

Basics:...
The Java Foundation Packages

DefiningaPackage:
•Includeapackagecommandasthefirststatementina
Javasourcefile.Anyclassesdeclaredwithinthatfilewill
belongtothespecifiedpackage.
•Thepackagestatementdefinesanamespaceinwhich
classesarestored.Ifyouomitthepackagestatement,the
classnamesareputintothedefaultpackage,whichhasno
name.
•Whilethedefaultpackageisfineforshort,sample
programs,itisinadequateforrealapplications.Mostofthe
time,youwilldefineapackageforyourcode.
•GeneralForm:packagepkg;Eg:packageMyPackage;

DefiningaPackage:...
•Javausesfilesystemdirectoriestostorepackages.For
example,the.classfilesforanyclassesyoudeclaretobe
partofMyPackagemustbestoredinadirectorycalled
MyPackage.
•Rememberthatcaseissignificant,andthedirectory
namemustmatchthepackagenameexactly.
•Morethanonefilecanincludethesamepackage
statement.Thepackagestatementsimplyspecifiesto
whichpackagetheclassesdefinedinafilebelong.Itdoes
notexcludeotherclassesinotherfilesfrombeingpartof
thatsamepackage.
•Mostreal-worldpackagesarespreadacrossmanyfiles.

DefiningaPackage:...
•Youcancreateahierarchyofpackages.Todoso,simply
separateeachpackagenamefromtheoneaboveitbyuse
ofaperiod.Thegeneralformofamultileveledpackage
statementpackagepkg1[.pkg2[.pkg3]];
•Apackagehierarchymustbereflectedinthefilesystemof
yourJavadevelopmentsystem.
•Eg:Apackagedeclaredaspackagejava.awt.image;
needstobestoredinjava\awt\imageinaWindows
environment.
•Besuretochooseyourpackagenamescarefully.You
cannotrenameapackagewithoutrenamingthedirectoryin
whichtheclassesarestored.

FindingPackagesandCLASSPATH:
•Packagesaremirroredbydirectories.Thisraisesan
importantquestion:HowdoestheJavarun-timesystem
knowwheretolookforpackagesthatyoucreate?
•Theanswerhasthreeparts.
✓First,bydefault,theJavarun-timesystemusesthecurrent
workingdirectoryasitsstartingpoint.Thus,ifyour
packageisinasubdirectoryofthecurrentdirectory,itwill
befound.
✓Second,youcanspecifyadirectorypathorpathsbysetting
theCLASSPATHenvironmentalvariable.
✓Third,youcanusethe-classpathoptionwithjavaand
javactospecifythepathtoyourclasses.

FindingPackagesandCLASSPATH:...
•Eg:packageMyPack;Inorderforaprogramtofind
MyPack,oneofthreethingsmustbetrue.
✓Eithertheprogramcanbeexecutedfromadirectory
immediatelyaboveMyPack,or
✓theCLASSPATHmustbesettoincludethepathto
MyPack,or
✓the-classpathoptionmustspecifythepathtoMyPack
whentheprogramisrunviajava.
•Whenthesecondtwooptionsareused,theclasspathmustnotinclude
MyPack,itself.ItmustsimplyspecifythepathtoMyPack.Forexample,
inaWindowsenvironment,ifthepathtoMyPackis
C:\MyPrograms\Java\MyPackThentheclasspathtoMyPackis
C:\MyPrograms\Java\MyPack

FindingPackagesandCLASSPATH:...
•AShortPackageExample
CallthisfileAccountBalance.javaand
putitinadirectorycalledMyPack.
Next,compilethefile.Makesurethat
theresulting.classfileisalsointhe
MyPackdirectory.Then,tryexecuting
theAccountBalanceclass,usingthe
followingcommandline:
javaMyPack.AccountBalance
Remember,youwillneedtobeinthe
directoryaboveMyPackwhenyou
executethiscommand.
AccountBalanceisnowpartofthe
packageMyPack.Thismeansthatit
cannotbeexecutedbyitself.

FindingPackagesandCLASSPATH:...
•AShortPackageExample...

AccessProtection:
•Packagesaddanotherdimensiontoaccesscontrol.Java
providesmanylevelsofprotectiontoallowfine-grained
controloverthevisibilityofvariablesandmethodswithin
classes,subclasses,andpackages.
•Classesandpackagesarebothmeansofencapsulatingand
containingthenamespaceandscopeofvariablesand
methods.
•Packagesactascontainersforclassesandother
subordinatepackages.
•Classesactascontainersfordataandcode.Theclassis
Java’ssmallestunitofabstraction.

AccessProtection:...
•Becauseoftheinterplaybetweenclassesandpackages,
Javaaddressesfourcategoriesofvisibilityforclass
members:
➢Subclassesinthesamepackage
➢Non-subclassesinthesamepackage
➢Subclassesindifferentpackages
➢Classesthatareneitherinthesamepackagenorsubclasses
•Thethreeaccessspecifiers,private,public,and
protected,provideavarietyofwaystoproducethemany
levelsofaccessrequiredbythesecategories.

AccessProtection:...
•WhileJava’saccesscontrolmechanismmayseem
complicated,wecansimplifyitasfollows:
oAnythingdeclaredpubliccanbeaccessedfromanywhere.
oAnythingdeclaredprivatecannotbeseenoutsideofits
class.
oWhenamemberdoesnothaveanexplicitaccess
specification,itisvisibletosubclassesaswellastoother
classesinthesamepackage.Thisisthedefaultaccess.
oIfyouwanttoallowanelementtobeseenoutsideyour
currentpackage,butonlytoclassesthatsubclassyourclass
directly,thendeclarethatelementprotected.

AccessProtection:...
•ClassMemberAccess-Appliesonlytomembersofclasses.
Anon-nestedclasshasonly
twopossibleaccesslevels:
defaultandpublic.Whena
classisdeclaredaspublic,it
isaccessiblebyanyother
code.
Ifaclasshasdefaultaccess,
thenitcanonlybeaccessedby
othercodewithinitssame
package.
Whenaclassispublic,itmust
betheonlypublicclass
declaredinthefile,andthe
filemusthavethesamename
astheclass.

AccessProtection:...
•AnAccessExample

AccessProtection:...
•AnAccessExample...

AccessProtection:...
•AnAccessExample...

ImportingPackages:
•Giventhatpackagesexistandareagoodmechanismfor
compartmentalizingdiverseclassesfromeachother,itiseasyto
seewhyallofthebuilt-inJavaclassesarestoredinpackages.
•TherearenocoreJavaclassesintheunnameddefaultpackage;
allofthestandardclassesarestoredinsomenamedpackage.
Sinceclasseswithinpackagesmustbefullyqualifiedwiththeir
packagenameornames,itcouldbecometedioustotypeinthe
longdot-separatedpackagepathnameforeveryclassyouwant
touse.
•Forthisreason,Javaincludestheimportstatementtobring
certainclasses,orentirepackages,intovisibility.Once
imported,aclasscanbereferredtodirectly,usingonlyits
name.

ImportingPackages:...
•Theimportstatementisaconveniencetotheprogrammerand
isnottechnicallyneededtowriteacompleteJavaprogram.If
youaregoingtorefertoafewdozenclassesinyour
application,however,theimportstatementwillsavealotof
typing.
•InaJavasourcefile,importstatementsoccurimmediately
followingthepackagestatement(ifitexists)andbeforeany
classdefinitions.Thegeneralformoftheimportstatement:
import pkg1[.pkg2].(classname|*);
•Here,pkg1isthenameofatop-levelpackage,andpkg2isthe
nameofasubordinatepackageinsidetheouterpackage
separatedbyadot(.).

ImportingPackages:...
•Thereisnopracticallimitonthedepthofapackagehierarchy,
exceptthatimposedbythefilesystem.Finally,youspecify
eitheranexplicitclassnameorastar(*),whichindicatesthat
theJavacompilershouldimporttheentirepackage.
•Thiscodefragmentshowsbothformsinuse:
import java.util.Date;
import java.io.*;
•CAUTIONThestarformmayincreasecompilationtime-
especiallyifyouimportseverallargepackages.Forthisreason
itisagoodideatoexplicitlynametheclassesthatyouwantto
useratherthanimportingwholepackages.However,thestar
formhasabsolutelynoeffectontherun-timeperformanceor
sizeofyourclasses.

ImportingPackages:...
•AllofthestandardJavaclassesincludedwithJavaarestoredina
packagecalledjava.
•Thebasiclanguagefunctionsarestoredinapackageinsideofthe
javapackagecalledjava.lang
•Normally,youhavetoimporteverypackageorclassthatyouwantto
use,butsinceJavaisuselesswithoutmuchofthefunctionalityin
java.lang,itisimplicitlyimportedbythecompilerforall
programs.Thisisequivalenttothefollowinglinebeingat
thetopofallofyourprograms:importjava.lang.*;
•Ifaclasswiththesamenameexistsintwodifferentpackagesthat
youimportusingthestarform,thecompilerwillremainsilent,
unlessyoutrytouseoneoftheclasses.Inthatcase,youwillgeta
compile-timeerrorandhavetoexplicitlynametheclassspecifying
itspackage.

ImportingPackages:...
•Itmustbeemphasizedthattheimportstatementisoptional.Any
placeyouuseaclassname,youcanuseitsfullyqualifiedname,
whichincludesitsfullpackagehierarchy.
•Forexample,thisfragmentusesanimportstatement:
importjava.util.*;
classMyDateextendsDate{
}
•Thesameexamplewithouttheimportstatementlookslikethis:
classMyDateextendsjava.util.Date{
}
•Inthisversion,Dateisfully-qualified.

ImportingPackages:...
•Whenapackageisimported,onlythoseitemswithinthe
packagedeclaredaspublicwillbeavailabletonon-
subclassesintheimportingcode.
•Forexample,ifyouwanttheBalanceclassofthepackage
MyPackshownearliertobeavailableasastand-alone
classforgeneraluseoutsideofMyPack,thenyouwill
needtodeclareitaspublicandputitintoitsownfile.

ImportingPackages:...

Basics:
•Throughtheuseoftheinterfacekeyword,Javaallows
youtofullyabstracttheinterfacefromits
implementation.
•Usinginterface,youcanspecifyasetofmethodsthat
canbeimplementedbyoneormoreclasses.The
interface,itself,doesnotactuallydefineany
implementation.
•Althoughtheyaresimilartoabstractclasses,
interfaceshaveanadditionalcapability:Aclasscan
implementmorethanoneinterface.Bycontrast,aclass
canonlyinheritasinglesuperclass(abstractorotherwise).

Basics:...
•Usingthekeywordinterface,youcanfullyabstracta
class’interfacefromitsimplementation.Alsoyoucan
specifywhataclassmustdo,butnothowitdoesit.
•Interfacesaresyntacticallysimilartoclasses,butthey
lackinstancevariables,andtheirmethodsaredeclared
withoutanybody.
•Onceitisdefined,anynumberofclassescanimplement
aninterface.Also,oneclasscanimplementanynumberof
interfaces.

Basics:...
•Toimplementaninterface,aclassmustcreatethe
completesetofmethodsdefinedbytheinterface.
However,eachclassisfreetodeterminethedetailsofits
ownimplementation.
•Byprovidingtheinterfacekeyword,Javaallowsyouto
fullyutilizethe“oneinterface,multiplemethods”aspect
ofpolymorphism.
•Interfacesaredesignedtosupportdynamicmethod
resolutionatruntime.
•NOTEInterfacesaddmostofthefunctionalitythatisrequiredfor
manyapplicationsthatwouldnormallyresorttousingmultiple
inheritanceinalanguagesuchasC++.

Basics:...
WhyuseJavainterface?Therearemainlythreereasons:
It is used to achieve fully abstraction.
Byinterface,wecansupportthefunctionalityofmultipleinheritance.
It can be used to achieve loose coupling.
•Thejavacompileraddspublicandabstractkeywordsbeforethe
interfacemethodandpublic,staticandfinalkeywordsbeforedata
members.

Basics:...
WhyuseJavainterface?Therearemainlythreereasons:
It is used to achieve fully abstraction.
Byinterface,wecansupportthefunctionalityofmultipleinheritance.
It can be used to achieve loose coupling.
•Thejavacompileraddspublicandabstractkeywordsbeforethe
interfacemethodandpublic,staticandfinalkeywordsbeforedata
members.

Basics:...
•Understandingrelationshipbetweenclassesandinterfaces
•MultipleinheritanceinJavabyinterface

DefininganInterface:
•Aninterfaceisdefinedmuchlikeaclass.TheGeneralform:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN= value;
}
•Whennoaccessspecifierisincluded,thendefaultaccessresults,andthe
interfaceisonlyavailabletoothermembersofthepackageinwhichitis
declared.Whenitisdeclaredaspublic,theinterfacecanbeusedbyanyother
code.Inthiscase,theinterfacemustbetheonlypublicinterfacedeclaredin
thefile,andthefilemusthavethesamenameastheinterface.

DefininganInterface:...
•Noticethatthemethodsthataredeclaredhavenobodies.
Theyendwithasemicolonaftertheparameterlist.They
are,essentially,abstractmethods;therecanbenodefault
implementationofanymethodspecifiedwithinan
interface.
•Eachclassthatincludesaninterfacemustimplementallof
themethods.
•Variablescanbedeclaredinsideofinterfacedeclarations.
Theyareimplicitlyfinalandstatic,meaningtheycannot
bechangedbytheimplementingclass.Theymustalsobe
initialized.
•Allmethodsandvariablesareimplicitlypublic.

DefininganInterface:...
•Examples:

ImplementingInterfaces:
•Onceaninterfacehasbeendefined,oneormoreclassescan
implementthatinterface.
•Toimplementaninterface,includetheimplementsclauseinaclass
definition,andthencreatethemethodsdefinedbytheinterface.
•Ifaclassimplementsmorethanoneinterface,theinterfacesare
separatedwithacomma.Ifaclassimplementstwointerfacesthat
declarethesamemethod,thenthesamemethodwillbeusedby
clientsofeitherinterface.
•Themethodsthatimplementaninterfacemustbedeclaredpublic.
Also,thetypesignatureoftheimplementingmethodmustmatch
exactlythetypesignaturespecifiedintheinterfacedefinition.

ImplementingInterfaces:...
•Itisbothpermissibleandcommonforclassesthatimplement
interfacestodefineadditionalmembersoftheirown.

ImplementingInterfaces:...
•AccessingImplementationsThroughInterfaceReferences

ImplementingInterfaces:...
•PartialImplementations
•Ifaclassincludesaninterfacebutdoesnotfullyimplementthe
methodsdefinedbythatinterface,thenthatclassmustbedeclaredas
abstract.
•Here,theclassIncompletedoesnotimplementcallback()andmust
bedeclaredasabstract.
•AnyclassthatinheritsIncompletemustimplementcallback()orbe
declaredabstractitself.

NestedInterfaces:
•Aninterfacecanbedeclaredamemberofaclassoranother
interface.Suchaninterfaceiscalledamemberinterfaceoranested
interface.
•Anestedinterfacecanbedeclaredaspublic,private,orprotected.
Thisdiffersfromatop-levelinterface,whichmusteitherbedeclared
aspublicorusethedefaultaccesslevel.
•Whenanestedinterfaceisusedoutsideofitsenclosingscope,it
mustbequalifiedbythenameoftheclassorinterfaceofwhichitisa
member.Thus,outsideoftheclassorinterfaceinwhichanested
interfaceisdeclared,itsnamemustbefullyqualified.

NestedInterfaces:...
•Noticethatthenameisfullyqualifiedbytheenclosing
class’name.Insidethemain()method,anA.NestedIF
referencecallednifiscreated,anditisassignedareference
toaBobject.BecauseBimplementsA.NestedIF,thisis
legal.
.

ApplyingInterfaces:
•Theinterfacetothestackremainsthesame.Thatis,the
methodspush()andpop()definetheinterfacetothestack
independentlyofthedetailsoftheimplementation.
•Becausetheinterfacetoastackisseparatefromits
implementation,itiseasytodefineastackinterface,
leavingittoeachimplementationtodefinethespecifics.

ApplyingInterfaces:...

ApplyingInterfaces:...

ApplyingInterfaces:...

VariablesinInterfaces:
•Youcanuseinterfacestoimportsharedconstantsinto
multipleclassesbysimplydeclaringaninterfacethat
containsvariablesthatareinitializedtothedesiredvalues.
Whenyouincludethatinterfaceinaclass(thatis,when
you“implement”theinterface),allofthosevariablenames
willbeinscopeasconstants.
•Itisasifthatclasswereimportingtheconstantfieldsinto
theclassnamespaceasfinalvariables.

VariablesinInterfaces:...

InterfacesCanBeExtended:
•Oneinterfacecaninheritanotherbyuseofthekeyword
extends.
•Thesyntaxisthesameasforinheritingclasses.
•Whenaclassimplementsaninterfacethatinheritsanother
interface,itmustprovideimplementationsforallmethods
definedwithintheinterfaceinheritancechain.

InterfacesCanBeExtended:

Exception-Handling
PreparedusingfollowingResources:
➢Herbert Schildt, “Java: The Complete Reference”,Tata McGrawHillEducation
➢E Balagurusamy, Programming with Java -ATata McGraw Hill Education
➢https://www.geeksforgeeks.org/java/
➢https://www.javatpoint.com/java-tutorial
➢https://www.tutorialspoint.com/java/index.htm
➢https://www.w3schools.com/java/
By: DIVAKARA .N

•Basics
•Differenttypesofexceptionclasses
•Useoftry&catchwiththrow
•throws&finally
•Creationofuserdefinedexceptionclasses

Basics:
The three categories of errors
•Syntaxerrorsarisebecausetherulesofthe
languagehavenotbeenfollowed.Theyare
detectedbythecompiler.
•Runtimeerrorsoccurwhiletheprogramis
runningiftheenvironmentdetectsan
operationthatisimpossibletocarryout.
•Logicerrorsoccurwhenaprogramdoesn't
performthewayitwasintendedto.

Basics:...
•Anexceptionisanabnormalconditionthatarisesinacode
sequenceatruntime.Inotherwords,anexceptionisa
run-timeerror.
•Incomputerlanguagesthatdonotsupportexception
handling,errorsmustbecheckedandhandledmanually-
typicallythroughtheuseoferrorcodes,andsoon.
•AJavaexceptionisanobjectthatdescribesan
exceptional(thatis,error)conditionthathasoccurred
inapieceofcode.Whenanexceptionalcondition
arises,anobjectrepresentingthatexceptioniscreated
andthrowninthemethodthatcausedtheerror.

Basics:...
•ExceptionscanbegeneratedbytheJavarun-timesystem,
ortheycanbemanuallygeneratedbyourcode.
•ExceptionsthrownbyJavarelatetofundamentalerrors
thatviolatetherulesoftheJavalanguageortheconstraints
oftheJavaexecutionenvironment.
•Manuallygeneratedexceptionsaretypicallyusedtoreport
someerrorconditiontothecallerofamethod.
•Javaexceptionhandlingismanagedviafive
keywords:try,catch,throw,throws,andfinally.

Basics:...
•Programstatementsthatyouwanttomonitorfor
exceptionsarecontainedwithinatryblock.Ifan
exceptionoccurswithinthetryblock,itisthrown.Our
codecancatchthisexception(usingcatch)andhandleit
insomerationalmanner.
•System-generatedexceptionsareautomaticallythrownby
theJavarun-timesystem.Tomanuallythrowanexception,
usethekeywordthrow.Anyexceptionthatisthrownout
ofamethodmustbespecifiedassuchbyathrowsclause.
Anycodethatabsolutelymustbeexecutedafteratry
blockcompletesisputinafinallyblock.

Basics:...
•Thegeneralformofanexception-handlingblock:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}

ExceptionTypes:
•Allexceptiontypesaresubclassesofthebuilt-inclass
Throwable.Thus,Throwableisatthetopofthe
exceptionclasshierarchy.ImmediatelybelowThrowable
aretwosubclassesthatpartitionexceptionsintotwo
distinctbranches.
•OnebranchisheadedbyException.Thisclassisusedfor
exceptionalconditionsthatuserprogramsshouldcatch.Thisis
alsotheclassthatyouwillsubclasstocreateourowncustom
exceptiontypes.ThereisanimportantsubclassofException,
calledRuntimeException.Exceptionsofthistypeare
automaticallydefinedfortheprogramsthatyouwriteand
includethingssuchasdivisionbyzeroandinvalidarray
indexing.

ExceptionTypes:...
•TheotherbranchistoppedbyError,whichdefines
exceptionsthatarenotexpectedtobecaughtundernormal
circumstancesbyourprogram.ExceptionsoftypeError
areusedbytheJavarun-timesystemtoindicateerrors
havingtodowiththerun-timeenvironment,itself.Stack
overflowisanexampleofsuchanerror.
•Thischapterwillnotbedealingwithexceptionsoftype
Error,becausethesearetypicallycreatedinresponseto
catastrophicfailuresthatcannotusuallybehandledbyour
program.

ExceptionTypes:...
•EveryExceptiontypeisbasicallyanobjectbelongingtoclass
Exception
•ThrowableclassistherootclassofExceptions.
•ThrowableclasshastwodirectsubclassesnamedException,Error

ExceptionTypes:...
Checked Exceptions
•AllExceptionsthatextendstheExceptionoranyoneits
subclassexceptRunTimeExceptionclassarechecked
exceptions.
•CheckedExceptionsarecheckedbytheJavacompiler.
•Therearetwoapproachesthatausercanfollowtodeal
withcheckedexceptions.
➢Inform the compiler that a method can throw an
Exception.
➢Catch the checked exception in try catch block.

ExceptionTypes:...
Checked Exceptions…
•IfCheckedexceptioniscaughtthenexceptionhandling
codewillbeexecutedandprogram’sexecutioncontinues.
•IfCheckedexceptionisnotcaughtthenjavainterpreter
willprovidethedefaulthandler.Butinthiscaseexecution
oftheprogramwillbestoppedbydisplayingthenameof
theexceptionsobject.

ExceptionTypes:...
Unchecked Exceptions
•AllExceptionsthatextendtheRuntimeExceptionorany
oneofitssubclassareuncheckedexceptions.
•UncheckedExceptionsareuncheckedbycompiler.
•Whetheryoucatchtheexceptionornotcompilerwillpass
thecompilationprocess.
•IfUncheckedexceptioniscaughtthenexceptionhandling
codewillbeexecutedandprogram’sexecutioncontinues.
•IfUncheckedexceptionisnotcaughtthenjavainterpreter
willprovidethedefaulthandler.Butinthiscaseexecution
oftheprogramwillbestoppedbydisplayingthenameof
theexceptionsobject.

ExceptionTypes:...
Unchecked Exceptions…

ExceptionTypes:...
Unchecked Exceptions…

ExceptionTypes:...
Unchecked Exceptions…

ExceptionTypes:...
Checked Exceptions vs. Unchecked Exceptions
•RuntimeException,Errorandtheirsubclassesare
knownasuncheckedexceptions.
•Allotherexceptionsareknownaschecked
exceptions,meaningthatthecompilerforcesthe
programmertocheckanddealwiththeexceptions.

ExceptionTypes:...
Checked Exceptions vs. Unchecked Exceptions…
•Exceptionswhicharecheckedforduringcompiletimeare
calledcheckedexceptions.Eg:SQLExceptionorany
userdefinedexceptionextendingtheExceptionclass.
•Exceptionswhicharenotcheckedforduringcompiletime
arecalleduncheckedexception.Eg:NullPointerException
oranyclassextendingtheRuntimeExceptionclass.
•Allthecheckedexceptionsmustbehandledintheprogram.
•Theexceptionsraised,ifnothandledwillbehandledbytheJava
VirtualMachine.TheVirtualmachinewillprintthestacktraceofthe
exceptionindicatingthestackofexceptionandthelinewhereitwas
caused.

UncaughtExceptions:
class Exc0 {
public static void main(String args[]) {
intd = 0;
inta = 42 / d;
}
}
•WhentheJavarun-timesystemdetectstheattempttodividebyzero,
itconstructsanewexceptionobjectandthenthrowsthisexception.
ThiscausestheexecutionofExc0tostop,becauseoncean
exceptionhasbeenthrown,itmustbecaughtbyanexception
handleranddealtwithimmediately.
•Inthisexample,wehaven’tsuppliedanyexceptionhandlersofour
own,sotheexceptioniscaughtbythedefaulthandlerprovidedby
theJavarun-timesystem.

UncaughtExceptions:...
•Anyexceptionthatisnotcaughtbyourprogramwill
ultimatelybeprocessedbythedefaulthandler.
•Thedefaulthandlerdisplaysastringdescribingthe
exception,printsastacktracefromthepointatwhichthe
exceptionoccurred,andterminatestheprogram.
•Hereistheexceptiongeneratedwhenthisexampleis
executed:
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)

UncaughtExceptions:...
•Thestacktracewillalwaysshowthesequenceofmethod
invocationsthatleduptotheerror.
class Exc1 {
static void subroutine() {
intd = 0;
inta = 10 / d;
}
public static void main(String args[]) {
Exc1.subroutine();
}
}
Theresultingstacktracefromthedefaultexceptionhandlershowshowthe
entirecallstackisdisplayed:
java.lang.ArithmeticException: / by zero
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)

Usingtryandcatch:
•Althoughthedefaultexceptionhandlerprovidedby
theJavarun-timesystemisusefulfordebugging,
youwillusuallywanttohandleanexception
ourself.
•Doingsoprovidestwobenefits:
➢First,itallowsyoutofixtheerror.
➢Second,itpreventstheprogramfrom
automaticallyterminating.

Usingtryandcatch:...
•Toguardagainstandhandlearun-timeerror,simplyenclosethe
codethatyouwanttomonitorinsideatryblock.
•Immediatelyfollowingthetryblock,includeacatchclausethat
specifiestheexceptiontypethatyouwishtocatch.
class Exc2 {
public static void main(String args[]) {
intd, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticExceptione) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Program output:
Division by zero.
After catch statement.

Usingtryandcatch:...
•Oncethecatchstatementhasexecuted,programcontrol
continueswiththenextlineintheprogramfollowingthe
entiretry/catchmechanism.
•Atryanditscatchstatementformaunit.Thescopeofthe
catchclauseisrestrictedtothosestatementsspecifiedby
theimmediatelyprecedingtrystatement.Acatch
statementcannotcatchanexceptionthrownbyanothertry
statement.
•Thegoalofmostwell-constructedcatchclauses
shouldbetoresolvetheexceptionalconditionand
thencontinueonasiftheerrorhadneverhappened.

Usingtryandcatch:...
// Handle an exception and move on.
import java.util.Random;
class HandleError{
public static void main(String args[]) {
inta=0, b=0, c=0;
Random r = new Random();
for(inti=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
} catch (ArithmeticExceptione) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
Forexample,inthis
programeachiterationofthe
forloopobtainstworandom
integers.Thosetwointegers
are
dividedbyeachother,and
theresultisusedtodivide
thevalue12345.
Thefinalresultisputintoa.
Ifeitherdivisionoperation
causesadivide-by-zero
error,itiscaught,thevalue
ofaissettozero,andthe
programcontinues.

Usingtryandcatch:...
Displaying a Description of an Exception
•Youcandisplaythisdescriptioninaprintln()statementbysimply
passingtheexceptionasanargument.Forexample,thecatchblock
intheprecedingprogramcanberewrittenlikethis:
catch (ArithmeticExceptione) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
•Whenthisversionissubstitutedintheprogram,andtheprogramis
run,eachdivide-by-zeroerrordisplaysthefollowingmessage:
Exception: java.lang.ArithmeticException: / by zero

MultiplecatchClauses:
•Insomecases,morethanoneexceptioncouldberaisedby
asinglepieceofcode.Tohandlethistypeofsituation,
youcanspecifytwoormorecatchclauses,each
catchingadifferenttypeofexception.
•Whenanexceptionisthrown,eachcatchstatementis
inspectedinorder,andthefirstonewhosetypematches
thatoftheexceptionisexecuted.
•Afteronecatchstatementexecutes,theothersare
bypassed,andexecutioncontinuesafterthetry/catch
block.

MultiplecatchClauses:...
•Eg:Totraptwodifferentexceptions
// Demonstrate multiple catch statements.
class MultiCatch{
public static void main(String args[]) {
try {
inta = args.length;
System.out.println("a = " + a);
intb = 42 / a;
intc[] = { 1 };
c[42] = 99;
} catch(ArithmeticExceptione) {
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsExceptione) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
The output generated by running it
both ways:
C:\>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg
a = 1
Array index oob:
java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.

MultiplecatchClauses:...
•Whenyouusemultiplecatchstatements,itisimportantto
rememberthatexceptionsubclassesmustcomebeforeany
oftheirsuperclasses.
•Thisisbecauseacatchstatementthatusesasuperclass
willcatchexceptionsofthattypeplusanyof
itssubclasses.Thus,asubclasswouldneverbereached
ifitcameafteritssuperclass.
•Further,inJava,unreachablecodeisanerror.

MultiplecatchClauses:...
SinceArithmeticExceptionisa
subclassofException,thefirst
catchstatementwillhandleall
Exception-basederrors,including
ArithmeticException.Thismeans
thatthesecondcatchstatementwill
neverexecute.
Tofixtheproblem,reversethe
orderofthecatchstatements.

NestedtryStatements:
•Atrystatementcanbeinsidetheblockofanothertry.
Eachtimeatrystatementisentered,thecontextofthat
exceptionispushedonthestack.Ifaninnertrystatement
doesnothaveacatchhandlerforaparticularexception,
thestackisunwoundandthenexttrystatement’scatch
handlersareinspectedforamatch.
•Thiscontinuesuntiloneofthecatchstatementssucceeds,
oruntilallofthenestedtrystatementsareexhausted.Ifno
catchstatementmatches,thentheJavarun-timesystem
willhandletheexception.

NestedtryStatements:...

NestedtryStatements:...
Theoutputofthisprogramis
identicaltothatofthepreceding
example.

throw:
•Sofar,youhaveonlybeencatchingexceptionsthatare
thrownbytheJavarun-timesystem.However,itispossible
foryourprogramtothrowanexceptionexplicitly,using
thethrowstatement.
•Thegeneralform:throwThrowableInstance;
•Here,ThrowableInstancemustbeanobjectoftypeThrowableora
subclassofThrowable.Primitivetypes,suchasintorchar,aswell
asnon-Throwableclasses,suchasStringandObject,cannotbe
usedasexceptions.
•TherearetwowaystoobtainaThrowableobject:
➢usingaparameterinacatchclause,or
➢creatingonewiththenewoperator.

throw:...
•Theflowofexecutionstopsimmediatelyafterthethrow
statement;anysubsequentstatementsarenotexecuted.The
nearestenclosingtryblockisinspectedtoseeifithasa
catchstatementthatmatchesthetypeofexception.
•Ifitdoesfindamatch,controlistransferredtothat
statement.Ifnot,thenthenextenclosingtrystatementis
inspected,andsoon.
•Ifnomatchingcatchisfound,thenthedefaultexception
handlerhaltstheprogramandprintsthestacktrace.
•Aasampleprogramthatcreatesandthrowsanexception.
Thehandlerthatcatchestheexceptionrethrowsittothe
outerhandler.

throw:...
The resulting output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo

throw:...
•TheprogramalsoillustrateshowtocreateoneofJava’sstandard
exceptionobjects.Paycloseattentiontothisline:
throw new NullPointerException("demo");
•Here,newisusedtoconstructaninstanceofNullPointerException.
ManyofJava’sbuiltinrun-timeexceptionshaveatleasttwo
constructors:onewithnoparameterandonethattakesastring
parameter.
•Whenthesecondformisused,theargumentspecifiesastringthat
describestheexception.Thisstringisdisplayedwhentheobjectis
usedasanargumenttoprint()orprintln().Itcanalsobeobtained
byacalltogetMessage(),whichisdefinedbyThrowable.

throws:
•Ifamethodiscapableofcausinganexceptionthatitdoes
nothandle,itmustspecifythisbehaviorsothatcallersof
themethodcanguardthemselvesagainstthatexception.
Byincludingathrowsclauseinthemethod’sdeclaration.
Athrowsclauseliststhetypesofexceptionsthatamethod
mightthrow.Thisisnecessaryforallexceptions,except
thoseoftypeErrororRuntimeException,oranyoftheir
subclasses.
•Allotherexceptionsthatamethodcanthrowmustbe
declaredinthethrowsclause.Iftheyarenot,acompile-
timeerrorwillresult.

throws:
•Thegeneralformofamethoddeclarationthatincludesa
throwsclause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here,exception-listisacomma-separatedlistoftheexceptionsthata
methodcanthrow.

throws:...
•Anexampleofanincorrectprogramthattriestothrowanexception
thatitdoesnotcatch.Becausetheprogramdoesnotspecifyathrows
clausetodeclarethisfact,theprogramwillnotcompile.
Tomakethisexamplecompile,youneedto
maketwochanges.First,youneedtodeclare
that throwOne( ) throws
IllegalAccessException.Second,main()
mustdefineatry/catch
statementthatcatchesthisexception.

finally:
•Whenexceptionsarethrown,executioninamethodtakes
aratherabrupt,nonlinearpaththataltersthenormalflow
throughthemethod.
•Dependinguponhowthemethodiscoded,itiseven
possibleforanexceptiontocausethemethodtoreturn
prematurely.Thiscouldbeaprobleminsomemethods.
•Eg:Ifamethodopensafileuponentryandclosesitupon
exit,thenyouwillnotwantthecodethatclosesthefileto
bebypassedbytheexception-handlingmechanism.The
finallykeywordisdesignedtoaddressthiscontingency.

finally:...
•finallycreatesablockofcodethatwillbeexecutedafteratry/catch
blockhascompletedandbeforethecodefollowingthetry/catch
block.
•Thefinallyblockwillexecutewhetherornotanexceptionis
thrown.Ifanexceptionisthrown,thefinallyblockwillexecute
evenifnocatchstatementmatchestheexception.
•Anytimeamethodisabouttoreturntothecallerfrominsidea
try/catchblock,viaanuncaughtexceptionoranexplicitreturn
statement,thefinallyclauseisalsoexecutedjustbeforethemethod
returns.Thiscanbeusefulforclosingfilehandlesandfreeingupany
otherresourcesthatmighthavebeenallocatedatthebeginningofa
methodwiththeintentofdisposingofthembeforereturning.The
finallyclauseisoptional.However,eachtrystatementrequiresat
leastonecatchorafinallyclause.

finally:...
REMEMBERIfafinallyblockisassociatedwithatry,thefinallyblock
willbeexecuteduponconclusionofthetry.
Inthisexample,procA()prematurelybreaksoutofthe
trybythrowinganexception.Thefinallyclauseis
executedonthewayout.procB()’strystatementis
exitedviaareturnstatement.
ThefinallyclauseisexecutedbeforeprocB()returns.
InprocC(),thetrystatementexecutesnormally,
withouterror.However,thefinallyblockisstill
executed.

Java’sBuilt-inExceptions:
•Insidethestandardpackagejava.lang,Javadefinesseveralexception
classes.Afewhavebeenusedbytheprecedingexamples.Themost
generaloftheseexceptionsaresubclassesofthestandardtype
RuntimeException.Aspreviouslyexplained,theseexceptionsneed
notbeincludedinanymethod’sthrowslist.InthelanguageofJava,
thesearecalleduncheckedexceptionsbecausethecompilerdoesnot
checktoseeifamethodhandlesorthrowstheseexceptions.
•Theuncheckedexceptionsdefinedinjava.langarelisted,liststhose
exceptionsdefinedbyjava.langthatmustbeincludedinamethod’s
throwslistifthatmethodcangenerateoneoftheseexceptionsand
doesnothandleititself.Thesearecalledcheckedexceptions.Java
definesseveralothertypesofexceptionsthatrelatetoitsvarious
classlibraries.

Java’sBuilt-inExceptions:...

Java’sBuilt-inExceptions:...

CreatingourOwnExceptionSubclasses:
•Auserdefinedexceptionshouldbeasubclassof
theexceptionclass.
•TheExceptionclassdoesnotdefineanymethods
ofitsown.Itdoes,ofcourse,inheritthosemethods
providedbyThrowable.Thus,allexceptions,
includingthosethatyoucreate,havethemethods
definedbyThrowableavailabletothem.

CreatingourOwnExceptionSubclasses:...

UsingExceptions:
•Exceptionhandlingprovidesapowerfulmechanismfor
controllingcomplexprogramsthathavemanydynamic
run-timecharacteristics.
•Itisimportanttothinkoftry,throw,andcatchasclean
waystohandleerrorsandunusualboundaryconditionsin
ourprogram’slogic.
•Unlikesomeotherlanguagesinwhicherrorreturncodes
areusedtoindicatefailure,Javausesexceptions.Thus,
whenamethodcanfail,haveitthrowanexception.Thisis
acleanerwaytohandlefailuremodes.
•Onelastpoint:Java’sexception-handlingstatements
shouldnotbeconsideredageneralmechanismfornonlocal
branching.

Multithreading
PreparedusingfollowingResources:
➢Herbert Schildt, “Java: The Complete Reference”,Tata McGrawHillEducation
➢E Balagurusamy, Programming with Java -ATata McGraw Hill Education
➢https://www.geeksforgeeks.org/java/
➢https://www.javatpoint.com/java-tutorial
➢https://www.tutorialspoint.com/java/index.htm
➢https://www.w3schools.com/java/
By: DIVAKARA .N

•BasicsofMultithreading
•Mainthread
•Threadlifecycle
•Creationofmultiplethreads
•Threadpriorities
•Threadsynchronization
•Inter-threadcommunication
•Deadlocksforthreads
•Suspending&Resumingthreads

Basics:
•Unlikemanyothercomputerlanguages,Javaprovides
built-insupportformultithreadedprogramming.
•Amultithreadedprogramcontainstwoormorepartsthat
canrunconcurrently.Eachpartofsuchaprogramiscalled
athread,andeachthreaddefinesaseparatepathof
execution.
•Thus,multithreadingisaspecializedformofmultitasking.
•Youarealmostcertainlyacquaintedwithmultitasking,
becauseitissupportedbyvirtuallyallmodernoperating
systems.However,therearetwodistincttypesof
multitasking:processbasedandthread-based.

Basics:…
•PROCESS-BASEDMULTITASKING
•Aprocessisaprogramthatisexecuting.Thus,process-
basedmultitaskingisthefeaturethatallowsourcomputer
toruntwoormoreprogramsconcurrently.
•Forexample,process-basedmultitaskingenablesyouto
runtheJavacompileratthesametimethatyouareusinga
texteditor.
•Inprocessbasedmultitasking,aprogramisthesmallest
unitofcodethatcanbedispatchedbythescheduler.

Basics:…
•THREAD-BASEDMULTITASKING
•Inathread-basedmultitaskingenvironment,thethreadis
thesmallestunitofdispatchablecode.Thismeansthata
singleprogramcanperformtwoormoretasks
simultaneously.
•Forinstance,atexteditorcanformattextatthesametime
thatitisprinting,aslongasthesetwoactionsarebeing
performedbytwoseparatethreads.

Basics:…
THREAD-BASED vs.PROCESS-BASED MULTITASKING
•Multitaskingthreadsrequirelessoverheadthanmultitasking
processes.
•Processesareheavyweighttasksthatrequiretheirownseparate
addressspaces.Interprocesscommunicationisexpensiveand
limited.Contextswitchingfromoneprocesstoanotherisalsocostly.
•Threads,ontheotherhand,arelightweight.Theysharethesame
addressspaceandcooperativelysharethesameheavyweight
process.Interthreadcommunicationisinexpensive,andcontext
switchingfromonethreadtothenextislowcost.
•WhileJavaprogramsmakeuseofprocessbasedmultitasking
environments,process-basedmultitaskingisnotunderthecontrolof
Java.

Basics:…
THREAD-BASED vs.PROCESS-BASED MULTITASKING…
•Multithreadingenablesyoutowriteveryefficientprogramsthat
makemaximumuseoftheCPU,becauseidletimecanbekepttoa
minimum.Thisisespeciallyimportantfortheinteractive,networked
environmentinwhichJavaoperates,becauseidletimeiscommon.
•Forexample,thetransmissionrateofdataoveranetworkismuch
slowerthantherateatwhichthecomputercanprocessit.Evenlocal
filesystemresourcesarereadandwrittenatamuchslowerpacethan
theycanbeprocessedbytheCPU.
•And,ofcourse,userinputismuchslowerthanthecomputer.Ina
single-threadedenvironment,ourprogramhastowaitforeachof
thesetaskstofinishbeforeitcanproceedtothenextone—even
thoughtheCPUissittingidlemostofthetime.Multithreadinglets
yougainaccesstothisidletimeandputittogooduse.

•TheJavaThreadModel
•TheJavarun-timesystemdependsonthreadsformany
things,andalltheclasslibrariesaredesignedwith
multithreadinginmind.Infact,Javausesthreadstoenable
theentireenvironmenttobeasynchronous.Thishelps
reduceinefficiencybypreventingthewasteofCPUcycles.
•Thevalueofamultithreadedenvironmentisbest
understoodincontrasttoitscounterpart.Single-threaded
systemsuseanapproachcalledaneventloopwithpolling.
•ThebenefitofJava’smultithreadingisthatthemain
loop/pollingmechanismiseliminated.Onethreadcan
pausewithoutstoppingotherpartsofyourprogram.

•TheJavaThreadModel...
•Eg:Theidletimecreatedwhenathreadreadsdatafromanetworkorwaitsfor
userinputcanbeutilizedelsewhere.
•Multithreadingallowsanimationloopstosleepforasecondbetweeneachframe
withoutcausingthewholesystemtopause.WhenathreadblocksinaJava
program,onlythesinglethreadthatisblockedpauses.Allotherthreadscontinueto
run.
AdvantageofJavaMultithreading:
•Itdoesn'tblocktheuserbecausethreadsareindependentandyou
canperformmultipleoperationsatsametime.
•Youcanperformmanyoperationstogethersoitsavestime.
•Threadsareindependentsoitdoesn'taffectotherthreadsif
exceptionoccurinasinglethread.

•TheJavaThreadModel...
•LifeCycleofaThread:
•Threadsexistinseveralstates.Athreadcanberunning.
•ItcanbereadytorunassoonasitgetsCPUtime.
•Arunningthreadcanbesuspended,whichtemporarilysuspends
itsactivity.
•Asuspendedthreadcanthenberesumed,allowingittopickup
whereitleftoff.
•Athreadcanbeblockedwhenwaitingforaresource.
•Atanytime,athreadcanbeterminated,whichhaltsits
executionimmediately.
•Onceterminated,athreadcannotberesumed.

•TheJavaThreadModel...
•LifeCycleofaThread:...

•TheJavaThreadModel...
ThreadPriorities
•Javaassignstoeachthreadaprioritythatdetermineshow
thatthreadshouldbetreatedwithrespecttotheothers.
•Threadprioritiesareintegersthatspecifytherelative
priorityofonethreadtoanother.Asanabsolutevalue,a
priorityismeaningless;ahigher-prioritythreaddoesn’trun
anyfasterthanalower-prioritythreadifitistheonly
threadrunning.
•Instead,athread’spriorityisusedtodecidewhentoswitch
fromonerunningthreadtothenext.Thisiscalledacontext
switch.

•TheJavaThreadModel...
ThreadPriorities...
•Therulesthatdeterminewhenacontextswitchtakesplace
aresimple:
➢Athreadcanvoluntarilyrelinquishcontrol.Thisisdoneby
explicitlyyielding,sleeping,orblockingonpendingI/O.Inthis
scenario,allotherthreadsareexamined,andthehighest-priority
threadthatisreadytorunisgiventheCPU.
➢Athreadcanbepreemptedbyahigher-prioritythread.Inthis
case,alower-prioritythreadthatdoesnotyieldtheprocessoris
simplypreempted-nomatterwhatitisdoing-byahigher-
prioritythread.Basically,assoonasahigher-prioritythread
wantstorun,itdoes.Thisiscalledpreemptivemultitasking.

•TheJavaThreadModel...
ThreadPriorities...
•Incaseswheretwothreadswiththesamepriorityarecompetingfor
CPUcycles,thesituationisabitcomplicated.Foroperatingsystems
suchasWindows,threadsofequalpriorityaretime-sliced
automaticallyinround-robinfashion.Forothertypesofoperating
systems,threadsofequalprioritymustvoluntarilyyieldcontrolto
theirpeers.Iftheydon’t,theotherthreadswillnotrun.
•Javathreadprioritiesareintherangebetween
MIN_PRIORITY(aconstantof1)andMAX_PRIORITY
(aconstantof10).Bydefault,everythreadisgivenpriority
NORM_PRIORITY(aconstantof5).

•TheJavaThreadModel...
Synchronization
•Becausemultithreadingintroducesanasynchronousbehaviortoyour
programs,theremustbeawayforyoutoenforcesynchronicitywhen
youneedit.
•Forexample,ifyouwanttwothreadstocommunicateandsharea
complicateddatastructure,suchasalinkedlist,youneedsomeway
toensurethattheydon’tconflictwitheachother.Thatis,youmust
preventonethreadfromwritingdatawhileanotherthreadisinthe
middleofreadingit.
•Forthispurpose,Javaimplementsaneleganttwistonanage-old
modelofinter-processsynchronization:themonitor.
•ThemonitorisacontrolmechanismfirstdefinedbyC.A.R.Hoare.

•TheJavaThreadModel...
Synchronization...
•Amonitorisaverysmallboxthatcanholdonlyonethread.Oncea
threadentersamonitor,allotherthreadsmustwaituntilthatthread
exitsthemonitor.Inthisway,amonitorcanbeusedtoprotecta
sharedassetfrombeingmanipulatedbymorethanonethreadata
time.
•Mostmultithreadedsystemsexposemonitorsasobjectsthatyour
programmustexplicitlyacquireandmanipulate.
•The synchronization is mainly used to,
To prevent thread interference.
To prevent consistency problem.

•TheJavaThreadModel...
Synchronization...
•Javaprovidesacleanersolution.Thereisnoclass
“Monitor”;instead,eachobjecthasitsownimplicit
monitorthatisautomaticallyenteredwhenoneofthe
object’ssynchronizedmethodsiscalled.
•Onceathreadisinsideasynchronizedmethod,noother
threadcancallanyothersynchronizedmethodonthe
sameobject.Thisenablesyoutowriteveryclearand
concisemultithreadedcode,becausesynchronization
supportisbuiltintothelanguage.

•TheJavaThreadModel...
Messaging
•Afteryoudivideyourprogramintoseparatethreads,youneedto
definehowtheywillcommunicatewitheachother.When
programmingwithmostotherlanguages,youmustdependonthe
operatingsystemtoestablishcommunicationbetweenthreads.This,
ofcourse,addsoverhead.
•Bycontrast,Javaprovidesaclean,low-costwayfortwoor
morethreadstotalktoeachother,viacallstopredefined
methodsthatallobjectshave.
•Java’smessagingsystemallowsathreadtoentera
synchronizedmethodonanobject,andthenwaitthere
untilsomeotherthreadexplicitlynotifiesittocomeout.

•TheJavaThreadModel...
TheThreadClassandtheRunnableInterface
•Java’smultithreadingsystemisbuiltupontheThread
class,itsmethods,anditscompanioninterface,Runnable.
•Threadencapsulatesathreadofexecution.Sinceyoucan’t
directlyrefertotheetherealstateofarunningthread,you
willdealwithitthroughitsproxy,theThreadinstancethat
spawnedit.
•Tocreateanewthread,yourprogramwilleitherextend
ThreadorimplementtheRunnableinterface.

•TheJavaThreadModel...
TheThreadClassandtheRunnableInterface...
•TheThreadclassdefinesseveralmethodsthathelpmanagethreads.

•TheMainthread
•WhenaJavaprogramstartsup,onethreadbeginsrunning
immediately.Thisisusuallycalledthemainthreadofyour
program,becauseitistheonethatisexecutedwhenyour
programbegins.
•Themainthreadisimportantfortworeasons:
✓Itisthethreadfromwhichother“child”threadswillbe
spawned.
✓Often,itmustbethelastthreadtofinishexecution
becauseitperformsvariousshutdownactions.

•TheMainthread...
•Althoughthemainthreadiscreatedautomaticallywhen
yourprogramisstarted,itcanbecontrolledthrougha
Threadobject.Todoso,youmustobtainareferencetoit
bycallingthemethodcurrentThread(),whichisapublic
staticmemberofThread.
•TheGeneralformofthemethodcurrentThread()
static Thread currentThread( )
•Thismethodreturnsareferencetothethreadinwhichitis
called.Onceyouhaveareferencetothemainthread,you
cancontrolitjustlikeanyotherthread.

•TheMainthread...
•Eg:

•TheMainthread...
•Eg:
•Inthisprogram,areferencetothecurrentthread(themainthread,in
thiscase)isobtainedbycallingcurrentThread(),andthisreference
isstoredinthelocalvariablet.Next,theprogramdisplays
informationaboutthethread.TheprogramthencallssetName()to
changetheinternalnameofthethread.Informationaboutthethreadis
thenredisplayed.Next,aloopcountsdownfromfive,pausingone
secondbetweeneachline.Thepauseisaccomplishedbythesleep()
method.Theargumenttosleep()specifiesthedelayperiodin
milliseconds.Noticethetry/catchblockaroundthisloop.Thesleep(
)methodinThreadmightthrowanInterruptedException.This
wouldhappenifsomeotherthreadwantedtointerruptthissleeping
one.Thisexamplejustprintsamessageifitgetsinterrupted.Inareal
program,youwouldneedtohandlethisdifferently.

•TheMainthread...
•Eg:
•Noticetheoutputproducedwhentisusedasanargumentto
println().
•Thisdisplays,inorder:thenameofthethread,itspriority,andthe
nameofitsgroup.Bydefault,thenameofthemainthreadismain.
Itspriorityis5,whichisthedefaultvalue,andmainisalsothe
nameofthegroupofthreadstowhichthisthreadbelongs.
•Athreadgroupisadatastructurethatcontrolsthestateofa
collectionofthreadsasawhole.
•Afterthenameofthethreadischanged,tisagainoutput.This
time,thenewnameofthethreadisdisplayed.

•Threadlifecycle
•As the process has several states, similarly a thread exists in several states. A thread can be in the
following states:
✓Ready to run (New):First time as soon as it gets CPU time.
✓Running: Under execution.
✓Suspended:Temporarily not active or under execution.
✓Blocked: Waiting for resources.
✓Resumed: Suspended thread resumed, and start from where it left off.
✓Terminated:Halts the execution immediately and never resumes.

•CreatingaThread
➢ImplementingRunnable
➢ExtendingThread
➢ChoosinganApproach
Creating a Thread
•Onecancreateathreadbyinstantiatinganobject
oftypeThread.
•Javadefinestwowaysinwhichthreadcanbe
accomplished:byimplementingtheRunnable
interfaceandbyextendingtheThreadclass.

•CreatingaThread...
ImplementingRunnable:
•Theeasiestwaytocreateathreadistocreateaclassthat
implementstheRunnableinterface.
•Runnableabstractsaunitofexecutablecode.Youcan
constructathreadonanyobjectthatimplements
Runnable.
•ToimplementRunnable,aclassneedonlyimplementa
singlemethodcalledrun(),whichisdeclaredlikethis:
public void run( )

•CreatingaThread...
ImplementingRunnable:...
•Insiderun(),youwilldefinethecodethatconstitutesthenew
thread.Itisimportanttounderstandthatrun()cancallother
methods,useotherclasses,anddeclarevariables,justlikethe
mainthreadcan.
•Theonlydifferenceisthatrun()establishestheentrypointfor
another,concurrentthreadofexecutionwithinyourprogram.
Thisthreadwillendwhenrun()returns.
•AfteryoucreateaclassthatimplementsRunnable,youwill
instantiateanobjectoftypeThreadfromwithinthatclass.
Threaddefinesseveralconstructors.Theonethatwewilluseis
shownhere:Thread(RunnablethreadOb,StringthreadName)

•CreatingaThread...
ImplementingRunnable:...
•Afterthenewthreadiscreated,itwillnotstartrunninguntilyoucall
itsstart()method,whichisdeclaredwithinThread.Inessence,
start()executesacalltorun().
•Thestart()methodisshownhere:voidstart()

•CreatingaThread...
ImplementingRunnable:...

•CreatingaThread...
ExtendingThread:
•Thesecondwaytocreateathreadistocreateanewclass
thatextendsThread,andthentocreateaninstanceofthat
class.
•Theextendingclassmustoverridetherun()method,
whichistheentrypointforthenewthread.
•Itmustalsocallstart()tobeginexecutionofthenew
thread.

•CreatingaThread...
ExtendingThread:...

•CreatingaThread...
ChoosinganApproach:
•Atthispoint,youmightbewonderingwhyJavahastwowaystocreatechild
threads,andwhichapproachisbetter.Theanswerstothesequestionsturnonthe
samepoint.
•TheThreadclassdefinesseveralmethodsthatcanbeoverriddenby
aderivedclass.Ofthesemethods,theonlyonethatmustbe
overriddenisrun().Thisis,ofcourse,thesamemethodrequired
whenyouimplementRunnable.
•ManyJavaprogrammersfeelthatclassesshouldbeextendedonly
whentheyarebeingenhancedormodifiedinsomeway.So,ifyou
willnotbeoverridinganyofThread’sothermethods,itisprobably
bestsimplytoimplementRunnable.

•Creationofmultiplethreads

•UsingisAlive()andjoin()
•Howcanonethreadknowwhenanotherthreadhasended?
Fortunately,Threadprovidesameansbywhichyoucan
answerthisquestion.Twowaysexisttodeterminewhether
athreadhasfinished.
•First,youcancallisAlive()onthethread.Thismethodis
definedbyThread,anditsgeneralformisshownhere:
final booleanisAlive( )
•TheisAlive()methodreturnstrueifthethreaduponwhich
itiscalledisstillrunning.Itreturnsfalseotherwise.

•UsingisAlive()andjoin()...
•WhileisAlive()isoccasionallyuseful,themethodthatyou
willmorecommonlyusetowaitforathreadtofinishis
calledjoin(),shownhere:
final void join( ) throws InterruptedException
•Thismethodwaitsuntilthethreadonwhichitiscalled
terminates.Itsnamecomesfromtheconceptofthecalling
threadwaitinguntilthespecifiedthreadjoinsit.
•Additionalformsofjoin()allowyoutospecifya
maximumamountoftimethatyouwanttowaitforthe
specifiedthreadtoterminate.

•UsingisAlive()andjoin()...

•UsingisAlive()andjoin()...

•Threadpriorities
•Tosetathread’spriority,usethesetPriority()method,
whichisamemberofThread.Thisisitsgeneralform:
final void setPriority(intlevel)
•Here,levelspecifiesthenewprioritysettingforthecallingthread.
•Thevalueoflevelmustbewithintherange
MIN_PRIORITY andMAX_PRIORITY.Currently,
thesevaluesare1and10,respectively.
•Toreturnathreadtodefaultpriority,specify
NORM_PRIORITY, whichiscurrently5.Thesepriorities
aredefinedasstaticfinalariableswithinThread.
•ToobtainthecurrentprioritysettingbycallingthegetPriority()
methodofThread,shownhere:finalintgetPriority()

•Threadpriorities...

•Threadsynchronization
•Whentwoormorethreadsneedaccesstoashared
resource,theyneedsomewaytoensurethattheresource
willbeusedbyonlyonethreadatatime.Theprocessby
whichthisisachievediscalledsynchronization.
•Ifyouhaveworkedwithsynchronizationwhenusingotherlanguages,suchasCor
C++,youknowthatitcanbeabittrickytouse.Thisisbecausetheselanguagesdo
not,themselves,supportsynchronization.Instead,tosynchronizethreads,your
programsneedtoutilizeoperatingsystemprimitives.
•Fortunately,becauseJavaimplementssynchronization
throughlanguageelements,mostofthecomplexity
associatedwithsynchronizationhasbeeneliminated.You
cansynchronizeyourcodeineitheroftwoways.Both
involvetheuseofthesynchronizedkeyword.

•Threadsynchronization...
UsingSynchronizedMethods:
•SynchronizationiseasyinJava,becauseallobjectshave
theirownimplicitmonitorassociatedwiththem.
•Toenteranobject’smonitor,justcallamethodthathas
beenmodifiedwiththesynchronizedkeyword.
•Whileathreadisinsideasynchronizedmethod,allother
threadsthattrytocallit(oranyothersynchronized
method)onthesameinstancehavetowait.
•Toexitthemonitorandrelinquishcontroloftheobjectto
thenextwaitingthread,theownerofthemonitorsimply
returnsfromthesynchronizedmethod.

•Threadsynchronization...
UsingSynchronizedMethods:...NotSynchronizedProgram

•Threadsynchronization...
UsingSynchronizedMethods:...
•To fix the preceding program, you must serialize access to call( ).
That is, you must restrict its access to only one thread at a time.
•To do this, you simply need to precede call( )’s definition
•with the keyword synchronized, as shown here:
class Callme{
synchronized void call(String msg) {
...
•This prevents other threads from entering call( ) while another thread
is using it. After synchronized has been added to call( ), the output
of the program is as follows:
[Hello]
[Synchronized]
[World]

•Threadsynchronization...
UsingSynchronizedMethods:...
•Anytimethatyouhaveamethod,orgroupofmethods,
thatmanipulatestheinternalstateofanobjectina
multithreadedsituation,youshouldusethe
synchronizedkeywordtoguardthestatefromrace
conditions.
•Remember,onceathreadentersanysynchronized
methodonaninstance,nootherthreadcanenterany
othersynchronizedmethodonthesameinstance.
•However,nonsynchronizedmethodsonthatinstance
willcontinuetobecallable.

•Threadsynchronization...
ThesynchronizedStatement:
•Whilecreatingsynchronizedmethodswithinclassesthatyoucreateisan
easyandeffectivemeansofachievingsynchronization,itwillnotworkin
allcases.
•Tounderstandwhy,considerthefollowing.Imaginethatyouwantto
synchronizeaccesstoobjectsofaclassthatwasnotdesignedfor
multithreadedaccess.Thatis,theclassdoesnotusesynchronized
methods.
•Further,thisclasswasnotcreatedbyyou,butbyathirdparty,andyoudo
nothaveaccesstothesourcecode.Thus,youcan’taddsynchronizedto
theappropriatemethodswithintheclass.
•Howcanaccesstoanobjectofthisclassbesynchronized?
Fortunately,thesolutiontothisproblemisquiteeasy:Yousimply
putcallstothemethodsdefinedbythisclassinsidea
synchronizedblock.

•Threadsynchronization...
ThesynchronizedStatement:...
•Thisisthegeneralformofthesynchronizedstatement:
synchronized(object) {
// statements to be synchronized
}
Here, object is a reference to the object being synchronized.
•Asynchronizedblockensuresthatacalltoamethodthatis
amemberofobjectoccursonlyafterthecurrentthreadhas
successfullyenteredobject’smonitor.

•Threadsynchronization...
ThesynchronizedStatement:...

•Inter-threadcommunication
•Inter-threadcommunicationorCo-operationisall
aboutallowingsynchronizedthreadstocommunicatewith
eachother.
•Cooperation(Inter-threadcommunication)isamechanism
inwhichathreadispausedrunninginitscriticalsection
andanotherthreadisallowedtoenter(orlock)inthesame
criticalsectiontobeexecuted.
•ItisimplementedbyfollowingmethodsofObjectclass:
•wait()
•notify()
•notifyAll()

•Inter-threadcommunication...
•Thesemethodshavebeenimplementedasfinalmethodsin
Object,sotheyareavailableinalltheclasses.
•Allthreemethodscanbecalledonlyfromwithina
synchronizedcontext.

•Inter-threadcommunication...

•Deadlocksforthreads
•Deadlockinjavaisapartofmultithreading.Deadlockcanoccurin
asituationwhenathreadiswaitingforanobjectlock,thatis
acquiredbyanotherthreadandsecondthreadiswaitingforan
objectlockthatisacquiredbyfirstthread.Since,boththreadsare
waitingforeachothertoreleasethelock,theconditioniscalled
deadlock.
•Deadlockdescribesasituationwheretwoormorethreadsare
blockedforever,waitingforeachother.Deadlockoccurswhen
multiplethreadsneedthesamelocksbutobtainthemindifferent
order.AJavamultithreadedprogrammaysufferfromthe
deadlockconditionbecausethesynchronizedkeyword
causestheexecutingthreadtoblockwhilewaitingforthe
lock,ormonitor,associatedwiththespecifiedobject.

•Deadlocksforthreads...DeadlockSituation
Whenyoucompileandexecuteabove
program,youfindadeadlocksituation
andbelowistheoutputproducedbythe
program:
Thread1:Holdinglock1...
Thread2:Holdinglock2...
Thread1:Waitingforlock2...
Thread2:Waitingforlock1...
Theprogramwillhangforeverbecause
neitherofthethreadsinpositionto
proceedandwaitingforeachotherto
releasethelock,soyoucancomeoutof
theprogrambypressingCTRL-C.

•Deadlocksforthreads...Solution
Sojustchangingtheorderofthelocks
preventtheprogramingoingdeadlock
situationandcompleteswiththe
followingresult:
Thread1:Holdinglock1...
Thread1:Waitingforlock2...
Thread1:Holdinglock1&2...
Thread2:Holdinglock1...
Thread2:Waitingforlock2...
Thread2:Holdinglock1&2...

•Suspending&Resumingthreads/
Suspending,Resuming,andStoppingThreads
•CoreJavaprovidesacompletecontrolovermultithreadedprogram.
Youcandevelopamultithreadedprogramwhichcanbesuspended,
resumedorstoppedcompletelybasedonyourrequirements.
•Therearevariousstaticmethodswhichyoucanuseonthreadobjects
tocontroltheirbehavior.

•Suspending&Resumingthreads/
Suspending,Resuming,andStoppingThreads...

•UsingMultithreading
•ThekeytoutilizingJava’smultithreadingfeatures
effectivelyistothinkconcurrentlyratherthanserially.For
example,whenyouhavetwosubsystemswithinaprogram
thatcanexecuteconcurrently,makethemindividual
threads.
•Withthecarefuluseofmultithreading,youcancreatevery
efficientprograms.Awordofcautionisinorder,however:
Ifyoucreatetoomanythreads,youcanactuallydegrade
theperformanceofyourprogramratherthanenhanceit.
•Remember,someoverheadisassociatedwithcontext
switching.Ifyoucreatetoomanythreads,moreCPUtime
willbespentchangingcontextsthanexecutingyourprogram!

Applet Programming
PreparedusingfollowingResources:
➢Herbert Schildt, “Java: The Complete Reference”,Tata McGrawHillEducation
➢E Balagurusamy, Programming with Java -ATata McGraw Hill Education
➢https://www.geeksforgeeks.org/java/
➢https://www.javatpoint.com/java-tutorial
➢https://www.tutorialspoint.com/java/index.htm
➢https://www.w3schools.com/java/
By: DIVAKARA .N

•Introduction,HowAppletsDifferfrom
Applications,PreparingtoWriteApplets,
BuildingAppletCode,AppletLifeCycle,
CreatinganExecutableApplet,Designinga
WebPage,AppletTag,AddingAppletto
HTMLFile,RunningtheApplet,MoreAbout
AppletTag,PassingParameterstoApplets,
AligningtheDisplay,MoreAboutHTML
Tags,DisplayingNumericalValues,Getting
InputfromtheUser,EventHandling.

Introduction
Applet Fundamentals
•Appletsaresmallapplicationsthatareaccessedonan
Internetserver,transportedovertheInternet,automatically
installed,andrunaspartofawebdocument.
•Afteranappletarrivesontheclient,ithaslimitedaccessto
resourcessothatitcanproduceagraphicaluserinterface
andruncomplexcomputationswithoutintroducingtherisk
ofvirusesorbreachingdataintegrity.

Introduction...
Applet Fundamentals
•Thesimpleapplet:
importjava.awt.*;
importjava.applet.*;
publicclassSimpleAppletextendsApplet{
publicvoidpaint(Graphicsg){
g.drawString("ASimpleApplet",20,20);
}
}

Introduction...
Applet Fundamentals
•Thesimpleapplet:...
•Thisappletbeginswithtwoimportstatements.Thefirstimportsthe
AbstractWindowToolkit(AWT)classes.Appletsinteractwiththeuser
(eitherdirectlyorindirectly)throughtheAWT,notthroughtheconsole-
basedI/Oclasses.TheAWTcontainssupportforawindow-based,GUI.
Fortunately,thissimpleappletmakesverylimiteduseoftheAWT.(Applets
canalsouseSwingtoprovidetheGUI.)
•Thesecondimportstatementimportstheappletpackage,whichcontains
theclassApplet.EveryappletthatyoucreatemustbeasubclassofApplet.
•ThenextlineintheprogramdeclarestheclassSimpleApplet.Thisclass
mustbedeclaredaspublic,becauseitwillbeaccessedbycodethatis
outsidetheprogram.

Introduction...
Applet Fundamentals
•Thesimpleapplet:...
•InsideSimpleApplet,paint()isdeclared.Thismethodisdefinedbythe
AWTandmustbeoverriddenbytheapplet.paint()iscalledeachtime
thattheappletmustredisplayitsoutput.whenevertheappletmustredraw
itsoutput,paint()iscalled.
•Thepaint()methodhasoneparameteroftypeGraphics.Thisparameter
containsthegraphicscontext,whichdescribesthegraphicsenvironmentin
whichtheappletisrunning.Thiscontextisusedwheneveroutputtothe
appletisrequired.
•Insidepaint()isacalltodrawString(),whichisamemberofthe
Graphicsclass.ThismethodoutputsastringbeginningatthespecifiedX,Y
location.

Introduction...
Applet Fundamentals
•Thesimpleapplet:...
•Thegeneralform:voiddrawString(Stringmessage,intx,inty)
•Here,messageisthestringtobeoutputbeginningatx,y.InaJavawindow,
theupper-leftcornerislocation0,0.ThecalltodrawString()intheapplet
causesthemessage“ASimpleApplet”tobedisplayedbeginningat
location20,20.
•Noticethattheappletdoesnothaveamain()method.UnlikeJava
programs,appletsdonotbeginexecutionatmain().Infact,mostapplets
don’tevenhaveamain()method.Instead,anappletbeginsexecution
whenthenameofitsclassispassedtoanappletviewerortoanetwork
browser.

Introduction...
Applet Fundamentals
•Thesimpleapplet:...
•AfteryouenterthesourcecodeforSimpleApplet,compileinthesame
waythatyouhavebeencompilingprograms.However,running
SimpleAppletinvolvesadifferentprocess.Infact,therearetwowaysin
whichyoucanrunanapplet:
➢ExceutingtheappletwithinaJava-compatiblewebbrowser.
➢Usinganappletviewer,suchasthestandardtool,appletviewer.An
appletviewerexecutesyourappletinawindow.Thisisgenerallythe
fastestandeasiestwaytotestyourapplet.

Introduction...
Applet Fundamentals
•Thesimpleapplet:...
•Toexecuteanappletinawebbrowser,youneedtowriteashortHTML
textfilethatcontainsatagthatloadstheapplet.Currently,Sun
recommendsusingtheAPPLETtagforthispurpose.HereistheHTMLfile
thatexecutesSimpleApplet:
<appletcode="SimpleApplet"width=200height=60>
</applet>
•Thewidthandheightstatementsspecifythedimensionsofthedisplayarea
usedbytheapplet.(TheAPPLETtagcontainsseveralotheroptions.)After
youcreatethisfile,youcanexecuteyourbrowserandthenloadthisfile,
whichcausesSimpleApplettobeexecuted.

Introduction...
Applet Fundamentals
•Thesimpleapplet:...
•ToexecuteSimpleAppletwithanappletviewer,youmayalsoexecutethe
HTMLfileshownearlier.Forexample,iftheprecedingHTMLfileis
calledRunApp.html,thenthefollowingcommandlinewillrun
SimpleApplet:
C:\>appletviewerRunApp.html

Introduction...
Applet Fundamentals
•Thesimpleapplet:...
However,amoreconvenientmethod
existsthatyoucanusetospeedup
testing.Simplyincludeacomment
attheheadofyourJavasourcecode
filethatcontainstheAPPLETtag.
Bydoingso,yourcodeisdocumented
withaprototypeofthenecessaryHTML
statements,andyoucantestyour
compiledappletmerelybystartingthe
appletviewerwithyourJavasource
codefile.Ifyouusethismethod,the
SimpleAppletsourcefilelookslikethis:

Introduction...
Applet Fundamentals
•Thesimpleapplet:...
•Withthisapproach,wecanquicklyiteratethroughappletdevelopmentby
usingthesethreesteps:
1)EditaJavasourcefile.
2)Compileyourprogram.
3)Executetheappletviewer,specifyingthenameofyourapplet’ssource
file.TheappletviewerwillencountertheAPPLETtagwithinthe
commentandexecuteyourapplet.

Introduction...
Applet Fundamentals
•Thesimpleapplet:...
•ThewindowproducedbySimpleApplet,asdisplayedbytheappletviewer,isshowninthe
followingillustration:
•Thekeypointsthatyoushouldremembernow:
•Appletsdonotneedamain()method.
•AppletsmustberununderanappletvieweroraJava-compatiblebrowser.
•UserI/OisnotaccomplishedwithJava’sstreamI/Oclasses.Instead,
appletsusetheinterfaceprovidedbytheAWTorSwing.

Introduction
•Javaprogramsaredividedintotwomaincategories,
appletsandapplications.
•AnapplicationisanordinaryJavaprogram.
•AnappletisakindofJavaprogramthatcanberunacross
theInternet.
•AppletsaresmallJavaprogramsthatareembeddedinWeb
pages.
•TheycanbetransportedovertheInternetfromone
computer(webserver)toanother(clientcomputers).
•Theytransformwebintorichmediaandsupportthe
deliveryofapplicationsviatheInternet.

Introduction...
•Allappletsaresubclasses(eitherdirectlyorindirectly)of
Applet.Appletsarenotstand-aloneprograms.Instead,
theyrunwithineitherawebbrowseroranappletviewer.
•Theillustrationsshowninthischapterwerecreatedwith
thestandardappletviewer,calledappletviewer,provided
bytheJDK.
•Butyoucanuseanyappletviewerorbrowseryoulike.
Executionofanappletdoesnotbeginatmain().Actually,
fewappletsevenhavemain()methods.
•Instead,executionofanappletisstartedandcontrolled
withanentirelydifferentmechanism.

Advantages
•Therearemanyadvantages:
➢Itworksatclientsidesolessresponsetime.
➢Secured
➢Itcanbeexecutedbybrowsersrunningundermanyplatforms,
includingLinux,Windows,MacOsetc.
Drawback
•Plug-inisrequiredatclientbrowsertoexecuteapplet.

HowAppletsDifferfromApplications
•AlthoughboththeAppletsandstand-aloneapplicationsareJava
programs,therearecertainrestrictionsareimposedonAppletsdueto
securityconcerns:
➢Appletsdon’tusethemain()method,butwhentheyareload,automatically
callcertainmethods(init,start,paint,stop,destroy).
➢Theyareembeddedinsideawebpageandexecutedinbrowsers.
➢Theycannotreadfromorwritetothefilesonlocalcomputer.
➢Theycannotcommunicatewithotherserversonthenetwork.
➢Theycannotrunanyprogramsfromthelocalcomputer.
➢Theyarerestrictedfromusinglibrariesfromotherlanguages.
•TheaboverestrictionsensuresthatanAppletcannotdoanydamage
tothelocalsystem.

BuildingAppletCode:AnExample
//HelloWorldApplet.java
import java.applet.Applet;
import java.awt.*;
public class HelloWorldAppletextends Applet {
public void paint(Graphics g) {
g.drawString("Hello World of Java!",25, 25);
}
}

EmbeddingAppletinWebPage
<HTML>
<HEAD>
<TITLE>
Hello World Applet
</TITLE>
</HEAD>
<body>
<h1>Hi, This is My First Java Applet on the Web!</h1>
<APPLET CODE="HelloWorldApplet.class" width=500 height=400>
</APPLET>
</body>
</HTML>

AccessingWebpage(runsApplet)

AnAppletSkeleton/AppletLifeCycle
•Allbutthemosttrivialappletsoverrideasetofmethods
thatprovidesthebasicmechanismbywhichthebrowseror
appletviewerinterfacestotheappletandcontrolsits
execution.
•Fourofthesemethods,init(),start(),stop(),and
destroy(),applytoallappletsandaredefinedby
Applet.
•Defaultimplementationsforallofthesemethodsare
provided.Appletsdonotneedtooverridethosemethods
theydonotuse.However,onlyverysimpleappletswillnot
needtodefineallofthem.

AnAppletSkeleton/AppletLifeCycle...
•Everyappletinheritsasetof
defaultbehavioursfromthe
Appletclass.Asaresult,when
anappletisloaded,itundergoes
aseriesofchangesinitsstate.
Theappletstatesinclude:
➢Initialisation–invokesinit()
➢Running–invokesstart()
➢Display–invokespaint()
➢Idle–invokesstop()
➢Dead/DestroyedState–invokes
destroy()

AnAppletSkeleton/AppletLifeCycle...
•publicvoidinit():isusedtoinitializedtheApplet.Itisinvokedonlyonce.
•publicvoidstart():isinvokedaftertheinit()methodorbrowseris
maximized.ItisusedtostarttheApplet.
•publicvoidstop():isusedtostoptheApplet.ItisinvokedwhenAppletis
stoporbrowserisminimized.
•publicvoiddestroy():isusedtodestroytheApplet.Itisinvokedonly
once.

PassingParameterstoApplet
<HTML>
<HEAD>
<TITLE>
Hello World Applet
</TITLE>
</HEAD>
<body>
<h1>Hi, This is My First Communicating Applet on the Web!</h1>
<APPLET CODE="HelloAppletMsg.class" width=500 height=400>
<PARAM NAME="Greetings" VALUE="Hello Friend, How are you?">
</APPLET>
</body>
</HTML>

AppletProgramAcceptingParameters
//HelloAppletMsg.java
importjava.applet.Applet;
importjava.awt.*;
publicclassHelloAppletMsgextendsApplet{
Stringmsg;
publicvoidinit()
{
msg=getParameter("Greetings");
if(msg==null)
msg="Hello";
}
publicvoidpaint(Graphicsg){
g.drawString(msg,10,100);
}
}
Thisisnameofparameterspecifiedin
PARAMtag;Thismethodreturnsthe
valueofparamter.

Whathappenifwedon’tpassparameter?
SeeHelloAppletMsg1.html
<HTML>
<HEAD>
<TITLE>
Hello World Applet
</TITLE>
</HEAD>
<body>
<h1>Hi, This is My First Communicating Applet on the Web!</h1>
<APPLET CODE="HelloAppletMsg.class" width=500 height=400>
</APPLET>
</body>
</HTML>
getParameter()returns
null.Somedefaultvalue
maybeused.

DisplayingNumericValues
//SumNums.java
import java.applet.Applet;
import java.awt.*;
public class SumNumsextends Applet {
public void paint(Graphics g) {
intnum1 = 10;
intnum2 = 20;
intsum = num1 + num2;
String str= "Sum: "+String.valueOf(sum);
g.drawString(str,100, 125);
}
}
SumNums.html
<HTML>
<HEAD>
<TITLE>
Hello World Applet
</TITLE>
</HEAD>
<body>
<h1>Sum of Numbers</h1>
<APPLET CODE="SumNums.class" width=500 height=400>
</APPLET>
</body>
</HTML>

InteractiveApplet
•Appletsworkinagraphicalenvironment.Therefore,
appletstreatsinputsastextstrings.
•Weneedtocreateanareaonthescreeninwhichusecan
typeandeditinputitems.
•WecandothisusingTextFieldclassoftheappletpackage.
•Whendataisentered,aneventisgenerated.Thiscanbe
usedtorefreshtheappletoutputbasedoninputvalues.

InteractiveApplet...
//SumNumsInteractive..java
import java.applet.Applet;
import java.awt.*;
public class SumNumsInteractiveextends Applet {
TextFieldtext1, text2;
public void init()
{
text1 = new TextField(10);
text2 = new TextField(10);
text1.setText("0");
text2.setText("0");
add(text1);
add(text2);
}
public void paint(Graphics g) {
intnum1 = 0;
intnum2 = 0;
intsum;
String s1, s2, s3;
g.drawString("Input a number in each box ", 10, 50);
try {
s1 = text1.getText();
num1 = Integer.parseInt(s1);
s2 = text2.getText();
num2 = Integer.parseInt(s2);
}
catch(Exception e1)
{}
sum = num1 + num2;
String str = "THE SUM IS: "+String.valueOf(sum);
g.drawString (str,100, 125);
}
public boolean action(Event ev, Object obj)
{
repaint();
return true;
}
}

AppletandSecurity
•Anappletcanbeaprogram,writtenbysomeoneelse,that
runsonyourcomputer.
•Wheneversomeoneelse'sprogramrunsonyourcomputer,
therearesecurityquestionsyoushouldask:
➢Willitreadinformationfromyourfiles?
➢Willitcorruptyouroperatingsystem?
•Appletsaredesignedsothattheycannotdoanyofthese
things(atleasteasily).

Summary
•AppletsaredesignedtooperateinInternetandWeb
environment.
•TheyenablethedeliveryofapplicationsviatheWeb.
•Inthispresentationwelearned:
✓How do applets differ from applications?
✓Life cycles of applets
✓How to design applets?
✓How to execute applets?
✓How to provide interactive inputs?
Tags