Java2020 programming basics and fundamentals

swecsaleem 18 views 238 slides Jul 22, 2024
Slide 1
Slide 1 of 527
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
Slide 497
497
Slide 498
498
Slide 499
499
Slide 500
500
Slide 501
501
Slide 502
502
Slide 503
503
Slide 504
504
Slide 505
505
Slide 506
506
Slide 507
507
Slide 508
508
Slide 509
509
Slide 510
510
Slide 511
511
Slide 512
512
Slide 513
513
Slide 514
514
Slide 515
515
Slide 516
516
Slide 517
517
Slide 518
518
Slide 519
519
Slide 520
520
Slide 521
521
Slide 522
522
Slide 523
523
Slide 524
524
Slide 525
525
Slide 526
526
Slide 527
527

About This Presentation

java programmming


Slide Content

Programming Basics

Programming Basics
Procedural or Procedure Oriented Programming (POP)
1)ProcedureOrientedProgrammingcontainsstepbystep
proceduretoexecute.
2)Here,theproblemsgetdecomposedintosmallparts
andthentosolveeachpartoneormorefunctionsare
used.
3)ThusinPOPapproach,theproblemisviewedasa
sequenceofthingstobedone,suchas,inputtaking,
calculatinganddisplaying.
2

Programming Basics
Forexample,
Consideringthatwehavetotaketwovaluesfromuser
andthentodisplaythesummationoftheinputtedvalues.
InPOPapproachthisproblemmaybedecomposedas
following,
1)Firsttakeaninputandputitunderonevariable,here
takingasa.
2)Thentakeanotherinputandputitunderanother
variable,heretakingasb.
3)Nowdefineavariable,suchasc,asc=a+b.
4)Nowdisplayc.
3

Programming Basics
4

Difference between Compiler and Interpreter
Interpreter Compiler
Translatesprogramone
statementatatime.
Scanstheentireprogramand
translatesitasawholeintomachine
code.
Nointermediateobjectcodeis
generated,hencearememory
efficient.
Generatesintermediateobjectcode
whichfurtherrequireslinking,hence
requiresmorememory.
Continuestranslatingthe
programuntilthefirsterroris
met,inwhichcaseitstops.
Hencedebuggingiseasy.
Itgeneratestheerrormessageonly
afterscanningthewholeprogram.
Hencedebuggingiscomparatively
hard.
Programminglanguagelike
Python,Rubyuseinterpreters.
ProgramminglanguagelikeC,C++
usecompilers.
5

Difference between Compiler and Interpreter
6

Introduction To JAVA

8
Introduction To JAVA
Unit # 2 : Introduction to Java
What is Java?
History Of Java
Java Features
Java Installation
First Java Application
Types of Java Applications
Java Editions
Java Software Components
Interview Questions

9
Introduction To JAVA
What is JAVA?
Javaissimple,highperformance,object-oriented,robust,
secure,multi-threaded,andplatformindependentprogramming
languagetodevelopsoftwarethatcanbeusedforgaming,web,
business,desktop,database,andotherapplications.
DesigngoalofJavalanguageproject
Writeonce,runanywhere(WORA)–thatmeansjava
programcanrunanywhereandonanyplatform.Whenjavacodeis
compileditisconvertedintobytecode.Nowthisbytecodeis
neededtorunusingJVM,noneedofsourcecodeand
recompilation.

10
Introduction To JAVA
History Of Java
1.JAVAwasdevelopedbyJamesGoslingandPatrick
NaughtonfromSunMicrosystemsIncin1991,
later(2010)acquiredbyOracleCorporation.
2.ThedesigngoalofJavaisWORA(WriteOnce
Run/ExecuteAnywhere)itmeanswriteaprogramonce
andthenrunthisprogramonmultipleoperatingsystems.
3.ThefirstpubliclyavailableversionofJava(Java1.0)
wasreleasedin1995andthecurrentofversionofJavais
JavaSE11releasedonSeptember,25th2018

11
Introduction To JAVA
Features of JAVA?

12
Introduction To JAVA
Important Features Of Java
Simple
1)Itdoesnotuseheaderfiles.
2)Eliminatedtheuseofpointerandoperator
overloading.
3)Javaiseasytolearnandfamiliarbecausejava
syntaxisjustlikec++.
4)ThereisaprovisionofAutomaticGarbage
Collection,inwhichthereisnoneedtoremove
theunreferencedobjectsexplicitly.

Introduction To JAVA
Compiled and Interpreted
Usually,acomputerlanguagecanbeeithercompiledorinterpreted.
JavaintegratesthepowerofCompiledLanguageswiththe
flexibilityofInterpretedLanguages.
Javacompiler(javac)compilesthejavasourcecodeintothe
bytecode.
JavaVirtualMachine(JVM)thenexecutesthisbytecodewhichis
executableonmanyoperatingsystemsandisportable.
13

14
Introduction To JAVA
PlatformIndependent
1)Platform-independentmeansaprogramcompiledononemachinecanbe
executedonanymachineintheworldwithoutanychange.Javaachievesplatform
independencebyusingtheconceptoftheBYTEcode.
2)TheJavacompilerneverconvertsthesourcecodetomachinecodelikethatof
theC/C++compiler.Instead,itconvertsthesourcecodeintoanintermediatecode
calledthebytecodeandthisbytecodeisfurthertranslatedtomachine-dependent
formbyanotherlayerofsoftwarecalledJVM(JavaVirtualMachine).
3)Therefore,JVMcanexecutebytecodeonanyplatformorOSonwhichitis
present,regardlessofthefactthatonwhichmachinethebytecodewasgenerated.
4)Thisiswherethe“WriteOnce,runanywhere”(WORA)sloganforJavacomes
in,whichmeansthatwecandevelopapplicationsononeenvironment(OS)and
runonanyotherenvironmentwithoutdoinganymodificationinthecode.

15
Introduction To JAVA

Introduction To JAVA
Portable
YoucanrunJavabytecodeonanyhardwarethathasa
compliantJVMwhichcanconvertthebytecode
accordingtothatparticularmachine.
InJava,thesizeoftheprimitivedatatypesismachine-
independent,whichweredependentinthecaseofC/C++.
So,theseprovisionsmakeJavaprogramsportableamong
differentplatformssuchasWindows,Unix,Solaris,and
Mac.
Moreover,anychangesandupdatesmadeinOperating
Systems,ProcessorsandSystemresourceswillnot
enforceanychangesinJavaprograms.
16

17
Introduction To JAVA
Object Oriented Programming Language
1)Objectorientedprogrammingisawayof
organizingprogramsascollectionofobjects,each
ofobjectrepresentsaninstanceofaclass.
2)Javaprogramsalsoorganizingcollectionof
classesandobjectssoJavaiscalledasobject
orientedprogramminglanguage

18
Introduction To JAVA
Robust
Robustmeansinbuiltcapabilitiestohandle
errors/exceptions.
Javaisrobustbecauseoffollowing
1)Built-inExceptionhandling.
2)Strongtypecheckingi.e.alldatamustbe
declaredanexplicittype.
3)Automaticgarbagecollection.
4)Firstchecksthereliabilityofthecodebefore
Executionetc.

19
Introduction To JAVA
Secure
JavaprogramsrunwithintheJVMwhichprotects
fromunauthorizedaccesstosystemresources.
That’swhyseveralsecurityflawslikestack
corruptionorbufferoverflowisimpossibleto
exploitinJava.

20
Introduction To JAVA
Multithreading
Javasupportsmultithreading.Multithreadingisa
featurethatallowsconcurrentexecutionoftwoor
morepartsofaprogramformaximumutilization
ofCPU.

21
Introduction To JAVA
Distributed
ThisfeatureinJavagivestheadvantageofdistributed
programming,whichisveryhelpfulwhenwedeveloplarge
projects.Javahelpsustoachievethisbyprovidingtheconceptof
RMI(RemoteMethodInvocation)andEJB(EnterpriseJavaBeans).
InJava,wecansplitaprogramintomanypartsandstorethese
partsondifferentcomputers.AJavaprogrammersittingona
machinecanaccessanotherprogramrunningontheothermachine.
Javacomeswithanextensivelibraryofclassesforinteracting,
usingTCP/IPprotocolssuchasHTTPandFTP,whichmakes
creatingnetworkconnectionsmucheasierthaninC/C++.
Italsoenablesmultipleprogrammersatmanylocationstowork
togetheronasingleproject.

22
Introduction To JAVA
Architectural Neutral
Architecturalneutralmeansthattheprogramwrittenonone
platformisindependentofotherplatformsandcanrunonany
otherplatformwithoutrecompilingthem.
Byte-codeisnotdependentonanymachinearchitectureandJava
VirtualMachine(JVM)caneasilytranslatebytecodeintoa
machine-specificcode.
Dynamic
Theprocessofallocatingthememoryspacetotheinputofthe
programatarun-timeisknownasdynamicmemoryallocation.In
Javamemoryallocationhappenedatrun-timewiththehelpof'new'
operator.SoJavaisdynamic

23
Introduction To JAVA
High performance
Javaprovideshighperformancewiththeuseof“JIT–JustInTime
compiler”,inwhichthecompilercompilesthecodeon-demand
basis,thatis,itcompilesonlythatmethodwhichisbeingcalled.
Thissavestimeandmakesitmoreefficient.
Javaarchitectureisalsodesignedinsuchawaythatitreduces
overheadsduringruntime.Theinclusionofmultithreading
enhancestheoverallexecutionspeedofJavaprograms.
BytecodesgeneratedbytheJavacompilerarehighlyoptimized,so
JavaVirtualMachinecanexecutethemmuchfaster.

24
Introduction To JAVA
Components Of Java Software
Java Development Kit (JDK)
JavaDevelopmentKitcontainstwoparts.Onepart
containstheutilitieslikejavac,debuggerandsomejar
fileswhichhelpsincompilingthesourcecode(.java
files)intobytecode(.classfiles)anddebugtheprograms.
TheotherpartistheJRE,whichcontainstheutilitieslike
javawhichhelpinrunning/executingthebytecode.Ifwe
wanttowriteprogramsandrunthem,thenweneedthe
JDKinstalled.

25
Introduction To JAVA
Java Run-time Environment (JRE)
JavaRun-timeEnvironmenthelpsinrunningthe
programs.
JREcontainstheJVM,thejavaclasses/packages
andtherun-timelibraries.
Ifwedonotwanttowriteprograms,butonly
executetheprogramswrittenbyothers,thenJRE
alonewillbesufficient.

26
Introduction To JAVA
Java Virtual Machine (JVM)
JavaVirtualMachineisimportantpartoftheJRE,
whichactuallyrunstheprograms(.classfiles),it
usesthejavaclasslibrariesandtherun-time
librariestoexecutethoseprograms.
Everyoperatingsystem(OS)orplatformwillhave
adifferentJVM.

27
Introduction To JAVA
Just In Time Compiler (JIT)
JITisamoduleinsidetheJVMwhichhelpsin
compilingcertainpartsofbytecodeintothe
machinecodeforhigherperformance.

28
Introduction To JAVA

29
Introduction To JAVA
Editions Of Java Software
JavaSE (Java Standard/Software Edition)
JavaSEismainlyusedtocreateapplicationsfor
Desktopenvironment.
ItconsistallthebasicsofJavathelanguage,
variables,primitivedatatypes,Arrays,Streams,
StringsJavaDatabaseConnectivity(JDBC)and
muchmore.

30
Introduction To JAVA
JavaEE(Java Enterprise Edition)
TheenterpriseeditionofJavahasamuchlarger
usageofJava,likedevelopmentofweb
applications,networking,serversidescriptingand
othervariouswebbasedapplications.
JavaEEusesmanycomponentsofJavaSE,aswell
as,hasmanynewfeaturesofit’sownlike
Servlets,JavaBeans,JavaMessageServicesetc,.

31
Introduction To JAVA
JavaME (Java Micro/Mobile Edition)
ThisversionofJavaismainlyconcentratedforthe
applicationsrunningonembeddedsystems,
mobileswirelessdevices,settopboxesetc.
OldNokiaphones,whichusedSymbianOS,used
thistechnology.

First Java Application

33
First Java Application
Steps To Write First Java Program
Step 1:Decalre the class
Every java application must have at least one class
definition that consists of class keyword followed
by class name.
public class FirstJavaProgram
{
}

34
First Java Application
Step 2: Declare the main() method
ToexecutetheaboveclassJVMneedoneentrypointin
theclassthatentrypointismain()methodhaving
signatureasshownbelow
publicstaticvoidmain(String[]args){}

35
First Java Application
public–accessmodifier,meaningglobalvisibility
static–themethodcanbeaccessedstraightfromthe
class,wedon’thavetoinstantiateanobjecttohavea
referenceanduseit
void–meansthatthismethoddoesn’treturnavalue
main–thenameofthemethod,that’stheidentifierJVM
looksforwhenexecutingaJavaprogram
argsparameter,itrepresentsthevaluesreceivedbythe
method.

36
First Java Application
Step 3: Write logic
Writesomelogicorstatementtogeneratesimple
responseasshownbelow
System.out.println("Thisismyfirstprogramin
java");

37
First Java Application

38
First Java Application
Step 4:Save The File
Weshouldalwayssavethefilesameasthepublic
classname.
Inourprogram,thepublicclassnameis
FirstJavaProgram,that’swhyourfilenameshould
beFirstJavaProgram.java.

39
First Java Application
Step 5: Compile The Program
Wewillcompiletheprogram.Forthis,open
commandprompt(cmd)onWindowstypethe
followingcommandandhitenter.
javacFirstJavaProgram.java
Stpe6:ExecuteTheProgram
Aftercompilationthe.javafilegetstranslatedintothe
.classfile(bytecode).Nowwecanruntheprogram.To
runtheprogram,typethefollowingcommandandhit
enter:javaFirstJavaProgram

40
First JAVA Application
Java Compilation And Execution
1)IntheJavaprogramminglanguage,allsource
codeisfirstwrittenandsavewith
the.javaextension.
2)Aftercompilation,.classfilesaregenerated
byjavaccompiler.
3)A.classfilecontainbytecodethatisnot
naturaltoyourprocessor,thisbytecodeconvert
intoprocessorunderstandablecodebyJVM

41
First JAVA Application
Java Compilation and Execution

Naming Conventions in Java

Naming Conventions In Java
Identifiers
A name in the program is an identifier it may be class
name or method name, variable name or label name.
Example
Class Test{
public static void main(String[] args){
int x=10
System.out.println(x);
}
43

Naming Conventions In Java
Rules for defining Identifiers
1)Identifiersmuststartwithaletter,acurrencycharacter($),ora
connectingcharactersuchastheunderscore(_).
2)Identifierscannotstartwithanumber
3)Afterthefirstcharacter,identifierscancontainanycombination
ofletters,currencycharacters,connectingcharacters,or
numbers.
4)Inpractice,thereisnolimittothenumberofcharactersan
identifiercancontain.
5)Youcan'tuseaJavakeywordasanidentifier.
6)IdentifiersinJavaarecase-sensitive;fooandFOOaretwo
differentidentifiers.
44

Naming Conventions In Java
Coding standards for classes
Usuallyclassnameshouldbenoun.Shouldstartswith
uppercaseletterandifitcontainmultiplewordsevery
innerwordsalsoshouldstartwithcapitalletters.
Example:
String
StringBuffer
NumberFormat
CustomerInformation
45

Naming Conventions In Java
Coding standards for Interfaces
Usuallyinterfacenamedshouldbeadjective,startswith
capitallettersandifitcontainsmultiplewords,every
innerwordalsoshouldstartswithcapitalletter.
Example:
Runnable
Serializable
Clonable
Movable
Transferable
Workable
46

Naming Conventions In Java
Coding standards with methods
Valuesshouldbeeitherverbsorverb+noun
combination.
Startswithlowercaseandeveryinnerwordsstartswith
uppercase(thisconventionisalsocalledcamelcase
convention).
Example:
getName(), getMessage(), toString(), show(), display().
47

Naming Conventions In Java
Coding standards for variables
Usuallythevariablestartswithnounandeveryinner
wordshouldstartwithuppercasei.ecamelcase
convention.
Example:
name, rollNo, bandwidth, totalNumber.
48

Naming Conventions In Java
Codingstandardsforconstants
Itshouldbenoun,itshouldcontainonlyuppercase
lettersandworksareseparatedwithunderscores.
Example:
MAX_SIZE, MIN_PRIORITY, COLLEGE_NAME.
49

Data types, Literals and Variables in
Java

Data types in Java
Datatype
Incomputerscience,adatatypeisanattributeofdatathattellsthe
compilerorinterpreterhowtheprogrammeraimstousethedata.
JavaDataTypes
1)PrimitiveDataTypes
2)Non-PrimitiveDataTypes
PrimitiveDataTypes
Asthenamesuggests,theprogramminglanguagepre-definesthe
primitivedatatypes.Primitivetypesarethemostbasicdatatypes
availableinJava.
Thereare8primitivedatatypesinJava:byte,char,short,int,long,
float,doubleandboolean.
Primitivedatatypeshaveaconstraintthattheycanholddataofthe
sametypeandhaveafixedsize.
51

Data types in Java
52

Data types in Java
Non-Primitive Data Types/ Referenced Data Types
1)Thetermnon-primitivedatatypemeansthatthese
typescontain“amemoryaddressofthevariable”.
2)Incontrasttoprimitivedatatypes,whicharedefinedby
Java,non-primitivedatatypesarenotdefinedorcreated
byJavabuttheyarecreatedbytheprogrammers.They
arealsocalledReferencedatatypesbecausethey
cannotstorethevalueofavariabledirectlyinmemory.
3)Non-primitivedatatypesdonotstorethevalueitself
buttheystoreareferenceoraddress(memorylocation)
ofthatvalue.
53

Data types in Java
Java Integers
It can hold whole numbers such as 196, -52, 4036 etc. Java supports four
different types of integers These are:
54

Data types in Java
55

Data types in Java
56

Floating Point Numbers
Floating Representation
57

Single precision floating point number
Singleprecisionuses32bittorepresentafloatingpointnumber.
Firstbitrepresentthesignofthenumber,negativeorpositive.
Next8bitsareusedtostoretheexponentofthenumber.This
exponentcanbesigned8-bitintegerrangingfrom-127–128of
signedinteger(0to255).
Andtheleft23bitsareusedtorepresentthefractionpartandare
calledfractionbits.
8exponentbitsprovideuswiththerangeand23bitsprovideus
withtheactualprecision.
58

Double precision floating point number
Doubleprecisionuses64bitstorepresentavalue.
Firstbitisusedforthesamepurposeasinsinglepointprecision
i.e.,representssignofthenumber.
Next11bitsareusedtodenoteexponent,whichprovideuswith
therange,andhas3morebitsthansingleprecision,soitisused
torepresentawiderrangeofvalues.
Next52bitsareusedtorepresentthefractionalpartwhichis29
bitsmorethanbinary32bitrepresentationscheme.Soithasa
greaterprecisionthansingleprecision.
59

Data types in Java
60
Floating-Point Literals in Java
Here,datatypescanonlybespecifiedindecimalformsandnot
inoctalorhexadecimalform.

Data types in Java
Java Characters
Acharacterisusedtostorea‘single’character.Asinglequote
mustsurroundacharacter.ThevalidCharactertypeischar.In
Java,acharacterisnotan8-bitquantitybutherecharacteris
representedbya16-bitUnicode.
61
Syntax char myChar= ’A’ ;
Size 2 bytes(16 bits)
Values A single character representing a digit, letter,
or symbol.
Default Value ‘\u0000’ (0)
Range \u0000’ (0) to ‘\uffff’ (65535)

Data types in Java
Char Literals in Java
These are the four types of char
Single Quote
JavaLiteralcanbespecifiedtoachardatatypeasasingle
characterwithinasinglequote.
charch='a';
Char as Integral
A char literal in Java can specify as integral literal which also
represents the Unicode value of a character.
Furthermore, an integer can specify in decimal, octal and even
hexadecimal type, but the range is 0-65535.
char ch = 062;
62

Data Types in Java
Unicode Representation
Char literals can specify in Unicode representation ‘\uxxxx’. Here
XXXX represents 4 hexadecimal numbers.
char ch = '\u0061';// Here /u0061 represent a.
Escape Sequence
Escape sequences can also specify as char literal.
63

Data types in Java
boolean
•booleandatatyperepresentsonebitofinformationas
eithertrueorfalse.i.e.thereisonlytwopossiblevalue
trueorfalse.Internally,JVMusesonebitofstorageto
representabooleanvalue.
•Itisgenerallyusedtotestaparticularconditional
statementduringtheexecutionofprogram.
•booleandatatypetakeszerobytesofmemory.
•Defaultvalueisfalse.
For example:
boolean b = false;
64

Variables in Java
VariablesinJava
AvariableinJavaisakindofcontainerthatcontainsthevalue
duringprogramexecution.Variableisabasicunitofstorageina
programthatrepresentsreservedstoragelocations,whosevalues
canbemanipulatedduringtheexecutionofaprogram.
DeclarationofaVariable
Todeclarethevariable,wemustspecifythedatatypefollowedby
theuniquenameofthevariable.
Syntax:
dataTypevariableName
Example:
doublepayRate;
65

Variables in Java
Initialization of a Variable
Syntax:
variableName = value ;
Example:
payRate = 2500;
Combining the declaration and initialization, we can
write
dataType variableName = value ;
Example:
double area = 378.87 ;
66

Variables in Java
67

Variables in Java
Naming conventions for variables
1)Thevariablenamescannotcontainwhitespaces,forexample,
longdistance=1000;isinvalidbecausethevariablenamehasa
spaceinit.
2)Avariablenamecanbeginwithaspecialcharacterdollar($)and
underscore(_).
3)Thefirstletterofavariablecannotbeadigit.
4)Avariablenameshouldbeginwithalowercaseletter,for
example,intnumber.Forlengthyvariablenameshavingmore
thanoneword,wecanusecamelCase,forexample,int
salaryPerDay;floatrateOfInterest;,etc.arevalid.
5)Wecannotusekeywordslikeint,for,while,class,etcasa
variablename.
6)Variablenamesarecase-sensitiveinJava.
68

Type Promotion in Java
Type Promotion in Java
ThereareseveraltypepromotionrulesinJavathatare
followedwhileevaluatingexpressions-
1)Allbyte,shortandcharvaluesarepromotedtoint.
2)Ifanyoperandislongthentheexpressionresultislong.
i.e.wholeexpressionispromotedtolong.
3)Ifanyoperandisafloatthentheexpressionresultis
float.i.e.wholeexpressionisautomaticallypromotedto
float.
4)Ifanyoperandisadoublethentheexpressionresultis
double.i.e.wholeexpressionispromotedtodoublein
Java.
69

Type Promotion in Java
When one of the operand is double.
int i = 30;
double d = 2.5;
double result = i * d;
When one of the operand is float.
short s = 4;
int i = 30;
float f = 6.75f;
float result = (s+i) * f;
70

Type Casting in Java

Type Casting in Java
What is Type Casting or Type Conversion
TypeConversionorTypeCastingistheprocessof
convertingavariableofonepredefinedtypeintoanother.
Ifthesedatatypesarecompatiblewitheachother,the
compilerautomaticallyconvertsthemandiftheyarenot
compatible,thentheprogrammerneedstotypecastthem
explicitly.
72

Type Casting in Java
Types of Type Conversion
1)Implicit Type Conversion
2)Explicit Type Conversion
73

Type Casting in Java
Implicit Type Conversion
ImplicitTypeConversionorAutomatictypeconversionisaprocess
ofautomaticconversionofonedatatypetoanotherbythecompiler.
ThisprocessisalsocalledWideningConversionbecausethecompiler
convertsthevalueofnarrower(smallersize)datatypeintoavalueof
abroader(largersize)datatypewithoutlossofinformation.
Theimplicitdatatypeconversionispossibleonlywhen
1)Thetwodatatypesarecompatiblewitheachother.
2)Thereisaneedtoconvertasmallerornarrowerdatatypetothe
largertypesize.
Forexample,thecompilerautomaticallyconvertsbytetoshort
becausethebyteissmaller(8bits)ornarrowerthanshort(16bits).
74

Type Casting in Java
75

Type Casting in Java
Explicit Type Conversion
TheExplicitTypeConversionisaprocessofexplicitly
convertingatypetoaspecifictype.Wealsocallit
NarrowingConversion.Thetypecastingisdonemanually
bytheprogrammer,andnotbythecompiler.Weneedto
doexplicitornarrowingtypeconversionwhenthevalue
ofabroader(highersize)datatypeneedstobeconverted
toavalueofanarrower(lowersize)datatype.
Forexample,doubledatatypeexplicitlyconvertedinto
inttype.
76

Type Casting in Java
ThefollowingisthesyntaxoftypecastinginJava
(type)expression;
Wheretypeisavaliddatatypetowhichtheconversionis
tobedone.
Forexample,ifwewanttomakesurethattheexpression
(x/y+5)evaluatestotypefloat,wewillwriteitas,
(float)(x/y+5);
77

Type Casting in Java
78

Type Casting in Java
79

Operators In Java

Operators in Java
Incomputerprogramming,anoperatorisaspecial
symbolthatisusedtoperformoperationsonthevariables
andvalues.
Theoperatorsrepresenttheoperations(specifictasks)
andtheobjects/variablesoftheoperationsareknownas
operands.
81

Operators in Java
Types of Operators
82

Operators in Java
Arithmetic Operators
Javaprovidesoperatorsforfivebasicarithmetic
calculations:addition,subtraction,multiplication,division,
andtheremainderwhichare+,-,*,/,and%respectively.
Eachoftheseisabinaryoperatorthatis,itrequirestwo
values(operands)toperformcalculations.
83

Operators in Java
Relational Operators
Javaprovides6relationaloperatorsforcomparingnumbersand
characters.But,relationaloperatorsdonotworkwithstrings.After
thecomparison,theyreturntheresultinbooleandatatype.Ifthe
comparisonistrue,therelationaloperatorresultsintrue,otherwise
false.
84

Operators in Java
85

Operators in Java
Logical Operators
Logicaloperatorsarealsoknownasconditionaloperators.These
operatorsareusedforevaluatingoneormorebooleanexpression,
forcomplexdecision-making.Theyalsoreturnabooleanvalue
(trueorfalse).Therearethreetypesoflogicalorconditional
operatorsinJavaare&&(Logical-AND),||(Logical-OR)and!
(LogicalNOT).typesoflogicalorconditionaloperators
Inthis,&&(Logical-AND)and||(Logical-OR)operatorsarethe
binarylogicaloperatorsthatworkontwooperandsorexpressions,
while!(LogicalNOT)isaunarylogicaloperatorwhichworkson
singleoperandorexpression.
86

Operators in Java
87

Operators in Java
1)ALogical-AND(&&)evaluatestheleftsideoftheoperation
first(operandone),andifitresolvestofalse,the&&operator
doesn'tbotherlookingattherightsideoftheexpression
(operandtwo)sincethe&&operatoralreadyknowsthatthe
completeexpressioncan'tpossiblybetrue.
2)TheLogical-OR(||)operatorissimilartothe&&operator,
exceptthatitevaluatestotrueifEITHERoftheoperandsis
true.
3)IfthefirstoperandinanORoperationistrue,theresultwillbe
true,sotheshort-circuit||doesn'twastetimelookingatthe
rightsideoftheequation.
4)Ifthefirstoperandisfalse,however,theshort-circuit||hasto
evaluatethesecondoperandtoseeiftheresultoftheOR
operationwillbetrueorfalse.
88

Operators in Java
ThelogicalNOToperator,whichiswrittenas!,isa
unaryoperatorthatworksonasingleoperandor
expression.TheLogicalNOToperator(!)negatesor
reversesthetruthvalueofitsoperand.Thatisifthe
expressionistrue,then!expressionisfalseandvice-
versa.
!(9!=0)//resultsintofalsebecause9isnon-zero(i.e.,true).
!(6>2)//resultsintofalsebecausetheexpression6>2istrue.
!(4>10)//resultsintotruebecausetheexpression4>10isfalse.
89

Operators in Java
Bitwise Operators in Java
TheBitwiseoperatorsmanipulatetheindividualbitsofa
number.Thebitwiseoperatorsworkwiththeinteger
typesthatis,byte,short,int,andlongtypes.Java
provides4bitwiseoperators:
90

Operators in Java
91

Operators in Java
Bitwise NOT( ~ )
TheBitwiseNOTisrepresentedbythesymbol(~).
BitwiseNOTisanunaryoperatorandinvertsallthe
bitsrepresentedbyitsoperand.Thatis,0sbecome1s
and1sbecome
bytea=3;//00000011
byteb=(byte)~a;//11111100
System.out.println("Valueofb="+b);//-4
92

Operators in Java
93

Operators in Java
The Bitwise AND Operator (&)
The bitwise AND operator, &, produces a 1 bit if both the
operands are also 1. A zero is produced in all the other
cases.
Example
00101010 42
&00001111 15
_________
00001010 10
94

Operators in Java
The Bitwise OR Operator
ThebitwiseORoperator,|,combinesbitssuchthatif
eitherofthebitsintheoperandsis1,thentheresultant
bitis1.
Example
00101010 42
|00001111 15
_________
00101111 47
95

Operators in Java
The Bitwise XOR Operator
ThebitwiseXORoperator,^,combinesbitssuchthatif
exactlyoneoperandis1,thentheresultis1.Otherwise,
theresultiszero.
Example
00101010 42
^00001111 15
_________
00100101 37
96

Operators in Java
Javaternary(?)Operator
Ternary(three-way)operatorcanreplacecertaintypesofif-then-elsestatements.
generalform
expression1?expression2:expression3
Here,expression1canbeanyexpressionthatevaluatestoabooleanvalue.If
expression1istrue,thenexpression2isevaluated;otherwise,expression3is
evaluated.
inti,k;
i=10;
k=i<0?-i:i;//getabsolutevalueofi
System.out.println("Absolutevalueof"+i+"is"+k);//10
i=-10;
k=i<0?-i:i;//getabsolutevalueofi
System.out.println("Absolutevalueof"+i+"is"+k);//-10
97

Operators in Java
JavainstanceofOperator
TheinstanceofoperatorinJava,usedonlyfortheobjectreferencevariables.This
operatorbasicallycheckswhethertheobjectisofaspecifictype(classor
interfacetype).
generalform
(Objectreferencevariable)instanceof(class/interfacetype)
Stringstr_name="James";
booleanres=str_nameinstanceofString;
System.out.println(res);
98

Control Statements in Java

Control Statements in Java
Control Statements in Java
Thestatementsthosewhocontroltheorderofexecutionofa
programareknownascontrolstatements
Typesofcontrolstatements
1)Selection/DecisionmakingStatements
Usingthesestatements,apieceofcodewouldbeexecuted
onlyifacertaincondition(s)istrue.
2)Iterationstatements
Usingthesestatementstoiterateablockofcoderepeatedly
untiltheconditionisfalse
3)Jumpstatements
Usingthesestatementstoskipthestatementsandcome-out
fromthose.
100

Control Statements in Java
101

Control Statements in Java
The if-else control statement
Theif-elsestatementisusedtochoose&executeanyoneactionamongtwo.
Syntax
if(condition){
//groupofprogrammingstatements
}
else{
//groupofprogrammingstatements
}
Bracesintheif-elseandothercontrolstatementsareoptionalifweusedonlyone
statementforeveryaction
Iftheconditionpresentinsidetheparenthesesistrue,if-blockisexecuted.After
executionofif-block,programcontrolskipselse-blockandjumpsdirectlyto
thestatementsafterelse-block.
Iftheconditioninsidetheparenthesisisfalse,else-blockisexecutedbyskipping
if-block
102

Control Statements in Java
103

Control Statements in Java
if statement (if without else statement)
Itispossibletouseifstatementwithouttheelsestatement.
Syntax
if(condition){
//groupof
//programming
//statements
}
Iftheconditioninsideparenthesesistrue,if-blockisexecuted.
Afterexecutionofif-block,programcontrolexecutesstatements
afterit.
Iftheconditioninsidetheparenthesisisfalse,if-blockisskipped,
andstatementsafteritareexecuted.
104

Control Statements in Java
105

Control Statements in Java
Nested if statement
InJavaprogramming,itispossibletoplaceifcontrolstatementinsideanotherif-blockor
else-block.
if(condition1){//outerif-block
if(condition2){
block1
}
}
else{//outerelse-block
if(condition3){
block2
}
}
Intheaboveexample,ifcondition1becomestrue,programcontrolentersintoouterif-block.
Thenitchecksforcondition2.Ifcondition2istrue,block1isexecuted.
Afterexecutionofblock1,controlistransferreddirectlytothestatementaftertheouterelse-
block.
Ifcondition1becomesfalse,programcontrolentersintoouterelse-blockskippingouterif-
block.Thenitchecksforcondition3.Ifcondition3istrue,block2isexecuted.After
executionofblock2andouterelse-blockcontrolistransferreddirectlytostatementafter
it.
106

Control Statements in Java
107

Control Statements in Java
108
Program to find bigger number among three given number
if(a>b){//’a’ is bigger
if(a>c)//’a’ is already bigger than ‘b’ so the comparison with ‘c’ only
‘a’ is bigger
else
‘c’ is bigger
}//outer if
else{
if(b>c)//compare to ‘a’ ‘b’ is bigger control comes to here.
Comparison with ‘c’ only
‘b’ is bigger
else
‘c’ is bigger
}
a=12, b=14, c=11

Control Statements in Java
109
Program to find out the given year is leap year or not?
Logic: A centennial (divisible by 100) year is leap if it is divisible by
400, and a non-centennial year is leap if it is divisible by 4.
if(year %100!=0){
if(year%4==0)
leap year
else
not a leap year
}
else{
if(year%400==0)
leap year
else
not a leap year
}
Solutionwith if-else
--------------------------
if(year%100!=0 && year %4==0 || year%400==0)
leap year
else
not a leap year

Control Statements in Java
110
Given3intvalues,abc,returntheirsum.However,ifoneofthevalues
is13thenitdoesnotcounttowardsthesumandvaluestoitsrightdonot
count.Soforexample,ifbis13,thenbothbandcdonotcount.
publicintluckySum(inta,intb,intc){
}
Forexample,
luckySum(1,2,3)→6
luckySum(1,2,13)→3
luckySum(1,13,3)→1
luckySum(13,5,3)→0

Control Statements in Java
111
luckySum solution
public int luckySum(int a, int b, int c) {
if (a == 13)
return 0;
else if (b == 13)
return a;
else if (c == 13)
return a + b;
else
return a + b +c;
}

Control Statements in Java
112
Whenbachelor'sgettogetherforaparty,theyliketohavebeers.A
bachelorpartyissuccessfulwhenthenumberofbeersisbetween40and
60,inclusive.Unlessitistheweekend,inwhichcasethereisnoupper
boundonthenumberofbeers.Returntrueifthepartywiththegiven
valuesissuccessful,orfalseotherwise.
publicbooleanbeerParty(intbeers,booleanisWeekend){
}
beerParty(30,false)→false
beerParty(50,false)→true
beerParty(70,true)→true
beerParty(30,true)→false

Control Statements in Java
113
beerParty solution
public boolean beerParty(int beers, boolean isWeekend) {
if (isWeekend == true && beers >= 40)
return true;
if (!(isWeekend) && beers >=40 && beers<= 60)
return true;
else
return false;
}

Control Statements in Java
114
Wearehavingapartywithamountsofteaandcandy.Returntheint
outcomeofthepartyencodedas0=bad,1=good,or2=great.Apartyis
good(1)ifbothteaandcandyareatleast5rating.However,ifeithertea
orcandyisatleastdoubletheamountoftheotherone,thepartyisgreat
(2).However,inallcases,ifeitherteaorcandyislessthan5rating,the
partyisalwaysbad(0).
publicintteaParty(inttea,intcandy){
}
teaParty(6,8)→1
teaParty(3,8)→0
teaParty(20,6)→2

Control Statements in Java
115
teaParty solution
public int teaParty(int tea, int candy) {
if (tea < 5 || candy < 5)
return 0;
if ((tea >= 2 * candy) || (candy >= 2 * tea))
return 2;
else
return 1;
}

Control Statements in Java
The if-else-if ladder statement
The if-else-if ladder is a very common programming constructs in Java, which is
also called the if-else-if staircase because of its appearance. We can use many
if-else-if statements in our program.
The general form or syntax of the if-else-if ladder statement is:
if( expression1)
statement1 ;
else if(expression2)
statement2;
.
.
else
statement3;
116

Control Statements in Java
117

Control Statements in Java
The switch statement
In Java programming, the switch statement is used to make a specific selection from
multiple cases.
Syntax
switch(expression){
case constant_value_1 :
statements to be executed;
break;
case constant_value_2 :
statements to be executed;
break;
case constant_value_N :
statements to be executed;
break;
case default :
statements to be executed;
}
118

Control Statements in Java
1)Inaswitchstatement,theexpressioninsideswitch’s
left&rightparenthesisisexecutedfirst.
2)Ifanycasematchestheexpressionvalue,program
controljumpsdirectlytothatcaseandstatementsof
thatcaseareexecuted.
3)Ifexpressionvaluedoesnotmatchwithanycase,then
programcontroljumpsdirectlytothedefaultcaseand
statementsofdefaultcaseareexecuted.
119

Control Statements in Java
120

Control Statements in Java
121

Control Statements in Java
The for loop
Syntax
for(initialization;condition;update){
// programming
// statements
}
Theforloopconsistsofthreeexpressionscalled
initialization,condition&updateanditsbody
(statementsinsidecurlybraces).
122

Control Statements in Java
123

Control Statements in Java
The while loop
Sameasforloop,whileloopisusedtoexecutespecific
partoftheprogramrepeatedly.
Syntax
while(condition){
// programming
// statements
}
124

Control Statements in Java
125

Control Statements in Java
The do-while loop
Sameasforloopandwhileloop,do-whileloopisalso
usedtoexecutespecificpartoftheprogramrepeatedly.
Theonlydifferenceisthatthebodyofdo-whileloopis
executedatleastonceeveniftheconditionisfalse.
Syntax
do{
// programming
// statements
}while(condition);
126

Control Statements in Java
127

Control Statements in Java
The break statement
Thestatementthatisusedtobreak/stoptheflowofloops&switch
statementisknownasbreakstatement.
Insidetheloop,breakstatementterminatestheloopexecution
whenitisencountered.
Insideswitchstatement,breakstatementisusedtojumpoutofthe
switchstatementinstantlywhenitisencountered.
Syntax
break;
JavaProgrammingLanguagebreakStatementWorkinginfor,
whileanddo-whileloops
Afterterminatingaloopbyusingthebreakstatement,program
controlistransferredimmediatelytothestatementaftertheloop.
128

Control Statements in Java
129

Control Statements in Java
The continue statement
Thecontinuestatementforceslooptoskipstatements
writtenafterit&continuenextexecutionoftheloop.
Syntax
continue;
Note
Ifthecontinuestatementisencounteredintheforloop,
programcontroljumpsdirectlytotheupdate
expression.
Ifthecontinuestatementisencounteredinthewhile&
do-whileloops,programcontroljumpsdirectlytothe
condition.
130

Control Statements in Java
131

Type Promotion in Java
132

Arrays In Java

Arrays In Java
1)InJavaarrayisanobjectwhichstoremultiple
variablesofthesametype.Itcanholdprimitivetypes
aswellasobjectreferences.Sincearrayisanobject,it
iscreatedduringruntime.Thearraylengthisfixed.
2)Arrayisanindexbaseddatastructuresoitallow
randomaccesstoelements,theystore.Indicesstart
with'0'
134

Arrays In Java
Features of an Array
1)Arrayisanobjectsowecanfindthelengthofthearray
usingattribute'length'.
2)Arrayisanorderedandeachhaveanindexbeginning
from'0'forthefirstelement.
3)Arrayscanstoreprimitivesaswellasobjects.Butall
mustbeofasingletypeinonearrayinstance.
4)Justlikeothervariablessocanusedasmethod
arguments.
5)Thesizeofanarraymustbespecifiedbyanintvalue.
135

Arrays In Java
136

Arrays In Java
Array Declaration
Thedeclarationofarraystatesthetypeoftheelementthat
thearrayholdsfollowedbythesquarebracesand
identifierwhichindicatestheidentifierisarraytype.
Example
Declaringanarraywhichholdselementsofintegertype.
137

Arrays In Java
Different way of declaring an array
138

Arrays In Java
Note
139

Arrays In Java
140

Arrays In Java
Note
141

Arrays In Java
142

Arrays In Java
Initialization of an array
143

Arrays In Java
144

Arrays In Java
145

Arrays In Java
146

Arrays In Java
Accessing elements from an array by using index value
Afterthearrayiscreated,itselementscanbeaccessedby
theirindex.Theindexisanumberplacedinsidesquare
bracketswhichfollowthearrayname.
Example,
String[]names={"Jane","Thomas","Lucy","David"};
System.out.println(names[0]);
System.out.println(names[1]);
System.out.println(names[2]);
System.out.println(names[3]);
147

Arrays In Java
Accessing elements from an array by using for each
loop
J2SE5introducesspecialtypeofforloopcalledforeach
looptoaccesselementsofarray.Usingforeachloopyou
canaccesscompletearraysequentiallywithoutusing
indexofarray.
Example,
int[] arr = {10, 20, 30, 40};
for(int x : arr){
System.out.println(x);
}
148

Arrays In Java
Accessing elements from an array by using basic for
loop
Example,
String[] planets = { "Mercury", "Venus", "Mars", "Earth",
"Jupiter", "Saturn", "Uranus", "Neptune", "Pluto" };
for (int i=0; i < planets.length; i++) {
System.out.println(planets[i]);
}
149

Arrays In Java
Anonymous arrays
Youcancreateanarraywithoutspecifyinganyname
sucharraysareknownasanonymousarrays.Sinceit
doesn’thavenametoreferyoucanuseitonlyoncein
yourprogram.Generally,anonymousarraysarepassedas
argumentstomethods.
You can create an anonymous array by initializing it at
the time of creation.
For example,
new int[] { 1254, 5452, 5743, 9984}; //int array
new String[] {"Java", "JavaFX", "Hadoop"}; //String
array
150

Arrays In Java
public class AnonymousArray {
public static void arrayToUpperCase(String [] array) {
for(int i=0; i< array.length; i++) {
char[] ch = array[i].toCharArray();
for(int j=0; j<ch.length; j++){
ch[j] = Character.toUpperCase(ch[j]);
} System.out.println(new String(ch));
} }
public static void main(String args[]) {
arrayToUpperCase(new String[] {"Krishna", "Vishnu",
"Dhana", "Rupa", "Raja", "Kavya"});
}}
151

Arrays In Java
Two-dimensional Arrays
TheTwoDimensionalArrayinJavaprogramming
languageisnothingbutanArrayofArrays.InJavaTwo
DimensionalArray,datastoredinrowandcolumns,and
wecanaccesstherecordusingboththerowindexand
columnindex
152

Arrays In Java
Example,
Two dimensional array:
int[][] twoDarr = new int[10][20];
Three dimensional array:
int[][][] threeDarr = new int[10][20][30];
Thetotalnumberofelementsthatcanbestoredina
multidimensionalarraycanbecalculatedbymultiplying
thesizeofallthedimensions.Forexample:
Thearrayint[][]x=newint[10][20]canstoreatotalof
(10*20)=200elements.
153

Arrays In Java
Declaration of 2D array
Data_Type[][] Array_Name;
Example : int [][] anIntegerArray;
Create Two dimensional Array in Java
In order to create a two dimensional array in Java, we
have to use the New operator as we shown below:
Data_Type[][] Array_Name = new
int[Row_Size][Column_Size];
Example : anIntegerArray = new int[3][4];
It is a 2-dimensional array, that can hold a maximum of
12 elements,
154

Arrays In Java
155

Arrays In Java
Declaration and Initialization of 2D array
Syntax
data_type[][] array_name = {
{valueR1C1, valueR1C2, ....},
{valueR2C1, valueR2C2, ....}
};
For example,
int[][] arr = {{1, 2}, {3, 4}};
156

Arrays In Java
Retrieve elements from 2D arrays standard method
int[][] a={{10,20},{30,40}};//declaration and initialization
System.out.println("Two dimensional array elements are");
System.out.println(a[0][0]);
System.out.println(a[0][1]);
System.out.println(a[1][0]);
System.out.println(a[1][1]);
157

Arrays In Java
Retrieve elements from 2D array by using for loop
int[][] a={{10,20},{30,40},{50,60}};//declaration and initialization
System.out.println("Two dimensional array elements are");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++){
System.out.println(a[i][j]);
}
}
158

Arrays In Java
Dynamically passing row and column sizes
Scanner sc=new Scanner(System.in);
System.out.println("Enter Row length of an array : ");
int row=sc.nextInt();
System.out.println("Enter column length of an array : ");
int column=sc.nextInt();
int a[][]=new int[row][column];//declaration
159

Arrays In Java
System.out.print("Enter " + row*column + " Elements to
Store in Array :\n");
for (int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
a[i][j] = sc.nextInt();
}
}
160

Arrays In Java
System.out.print("Elements in Array are :\n");
for (int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
System.out.println("Row ["+i+"]: Column ["+j+"]
:"+a[i][j]);
}
}
161

Arrays In Java
Jagged Array in Java
Jaggedarrayisarrayofarrayssuchthatmemberarrays
canbeofdifferentsizes,i.e.,wecancreatea2-Darrays
butwithvariablenumberofcolumnsineachrow.These
typeofarraysarealsoknownasJaggedarrays.
int arr[][] = new int[2][]; // Declaring 2-D array with 2
rows
// Making the above array Jagged
arr[0] = new int[3]; // First row has 3 columns
arr[1] = new int[2]; // Second row has 2 columns
162

Arrays In Java
// Initializing array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
// Displaying the values of 2D Jagged array
System.out.println("Contents of 2D Jagged Array");
for (int i=0; i<arr.length; i++) {
for (int j=0; j<arr[i].length; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
163

Abstraction In Java
Inobjectorientedprogrammingabstractionisa
processofprovidingfunctionalitytotheusersbyhiding
itsimplementationdetailsfromthem
Inotherwords,theuserwillhavejustthe
knowledgeofwhatanentityisdoinginsteadofits
implementation
164

Abstraction In Java
ReallifeexampleofAbstractionisATMMachine;Allare
performingoperationsontheATMmachinelikecash
withdrawal,moneytransfer,retrievemini-statement…etc.
butwecan'tknowinternaldetailsaboutATM.
165

Abstraction In Java
Advantages of Abstraction
166

Abstraction In Java
How to Achieve Abstraction in Java?
InJava,wecanachieveDataAbstractionusingAbstract
classandInterface
Interfaceallow100%abstraction(completeabstraction).
Interfaceallowyoutoabstracttheimplementation
completely
Abstractclassallow0to100%abstraction(partialto
completeabstraction)becauseabstractclasscancontain
concretemethodsthathavetheimplementationwhich
resultsinapartialabstraction
167

Abstraction In Java
InJavaprogrammingwehavetwotypesofclassesthey
are
1)Concreteclass
2)Abstractclass
Aconcreteclassisonewhichiscontainingfullydefined
methodsorimplementedmethod.
classHelloworld{
voiddisplay(){
System.out.println("GoodMorning........");
}
}
168

Abstraction In Java
Abstractclass
Aclassthatisdeclaredwithabstractkeyword,isknownasabstract
class.Anabstractclassisonewhichiscontainingsomedefined
methodandsomeundefinedmethod.Injavaprogramming
undefinedmethodsareknownasun-Implemented,orabstract
method.
Syntax
abstractclassclassName{
......
}
Example
abstractclassA{
.....
}
169

Abstraction In Java
Abstract method
Anabstractmethodisonewhichcontainsonly
declarationorprototypebutitnevercontainsbodyor
implementation.Inordertomakeanymethodasabstract
whosedeclarationismustbepredefinedbyabstract
keyword.Thedeclarationofanabstractmethodmustend
withasemicolon;
Syntax
abstractReturnTypemethodName(Listofformal
parameter);
Example
abstractvoidBike();
170

Abstraction In Java
Rules for Using Abstract Class in Java
1)Wecandeclareanabstractclassusingtheabstract
keyword.
2)Itmayhaveabstractaswellasconcrete(non-abstract)
methods.
3)Anabstractclasscanhavestaticmethods.
4)Anabstractclasscanalsohaveconstructors.
5)Itcanhavefinalmethods.Ifwedeclarethemethodas
finalinsidetheabstractclassthenthesubclasscannot
changethebodyofthemethod.
171

Abstraction In Java
6)Wecan’tinstantiateorcreateanobjectofanabstract
class.
7)Aclassderivedfromtheabstractparentclassmust
implementeachmethodthatisdeclaredasabstractin
theparentclass.Otherwise,therewillbea
compilationerror.
8)Ifthederivedclassdoesnotimplementalltheabstract
methodsofanabstractparentclass,thenthederived
classmustalsodeclareitselfasabstract.
172

Abstraction In Java
Why do we need Abstract Classes in Java?
Wewanttocreateaclassthatjustdeclaresthemethodswithout
providingacompleteimplementationofeverymethod.And,we
wantthatthismethod(s)issharedbyallofitschildclasses,andall
theimplementationdetailswillbefilledbythesesubclasses.
Let’staketheexampleofabankingapplicationorsoftware.
SupposewehaveaclassBankAccountthathasamethoddeposit()
andwithdraw()andthesubclassesofitlikeSavingsAccount,
CurrentAccount,FixedDepositAccount,etc.Sincetheprocessof
depositandwithdrawaldiffersfromoneaccounttoanother,thereis
nopointtoimplementthesetwomethodsintheparentclass
BankAccount.Thisisbecauseeverychildclassmustoverridethese
methodsandprovideanimplementationofthem.
173

Abstraction In Java
174

Abstraction In Java
Interface In Java
1)InJava,aninterfaceisablueprintortemplateofaclass
usedtoachieve100%abstraction.
2)Whenyoucreateaninterface,you'redefiningacontract
forwhataclasscando,withoutsayinganythingabout
howtheclasswilldoit.
3)Therecanbeonlyabstractmethodsinaninterface.
4)Ifaclassimplementsaninterfaceanddoesnotprovide
methodbodiesforallfunctionsspecifiedintheinterface,
thentheclassmustbedeclaredabstract.
175

Abstraction In Java
Syntax to create an interface
interface interface-name{
//abstract methods
}
Example
interface Animal{
public void eat();
public void travel();
}
176

Abstraction In Java
Why we do use interface?
177

Abstraction In Java
Properties of a Java Interface
1)Aninterfaceisimplicitlyabstract.Whiledeclaringaninterface,you
donotneedtousethekeywordabstract.
2)Eachmethodofaninterfaceisimplicitlypublicandabstract,sowe
neednotusethepublicandabstractkeywordwhiledeclaringmethods
insideaninterface.
The following five method declarations are legal and identical
a)void bounce();
b)public void bounce();
c)abstract void bounce();
d)public abstract void bounce();
e)abstract public void bounce();
178

Abstraction In Java
3)All variables defined in an interface are public, static, and final.
In other words, interfaces can declare only constants, not
instance variables.
Legal interface constants declarations
a)public int x = 1; // Looks non-static and non-final, // but isn't!
b)int x = 1; // Looks default, non-final, // non-static, but isn't!
c)static int x = 1; // Doesn't show final or public
d)final int x = 1; // Doesn't show static or public
e)public static int x = 1; // Doesn't show final
f)public final int x = 1; // Doesn't show static
g)static final int x = 1 // Doesn't show public
179

Abstraction In Java
180

Abstraction In Java
4)Aninterfacecanextendoneormoreotherinterfaces.
5)Aclasscanextendonlyoneclass(nomultiple
inheritance),butitcanimplementoneormore
interfaces.
181

Abstraction In Java
182
1) class Foo { }
class Bar implements Foo { }
2) interface Baz { }
interface Fi { }
interface Fee implements Baz { }
3) class Foo { }
interface Zee implements Foo { }
4) class Foo
interface Zoo extends Foo { }

Abstraction In Java
5) interface Fi { }
interface Boo extends Fi { }
6) class Toon extends Foo, Button { }
7) class Zoom implements Fi, Baz { }
8) interface Vroom extends Fi, Baz { }
9)class Yow extends Foo implements Fi { }
183

Abstraction In Java
How interface is different from class ?
1)Youcannotinstantiateaninterface.
2)Itdoesnotcontainanyconstructors.
3)Allmethodsinaninterfaceareabstract.
4)Interfacecannotcontaininstancefields.Interfaceonly
containspublicstaticfinalvariables.
5)Interfaceiscannotextendedbyaclass;itis
implementedbyaclass.
6)Interfacecanextendmultipleinterfaces.Itmeans
interfaceexhibitthefunctionalitymultipleinheritance
184

Abstraction In Java
Implementing Interfaces in Java
Aclassimplementinganinterfaceitmeansthattheclass
agreestoperformthespecificbehaviorsoftheinterface.
Unlessaclassisdeclaredasabstract,itshouldperformall
thebehaviorsoftheinterface.
Inordertoimplementaninterface,aclassusesthe
implementskeyword.
public class Ball implements Bounceable {
public void bounce() { }
public void setBounceFactor(int bf) { }
}
185

Abstraction In Java
WhenweuseabstractandwhenInterface
Ifwedonotknowaboutanythingsaboutimplementationjustwe
haverequirementspecificationthenweshouldbegoforInterface
Ifwearetalkingaboutimplementationbutnotcompletely
(partiallyimplemented)thenweshouldbegoforabstract
Whyinterfacehavenoconstructor?
Because,constructorareusedforeliminatethedefaultvaluesby
userdefinedvalues,butincaseofinterfaceallthedatamembers
arepublicstaticfinalthatmeansallareconstantsononeedto
eliminatethesevalues.
Otherreasonbecauseconstructorislikeamethodanditisconcrete
methodandinterfacedoesnothaveconcretemethodithaveonly
abstractmethodsthat'swhyinterfacehavenoconstructor.
186

Abstraction In Java
187

Abstraction In Java
188

Abstraction In Java
Marker or tagged interface
Aninterfacethathavenomemberisknownasmarkeror
taggedinterface.Forexample:Serializable,Cloneable,
Remoteetc.Theyareusedtoprovidesomeessential
informationtotheJVMsothatJVMmayperformsome
usefuloperation.
Example
//WayofwritingSerializableinterface
publicinterfaceSerializable
{
}
189

Abstraction In Java
New features added in interfaces from JDK 8 version
1)Java8allowstheinterfacestohavedefaultandstatic
methods.
WhyDefaultmethods?
ClassessuchasA,B,CandDimplementsaninterfaceXYZInterface.Ifweadd
anewmethodtotheXYZInterface,wehavetochangethecodeinallthe
classes(A,B,CandD)thatimplementsthisinterface.Here,wehaveonlyfour
classesthatimplementstheinterfacewhichwewanttochangebutimagineif
therearehundredsofclassesimplementinganinterfacethenitwouldbealmost
impossibletochangethecodeinallthoseclasses.Thisiswhyinjava8,wehave
anewconcept“defaultmethods”.Thesemethodscanbeaddedtoanyexisting
interfaceandwedonotneedtoimplementthesemethodsintheimplementation
classesmandatorily,thuswecanaddthesedefaultmethodstoexistinginterfaces
withoutbreakingthecode.
190

Abstraction In Java
Why static methods?
Staticmethodsininterfacesaresimilartothedefault
methodsexceptthatwecannotoverridethesemethodsin
theclassesthatimplementstheseinterfaces.
191

Abstraction In Java
Interface with default method
interface MyInterface{
/* This is a default method so we need not
* to implement this method in the implementation
* classes
*/
default void newMethod(){
System.out.println("Newly added default method");
}
/* Already existing public and abstract method
void existingMethod(String str);
}
192

Abstraction In Java
Interface with static method
interface MyInterface{
default void newMethod(){
System.out.println("Newly added default method");
}
/* This is a static method. Static method in interface is
static void anotherNewMethod(){
System.out.println("Newly added static method");
}
//Already existing public and abstract method
void existingMethod(String str);
}
193

Abstraction In Java
Default Method and Multiple Inheritance
The multiple inheritance problem can occur, when we have two interfaces with
the default methods of same signature. Lets take an example.
interface MyInterface{
default void newMethod(){
System.out.println("Newly added default method");
} void existingMethod(String str);
}
interface MyInterface2{
default void newMethod(){
System.out.println("Newly added default method");
}void disp(String str);
}
How to solve this issue?
To solve this problem, we can implement this method in the implementation
class
194

Abstraction In Java
Java9hasintroducedanothernewfeature,Java9SE
onwardswecanhaveprivatemethodsininterfaces.
Java9introducedprivatemethodsininterfacestoremove
theredundancybysharingthecommoncodeofmultiple
defaultmethodsthroughprivatemethods.
195

Abstraction In Java
Multiple default methods with duplicate code (java8)
interface MyInterfaceInJava8 {
default void method1() {
System.out.println("Starting method");
System.out.println("Doing someting");
System.out.println("This is method1");
}
default void method2() {
System.out.println("Starting method");
System.out.println("Doing someting");
System.out.println("This is method2");
}
}
196

Abstraction In Java
Default methods sharing common code using private methods
interface MyInterfaceInJava9 {
default void method1() {
//calling private method
printLines();
System.out.println("This is method1");
}
default void method2() {
//calling private method
printLines();
System.out.println("This is method2");
}
private void printLines() {
System.out.println("Starting method");
System.out.println("Doing someting");
}
}
197

Abstraction In Java
Java9alsoallowsustohaveprivatestaticmethodsin
interfaces.
Sincejava8wecanhavestaticmethodsininterfaces
alongwithdefaultmethods.Wecannotsharethe
commoncodeofstaticmethodsusingthenon-static
privatemethod,wemusthavetousetheprivatestatic
methodtodothat.
198

Abstraction In Java
interface MyInterfaceInJava9 {
static void method1() {
printLines(); //calling private method
System.out.println("This is method1");
}
static void method2() {
printLines(); //calling private method
System.out.println("This is method2");
}
//this must be static else we will get compilation error
private static void printLines() {
System.out.println("Starting method");
System.out.println("Doing someting");
}
default void mymethods() {
method1();
method2();
}
}
199

Method Overriding
1)Declaringamethodinsubclasswhichisalready
presentinparentclassisknownasmethodoverriding.
2)Overridingisdonesothatachildclasscangiveits
ownimplementationtoamethodwhichisalready
providedbytheparentclass.
3)Inthiscasethemethodinparentclassiscalled
overriddenmethodandthemethodinchildclassis
calledoverridingmethod.
4)Themainadvantageofmethodoverridingisthatthe
classcangiveitsownspecificimplementationtoa
inheritedmethodwithoutevenmodifyingtheparent
classcode.
200

Method Overriding
Example on method overriding
class Human{
public void eat(){//Overridden method
System.out.println("Human is eating");
}
}
class Boy extends Human{
public void eat(){//Overriding method
System.out.println("Boy is eating");
}
}
201

Method Overriding
Rules of method overriding in Java
Argumentlist:Theargumentlistofoverridingmethod
(methodofchildclass)mustmatchtheOverridden
method(themethodofparentclass).Thedatatypesofthe
argumentsandtheirsequenceshouldexactlymatch.
202

Method Overriding
AccessModifieroftheoverridingmethod(methodofsubclass)
cannotbemorerestrictivethantheoverriddenmethodofparent
class.Fore.g.iftheaccesslevelofparentclassmethodispublic
thentheoverridingmethod(childclassmethod)cannothave
private,protectedanddefaultaccesslevel,becauseallofthese
threeaccesslevelaremorerestrictivethanpublic.
classMyBaseClass{
publicvoiddisp(){
System.out.println("Parentclassmethod");
}}
classMyChildClassextendsMyBaseClass{
protectedvoiddisp(){//C.E
System.out.println("Childclassmethod");
}}
203

Method Overriding
private,staticandfinalmethodscannotbeoverriddenas
theyarelocaltotheclass.Howeverstaticmethodscanbe
re-declaredinthesubclass,inthiscasethesub-class
methodwouldactdifferentlyandwillhavenothingtodo
withthesamestaticmethodofparentclass.
204

Association In Java

Association In Java
1)Associationisrelationbetweentwoseparateclasses
whichestablishesthroughtheirObjects.
2)Associationcanbeone-to-one,one-to-many,many-
to-one,many-to-many.
3)InObject-Orientedprogramming,anobject
communicatestootherobjecttousefunctionalityand
servicesprovidedbythatobject.
4)CompositionandAggregationarethetwoformsof
association.
206

Association In Java
AggregationorHAS-Arelationshipbetweentwo
classes.
WhenclassAhasareferencetotheobjectofanotherclassB,class
AissaidtobeinaHAS-ArelationshipwithclassB.Throughthis
referenceofclassBinit,classAcancallandusetheneeded
featuresofclassB,withoutcopyingalltheunnecessarycodeof
classBinit.
Let'stakeanexample
classStudent{
Stringname;
Addressad;
}
Hereintheabovecode,youcansaythatStudenthas-aAddress.
207

Association In Java
Composition or IS-A relationship between two classes
AnIS-Asignifiesarelationshipbetweenthetwoclasses
thatareconnectedtoeachotherthroughinheritance.The
basisofanIS-Arelationshipis-
a)Whenaclassextendsanotherconcrete(non-abstract)
class.
b)Whenaclassextendsanabstractclass.
c)Whenaclassimplementsaninterface.
208

String Handling In Java

String Handling In Java
Introduction
1)Basically,stringisasequenceofcharactersbutit’snot
aprimitivetype.
2)InJava,CharSequenceInterfaceisusedfor
representingasequenceofcharacters.
3)CharSequenceinterfaceisimplementedbyString,
StringBufferandStringBuilderclasses.Thesethree
classescanbeusedforcreatingstringsinjava.
4)Whenwecreateastringinjava,itactuallycreatesan
objectofabovethreeclasses
210

String Handling In Java
211

String Handling In Java
Creation of strings
1) Using string literal
WhilecreatingStringobjectusingstringliteral,newoperatorisnot
used.
Stringobjectscanbecreatedusingstringliteralasshownbelow:
Example
Stringstr1=“James”;
212

String Handlin In Java
213

String Handlin In Java
What is String Constant Pool?
TheStringConstantPool(SCP)isaplacewhere
objectswithstringliteralsarestored.
Itisapartoftheheapmemoryarea.
214

String Handlin In Java
215

String Handling In Java
216
WhenwecreateaStringusingdoublequotes,JVMlooksinthe
Stringpool(referstocollectionofStringswhicharestoredinheap
memory)tofindifanyotherStringisstoredwithsamevalue.
Iffound,itjustreturnsthereferencetothatStringobjectelseit
createsanewStringobjectwithgivenvalueandstoresitinthe
Stringpool.

String Handling In Java
217
Intheaboveimage,twoStringsarecreatedusingliterali.e“Apple”
and“Mango”.Now,whenthirdStringiscreatedwiththevalue
“Apple”,insteadofcreatinganewobject,thealreadypresent
objectreferenceisreturned.

String Handling In Java
2) Using new keyword
WhenStringobjectiscreatedusingthenewkeyword,
twosamestringobjectsarecreated.Oneinheaparea
(outsideSCP)&anotherinsideStringConstantPool
(SCP).
Example
Stringstr1=newString(“James”);
218

String Handling In Java
DifferencebetweenStringliteralandNewStringobject
WhenyouusenewString("Hello"),itexplicitlycreates
anewandreferentiallydistinctinstanceofaString
object.Itisanindividualinstanceofthejava.lang.String
class.
219

String Handling In Java
Strings=“Harry";mayreuseaninstancefromthestring
constantpoolifoneisavailable(StringPoolisapoolof
StringsstoredinJavaheapmemory)otherwisecreatea
newinstance
220

String Handling In Java
StringsAreImmutableObjects
Theobjectsinwhichyoucannotchangeanythingonce
theobjectiscreatedareknownasImmutableobjects.
OnceaStringobjectiscreated,itcanneverbechanged
soitisanimmutableobjectbutitsreferencevariableis
not.
221

String Handling In Java
String samplestring="Machine Learning";
samplestring.concat("Masters");
System.out.println(samplestring);
Variablesamplestring,whichstoresthestring“MachineLearning“.
Now,ifyouconcatenatethisstringwithanotherstring“Masters“,
thentheobjectcreatedfor“MachineLearning”willnotchange.
Instead,anewobjectwillbecreatedfor“MachineLearning
Masters“.
222

String Handling In Java
String Class Methods
public char charAt(int index)
Returnsthecharacteratthespecifiedindex.Specifiedindexvalue
shouldbebetween'0'to'length()-1'bothinclusive.Itthrows
IndexOutOfBoundsExceptionifindexisinvalid/outofrange.
Stringname="JamesSmith";
charch1=name.charAt(3)
charch2=name.charAt(6);
charch3=name.charAt(9);
223

String Handlin In Java
224

String Handling In Java
public void getChars(int srcBegin, int srcEnd, char[] dst, int
dstBegin)
This method is used to copy set of characters of the invoking string
into the specified character array.
Parameters
srcBegin − index of the first character in the string to copy.
srcEnd − index after the last character in the string to copy.
dst − the destination array.
dstBegin − the start offset in the destination array.
String s = "Its Beyond Simple";
int start = 4;
int end = 10;
char storage[] = new char[end-start];
s.getChars(start,end,storage,0);
System.out.println(storage);
225

String Handlin In Java
226

String Handling In Java
public byte[] getBytes()
ThismethodencodesthisStringintoasequenceofbytes
usingtheplatform'sdefaultcharset,storingtheresultinto
anewbytearray.
StringStr1=newString("WelcometoNareshIt");
byte[]b=Str1.getBytes();//bytearrayhavingallcharactes
withasciivalues
227

String Handling In Java
public char[] toCharArray()
Thismethodconvertsthisstringtoanewcharacterarray.
Itreturnsanewlyallocatedcharacterarray,whoselength
isthelengthofthisstringandwhosecontentsare
initializedtocontainthecharactersequencerepresented
bythisstring.
Stringstr=newString("WelcometoNacre");
char[]ch=str.toCharArray();//arraycontainstheall
charactersofthestring
228

String Handling In Java
boolean equals(Object anObject)
Usedtocomparetwostrings.Itreturnstrueifbothstring
representssamesequenceofcharacterselsefalse.
String s1="hello";
String s2="welcome";
s1.equals(s2);// returns false
s1.equals("hello");// returns true.
229

String Handling In Java
boolean equalsIgnoreCase(String anotherString)
Usedtocomparetwostrings,ignoringthecase(upperor
lowercase).Itreturnstrueifboththestringareofsame
lengthandrepresentssamesequenceofcharacter
ignoringthecaseelsereturnsfalse.
String s1="hello";
s1.equalsIgnoreCase("Hello");// returns true
230

String Handling In Java
regionMatches()method
ThismethodtestsifthetwoStringsareequal.Usingthismethod
wecancomparethesubstringofinputStringwiththesubstring
ofspecifiedString.
publicbooleanregionMatches(inttoffset,Stringother,intooffset,
intlen)
Casesensitivetest.
publicbooleanregionMatches(booleanignoreCase,inttoffset,
Stringother,intooffset,intlen)
Ithasoptiontoconsiderorignorethecase.
231

String Handling In Java
String str1 = new String("Hello, How are you");
String str2 = new String("How");
String str3 = new String("HOW");
System.out.println(str1.regionMatches(7, str2, 0, 3));
System.out.println(str1.regionMatches(7, str3, 0, 3));
System.out.println(str1.regionMatches(true, 7, str3, 0, 3));
232

String Handling In Java
boolean startsWith(String prefix)
checksifastringstartswiththestringrepresentedby
prefix.
Strings1=“refreshjava”;
s1.startsWith("refresh");// returns true.
s1.startsWith("Refresh");// returns false.
233

String Handling In Java
public boolean endsWith(String suffix)
ThismethodcheckswhethertheStringendswitha
specifiedsuffix.Thismethodreturnsabooleanvalue
trueorfalse.Ifthespecifiedsuffixisfoundattheend
ofthestringthenitreturnstrueelseitreturnsfalse.
String str1 = new String("This is a test String");
boolean var1 = str1.endsWith("String");
System.out.println("str1 ends with String: "+ var1);
234

String Handling In Java
int compareTo(String str)
TheJavaStringcompareTo()methodisusedforcomparingtwo
stringslexicographically.Eachcharacterofboththestringsis
convertedintoaUnicodevalueforcomparison.Ifboththe
stringsareequalthenthismethodreturns0elseitreturns
positiveornegativevalue.Theresultispositiveifthefirststring
islexicographicallygreaterthanthesecondstringelsetheresult
wouldbenegative.
Stringstr1="Stringmethodtutorial";
Stringstr2="compareTomethodexample";
intvar1=str1.compareTo(str2);
System.out.println("str1&str2comparison:"+var1);
235

String Handling In Java
substring() method
Thismethodisusedtogetthesubstringofagivenstringbasedonthepassed
indexes.Therearetwovariantsofthismethod.
1.Whenwepassonlythestartingindex:
publicStringsubstring(intbeginIndex)
Returnsthesubstringstartingfromthespecifiedindexi.ebeginIndexand
extendstothecharacterpresentattheendofthestring.
Forexample–"Hello".substring(1)wouldreturn"ello".
2.Whenwepassboththeindexes,startingindexandendindex:
publicStringsubstring(intbeginIndex,intendIndex)
Returnsanewstringthatisasubstringofthisstring.Thesubstringbeginsatthe
specifiedbeginIndexandextendstothecharacteratindexendIndex–1.Thus
thelengthofthesubstringisendIndex-beginIndex.Inotherwordsyoucansay
thatbeginIndexisinclusiveandendIndexisexclusivewhilegettingthe
substring.
Forexample–"Chaitanya".substring(2,5)wouldreturn"ait".
236

String Handling In Java
The concat() method
public String concat(String str)
Thismethodconcatenatesthestringstrattheendofthecurrent
string.Forexample–s1.concat("Hello");wouldconcatenatethe
String“Hello”attheendoftheStrings1.Thismethodcanbe
calledmultipletimesinasinglestatementlikethis
Strings1="Nacre";
s1=s1.concat("Software").concat("Service").concat("Pvt.Ltd");
237

String Handling In Java
replace() method
String replace(char oldChar, char newChar)
It replaces all the occurrences of a oldChar character with
newChar character.
For example, "pog pance".replace('p', 'd') would return
dog dance.
238

String Handling In Java
replaceFirst() method
String replaceFirst(String regex, String replacement)
Itreplacesthefirstsubstringthatfitsthespecifiedregular
expressionwiththereplacementString.
PatternSyntaxExceptionifthespecifiedregular
expression(regex)isnotvalid.
Stringstr=newString("facebook.com");
System.out.println(str.replaceFirst("com","net"));
Resultisfacebook.net
239

String Handling In Java
replaceAll() method
String replaceAll(String regex, String replacement)
It replaces all the substrings that fits the given regular
expression with the replacement String.
String str = new String("My .com site is facebook.com");
System.out.println(str.replaceAll("com", "net"));
Output is My.net site is facebook.net
240

String Handling In Java
indexOf()method
Thismethodisusedtofindtheindexofaspecifiedcharacterorasubstringina
givenString.
Thereare4variationsofthismethodinStringclass
1)intindexOf(intch)
ItreturnstheindexofthefirstoccurrenceofcharacterchinagivenString.
Strings="ILIKEJAVALIKEJAVA";
System.out.println("IndexofJ::"+s.indexOf('J'));
2)intindexOf(intch,intfromIndex)
Itreturnstheindexoffirstoccurrenceofcharacterchinthegivenstringafterthe
specifiedindex“fromIndex”.
Strings="ILIKEJAVALIKEJAVA";
System.out.println("IndexofJfrom8thindex::"+s.indexOf('J',8));
241

String Handlin In Java
242

String Handling In Java
3)intindexOf(Stringstr)
ReturnstheindexofstringstrinaparticularString.
Strings="ILIKEJAVALIKEJAVA";
System.out.println("Index of JAVA :: "+s.indexOf("JAVA"));
4)intindexOf(Stringstr,intfromIndex)
Returnstheindexofstringstrinthegivenstringafterthespecified
index“fromIndex”.
Strings="ILIKEJAVALIKEJAVA";
System.out.println("IndexofLIKEfrom4thindex::
"+s.indexOf("LIKE",4));
Note
Alltheabovevariationsreturns-1ifthespecifiedchar/substringis
notfoundintheparticularString. 243

String Handling In Java
244

String Handling In Java
lastIndexOf()method
Thismethodisusedtofindouttheindexoflast
occurrenceofacharacterorasubstringinagiven
String.
Tofindoutthelastoccurrenceofthespecifiedcharacter
orastring,thismethodstartsthesearchfromtheendof
stringandproceedsbackwardsfromthere.
IfthefromIndexisspecifiedduringthemethodcall,then
thebackwardsearchbeginsfromthespecifiedindex
fromIndex
245

String Handling In Java
1)intlastIndexOf(intch)
ItreturnsthelastoccurrenceofcharacterchinthegivenString.
Strings="ILIKEJAVALIKEJAVA";
System.out.println("LastIndexofJ::"+s.lastIndexOf('J'));
2)intlastIndexOf(intch,intfromIndex)
Itreturnsthelastoccurrenceofch,itstartslookingbackwardsfromthespecifiedindex
“fromIndex”.
Strings="ILIKEJAVALIKEJAVA";
System.out.println("LastIndexofJfrom16thindex::"+s.lastIndexOf('J',16));
3)intlastIndexOf(Stringstr)
ReturnsthelastoccurrenceofsubstringstrinaString.
Strings="ILIKEJAVALIKEJAVA";
System.out.println("LastIndexofLIKE::"+s.lastIndexOf("LIKE"))
4)intlastIndexOf(Stringstr,intfromIndex)
Returnsthelastoccurrenceofstr,startssearchingbackwardfromthespecifiedindex
“fromIndex”.
Strings="ILIKEJAVALIKEJAVA";
System.out.println("LastIndexofLIKE from9thindex::
"+s.lastIndexOf("LIKE",9));
246

String Handlin In Java
247

String Handling In Java
contains() method
Thismethodcheckswhetheraparticularsequenceof
charactersispartofagivenstringornot.
Thismethodreturnstrueifaspecifiedsequenceof
charactersispresentinagivenstring,otherwiseit
returnsfalse.
Syntaxofcontains()method
publicbooleancontains(CharSequencestr)
IftheCharSequenceisnullthenthismethodthrows
NullPointerException.
248

String Handling In Java
intern() method
1)It is used for getting the string from the memory if it is already
present.
2)This method ensures that all the same strings share the same
memory.
3)ThismethodsearchesthememorypoolforthementionedString,
ifthestringisfoundthenitreturnsthereferenceofit,elseit
allocatesanewmemoryspaceforthestringandassigna
referencetoit.
4)Forexample,creatingastring“hello”10timesusingintern()
methodwouldensurethattherewillbeonlyoneinstanceof
“Hello”inthememoryandallthe10referencespointtothe
sameinstance.
249

String Handling In Java
//String object in heap
String str1 = new String("hello world");
//String literal in pool
String str2 = "hello world";
//String literal in pool
String str3 = "hello world";
//String object interned to literal
//It will refer to existing string literal
String str4 = str1.intern();
250

String Handling In Java
isEmpty()method
ThismethodcheckswhetheraStringisemptyornot.
Thismethodreturnstrueifthegivenstringisempty,
elseitreturnsfalse.Inotherwordsyoucansaythatthis
methodreturnstrueifthelengthofthestringis0.
public boolean isEmpty()
251

String Handling In Java
join() method
InJava8wehaveanewMethodjoin()intheJavaString
class.JavaStringjoin()methodconcatenatesthegiven
StringsandreturnstheconcatenatedString.
publicstaticStringjoin(CharSequencedelimiter,
CharSequence...elements)
Thefirstargumentofthismethodspecifiesthedelimiter
thatisusedtojoinmultiplestrings.
Stringmessage=String.join("-","This","is","a",
"String");
Outputis:"This-is-a-String"
252

String Handling In Java
split() method
This method used for splitting a String into its substrings
based on the given delimiter or regular expression.
Wehavetwovariantsofsplit()methodinStringclass.
1.String[]split(Stringregex):Itreturnsanarrayofstringsafter
splittinganinputStringbasedonthedelimitingregular
expression.
2.String[]split(Stringregex,intlimit):ThisJavaStringsplit
methodisusedwhenwewantthesubstringstobelimited.
Theonlydifferencebetweenthismethodandabovemethodisthat
itlimitsthenumberofstringsreturnedaftersplitup.Fore.g.
split("anydelimiter",3)wouldreturnthearrayofonly3strings
evenifthedelimiterispresentinthestringmorethan3times.
253

String Handling In Java
String str = new String("28/12/2013");
String array1[]= str.split("/");
for (String temp: array1){
System.out.println(temp);
}
String array2[]= str.split("/", 2);
for (String temp: array2){
System.out.println(temp);
}
254

String Handling In Java
Difference between zero and negative limit in java string
split method
Limit zero excludes trailing empty strings, where as negative limit
includes trailing strings
String s="bbaaccaa";
String arr1[]= s.split("a", -1);
String arr2[]= s.split("a", 0);
255

String Handling In Java
Java String split with multiple delimiters (special characters)
String s = " ,ab;gh,bc;pq#kk$bb";
String[] str = s.split("[,;#$]");
Word as a regular expression in Java String split method
String str = "helloxyzhixyzbye";
String[] arr = str.split("xyz");
Splitting string based on whitespace
String str = "My name is Ram";
String[] arr = str.split(" ");
for (String s : arr)
System.out.println(s);
256

String Handling In Java
format() method
ThismethodisusedforformattingtheString.Therearesomany
thingsyoucandowiththismethod,forexampleyoucan
concatenatethestringsusingthismethodandatthesametime,
youcanformattheoutputofconcatenatedstring.
public static String format(Locale l,String format,
Object... args)
Returns a formatted string using the specified locale, format string,
and arguments.
public static String format(String format, Object... args)
Returns a formatted string using the specified format string and
arguments.
257

String Handling In Java
Java String Format Specifiers
%c –Character
%d –Integer
%s –String
%o –Octal
%x –Hexadecimal
%f –Floating number
%h –hash code of a value
258

String Handling In Java
String str = "just a string";
//concatenating string using format
String formattedString = String.format("My String is %s", str);
// %.6f is for having 6 digits in the fractional part
String formattedString2 = String.format("My String is
%.6f",12.121);
259

String Handling In Java
Wecanspecifytheargumentpositionsusing%1$,
%2$,..formatspecifiers.Here%1$representsfirst
argument,%2$secondargumentandsoon.
Stringstr1="coolstring";
Stringstr2="88";
Stringfstr=String.format("MyStringis:%1$s,%1$s
and%2$s",str1,str2);
System.out.println(fstr);
Resultis:
MyStringis:coolstring,coolstringand88
260

String Handling In Java
Left padding an integer number with 0's and converting
it into a String using Java String format() method.
int str = 88;
String formattedString = String.format("%05d", str);
System.out.println(formattedString);// 00088
261

String Handling In Java
Displaying String, int, hexadecimal, float, char, octal
value using format() method
String str1 = String.format("%d", 15); // Integer value
String str2 = String.format("%s", "BeginnersBook.com"); // String
String str3 = String.format("%f", 16.10); // Float value
String str4 = String.format("%x", 189); // Hexadecimal value
String str5 = String.format("%c", 'P'); // Char value
String str6 = String.format("%o", 189); // Octal value
262

String Handling In Java
StringBuffer Class
1)AsweknowthatStringobjectsareimmutable,soifwedoalotof
modificationstoStringobjects,wemayendupwithamemory
leak.ToovercomethisweuseStringBufferclass.
2)JavaStringBufferclassisusedtocreatemutable(modifiable)
stringobject.
3)StringBufferclassrepresentsgrowableandwritablecharacter
sequence.Itisalsothread-safei.e.multiplethreadscannotaccessit
simultaneously.
4)Everystringbufferhasacapacity.Aslongasthelengthofthe
charactersequencecontainedinthestringbufferdoesnotexceed
thecapacity,itisnotnecessarytoallocateanewinternalbuffer
array.Iftheinternalbufferoverflows,itisautomaticallymade
larger.
263

String Handling In Java
Constructors of StringBuffer class
1)StringBuffer():Createsanemptystringbufferwiththeinitial
capacityof16.
2)StringBuffer(intcapacity):Createsanemptystringbufferwith
thespecifiedcapacityaslength.
3)StringBuffer(Stringstr):Createsastringbufferinitializedto
thecontentsofthespecifiedstring.
4)StringBuffer(charSequence[]ch):Createsastringbufferthat
containsthesamecharactersasthespecifiedCharSequence.
264

String Handling In Java
Important methods of StringBuffer class
append() method
Theappend()methodconcatenatesthegivenargument(string
representation)totheendoftheinvokingStringBufferobject.
StringBufferclasshasseveraloverloadedappend()method.
StringBuffer append(String str)
StringBuffer append(int n)
StringBuffer append(Object obj)
StringBuffer strBuffer = new StringBuffer("Core");
strBuffer.append("JavaGuru");
System.out.println(strBuffer);
strBuffer.append(101);
System.out.println(strBuffer);
265

String Handling In Java
insert() method
Theinsert()methodinsertsthegivenargument(string
representation)intotheinvokingStringBufferobjectat
thegivenposition.
StringBuffer strBuffer=new StringBuffer("Core");
strBuffer.insert(1,"Java");
System.out.println(strBuffer);
266

String Handling In Java
replace() method
Thereplace()methodreplacesthestringfromspecified
startindextotheendindex.
StringBuffer strBuffer=new StringBuffer("Core");
strBuffer.replace( 2, 4, "Java");
System.out.println(strBuffer);
267

String Handling In Java
reverse() method
ThismethodreversesthecharacterswithinaStringBuffer
object.
StringBuffer strBuffer=new StringBuffer("Core");
strBuffer.reverse();
System.out.println(strBuffer);
268

String Handling In Java
delete() method
Thedelete()methodofStringBufferclassdeletesthe
stringfromthespecifiedbeginIndextoendIndex.
StringBuffer strBuffer=new StringBuffer("Core");
strBuffer.delete( 2, 4);
System.out.println(strBuffer);
269

String Handling In Java
capacity() method
Thecapacity()methodreturnsthecurrentcapacityof
StringBufferobject.Thecapacityistheamountof
storageavailablefornewlyinsertedcharacters,beyond
whichanallocationwilloccur.
StringBuffer strBuffer=new StringBuffer();
System.out.println(strBuffer.capacity());
strBuffer.append("1234");
System.out.println(strBuffer.capacity());
strBuffer.append("123456789112");
System.out.println(strBuffer.capacity());
strBuffer.append("1");
System.out.println(strBuffer.capacity()); //(oldcapacity*2)+2
270

String Handling In Java
271

String Handling In Java
StringBuilder Class
1)StringBuilderobjectsarelikeStringobjects,exceptthattheycan
bemodified.HenceJavaStringBuilderclassisalsousedto
createmutable(modifiable)stringobject.
2)StringBuilderissameasStringBufferexceptforoneimportant
difference.StringBuilderisnotsynchronized,whichmeansitis
notthreadsafe.
3)Thisclassisdesignedforuseasadrop-inreplacementfor
StringBufferinplaceswherethestringbufferwasbeingusedby
asinglethread.
4)InstancesofStringBuilderarenotsafeforusebymultiple
threads.Ifsuchsynchronizationisrequiredthenitis
recommendedthatStringBufferbeused.
272

String Handling In Java
Constructors of StringBuilder class
StringBuilder():Constructsastringbuilderwithno
charactersinitandaninitialcapacityof16characters.
StringBuilder(intcapacity):Constructsastringbuilder
withnocharactersinitandaninitialcapacityspecified
bythecapacityargument.
StringBuilder(Stringstr):Constructsastringbuilder
initializedtothecontentsofthespecifiedstring.The
initialcapacityofthestringbuilderis16plusthelength
ofthestringargument.
273

String Handling In Java
274

275

Exception Handling In Java

Exception Handling In Java
What is an Error?
Errorsarenotexceptionsatall,butproblemsthatarise
beyondthecontroloftheuserortheprogrammer.
SomeErrorsinJavaareVirtualMachineError,
OutOfMemoryError,etc.
Considerasituation,whenaprogramattemptstoallocate
memoryfromtheJVMbutthereisnotenoughspaceto
satisfytheuserrequest.Or,whenaprogramtriestoload
aclassfilebycallingClass.forName()methodandthe
classfileiscorrupt.Suchexceptionsareknownasan
error.
277

Exception Handling In Java
What is an Exception?
AnExceptionisanunexpectedeventthatinterruptsthe
normalflowoftheprogram.Whenanexceptionoccurs
programexecutiongetsterminated.Insuchcaseswegeta
systemgeneratederrormessage.
SomecommonexamplesofExceptionsinJavaare
1)Dividebyzeroerrors
2)Tryingtoaccessthearrayelementswithaninvalid
index
3)Invalidinputdatabytheuser
278

Exception Handling In Java
Difference between error and exception
279
Error Exception
1.Impossibletorecoverfroman
error
1.Possibletorecoverfrom
exceptions
2.Errorsareoftype‘unchecked’2.Exceptionscanbeeither
‘checked’or‘unchecked’
3.Occuratruntime 3.Canoccuratcompiletimeor
runtime
4.Causedbytheapplication
runningenvironment
4.Causedbytheapplication
itself

Exception Handling In Java
What is an Exception Handling? What happen when
Exception is raised?
Todesigntheprograminsuchawaythatevenifthereisan
exception,alloperationsareperformedthenonlytheprogram
shouldbeterminatediscalledexceptionhandling
Wheneveranexceptionoccurswhileexecutingastatement,creates
anexceptionobject(containsalinenumberwheretheexception
occurred,typeofexception)andthenthenormalflowofthe
programhaltsandJREtriestofindsomeonethatcanhandlethe
raisedexception.
ExceptionHandleristheblockofcodethatcanprocessthe
exceptionobject.
280

Exception Handling In Java
281

Exception Handling In Java
Exception Hierarchy
InJavaallexceptionsarerepresentedasanobjectof
classes.AlltheseclassesaresubclassofException.
Throwableisthesuperclasshastwosubclasses
ExceptionandError.
TheExceptionclass,anditssubclasses,isusedto
representexceptionalsituationsinaJavaprogramthat
maybehandledappropriately.
TheErrorclassanditssubclasses,representabnormal
conditionsthatarecausedbytheapplicationrunning
environment.
282

Exception Handling In Java
283

Exception Handling In Java
Types of Exceptions
TherearetwotypesofexceptionsinJava:
1)Checkedexceptions
2)Uncheckedexceptions
CheckedExceptions
Acheckedexceptionisacompile-timeexception,thatis,aJava
compilerchecksornotifiesduringthecompilation-time.The
programmercannotsimplyignoretheseexceptionsandshouldtake
caretohandletheseexceptions.Iftheprogrammerdoesnotwritethe
codetohandlethemthentherewillbeacompilationerror.
A checked exception extends the Exception class. Some checked
Exceptions are SQLException, IOException,
ClassNotFoundException, InvocationTargetException, etc.
284

Exception Handling In Java
Unchecked Exceptions
Anexceptionthatoccursduringtheexecutionofaprogramis
calledanuncheckedoraruntimeexception.
Sothecompilerdoesnotcheckwhethertheprogrammerhas
writtenthecodetohandlethemornotbutitistheresponsibilityof
theprogrammertohandletheuncheckedexceptionsandprovidea
safeexit.
Forexample,ifaprogramattemptstodivideanumberbyzero.Or,
whenthereisanillegalarithmeticoperation,thisimpossibleevent
generatesaruntimeexception.
SomeuncheckedexceptionsareArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException,
NumberFormatException, InputMismatchException,
IllegalStateException,etc.
285

Exception Handling In Java
In Java, exception handling is done using five keywords,
1)try
2)catch
3)throw
4)throws
5)finally
Exception handling is done by transferring the execution
of a program to an appropriate exception handler when
exception occurs.
286

Exception Handling In Java
try block
1)Thetryisusedtodefineablockofcodeinwhichexceptionsmay
occur,itmustbeusedwithinthemethod.
2)Javatryblockmustbefollowedbyeithercatchorfinallyblock.
Nointermediatestatementsareallowedbetweentryandcatch
blockorbetweentryandfinally
3)IfanyexceptionoccursintryblockthenCPUcontrolcomesout
tothetryblockandexecutesappropriatecatchblock.
4)Afterexecutingappropriatecatchblock,CPUcontrolnevergoes
totryblocktoexecutetherestofthestatements.
287

Exception Handling In Java
try{
}
//invalid
try{
}
int x;
catch(Exception e){
e.printStackTrace();
}
//invalid
try{
}
int y;
finally{
}
//invalid
try{
}
catch(Exception e){
e.printStackTrace();
}
//valid
try{
}
finally{
}
//valid
288

Exception Handling In Java
catch block
1)Ifanexceptionoccurswithinthetryblock,itisthrown.The
catchblockcodecatchesthisexceptionandhandleitinsome
rationalmanner
2)Itmustbeusedafterthetryblockonly,youcanusemultiple
catchblockwithasingletry.
3)Catchblockwillexecuteexceptionoccursintryblock.
4)Youcanwritemultiplecatchblocksforhandlingmultiple
exceptionstomakeyourapplicationstrong.
5)Atatimeonlyonecatchblockwillexecuteoutofmultiplecatch
blocks.
6)IncatchblockyoudeclareanobjectofException/subclassofan
ExceptionanditwillbeinternallyreferencedbyJVM.
289

Exception Handling In Java
290

Exception Handling In Java
finally block
1)Javafinallyblockisablockthatisusedtoexecuteimportant
codesuchasclosingconnection,streametc.
2)Innormalcasewhenthereisnoexceptionintryblockthenthe
finallyblockisexecutedaftertryblock.Howeverifanexception
occursthenthecatchblockisexecutedbeforefinallyblock.
3)Thestatementspresentinthefinallyblockexecuteevenifthetry
blockcontainscontroltransferstatementslikereturn,breakor
continue.
4)Ifanexceptionisthrown,finallyruns.Ifanexceptionisnot
thrown,finallyruns.
5)Iftheexceptioniscaught,finallyruns.Iftheexceptionisnot
caught,finallyruns
291

Exception Handling In Java
292

Exception Handling In Java
293

Exception Handling In Java
Note
1)It is illegal to use a try clause without either a catch
clause or a finally clause.
2)Any catch clauses must immediately follow the try
block. Any finally clause must immediately follow the
last catch clause (or it must immediately follow the try
block if there is no catch).
3)It is legal to omit either the catch clause or the finally
clause, but not both.
294

Exception Handling In Java
try-with resources
Generally,whenweuseanyresourceslikestreams,
connections,etc.wehavetoclosethemexplicitlyusing
finallyblock.Inthefollowingprogram,wearereading
datafromafileusingFileReaderandweareclosingit
usingfinallyblock.
try-with-resources,alsoreferredasautomaticresource
management,isanewexceptionhandlingmechanism
thatwasintroducedinJava7,whichautomaticallycloses
theresourcesusedwithinthetrycatchblock
295

Exception Handling In Java
try(FileReader fr = new FileReader("file path")) {
// use the resource
} catch () {
// body of catch
}
}
296

Exception Handling In Java
try with out resource management
FileReader fr = null;
try {
File file = new File("file.txt");
fr = new FileReader(file); char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); // prints the characters one by one
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
297

Exception Handling In Java
try with resource management
try(FileReader fr = new FileReader("E://file.txt")) {
char [] a = new char[50];
fr.read(a); // reads the contentto the array
for(char c : a)
System.out.print(c); // prints the characters one by
one
} catch (IOException e) {
e.printStackTrace();
}
298

Exception Handling In Java
Multiplecatchblocks
1)Morethanoneexceptioncouldberaisedbyasingle
pieceofcode,tohandlesuchasituation,twoor
morecatchclausesarespecified,eachcatchinga
differenttypeofexception.
2)Exceptionsubclassesifanymustcomebeforeany
oftheirsuperclasses.Otherwise,thesubclasswould
neverbereached
299

Exception Handling In Java
try {
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e){
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
catch(Exception e) {
System.out.println(e);
}
300

Exception Handling In Java
Note
Whileusingmultiplecatchstatements,itisimportantto
rememberthatsubclassesofclassExceptioninsidecatch
mustcomebeforeanyoftheirsuperclassesotherwiseit
willleadtocompiletimeerror.ThisisbecauseinJava,if
anycodeisunreachable,thenitgivescompiletimeerror.
301

Exception Handling In Java
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(Exception e) { //This block handles all Exception
System.out.println("Generic exception");
}
catch(ArrayIndexOutOfBoundsException e) { //This
block is unreachable
System.out.println("array index out of bound exception");
}
302

Exception Handling In Java
BeforeJava7,wehadtowritemultipleexception
handlingcodesfordifferenttypesofexceptionsevenif
therewascoderedundancy.
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
303

Exception Handling In Java
In Java SE 7 and later, we can now catch more than one type of exception in a
single catch block.
Each exception type that can be handled by the catch block is separated using a
vertical bar or pipe |.
Its syntax is:
try {
// code
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch block
}
Example
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
304

Exception Handling In Java
If the base exception class has already been specified in
the catch block, do not use child exception classes in the
same catch block. Otherwise, we will get a compilation
error.
Example
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (Exception | ArithmeticException |
ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
305

Exception Handling In Java
throws clause
We have a method myMethod() that has statements may generate either
ArithmeticException or NullPointerException, to handle that use try-catch as
shown below:
public void myMethod(){
try {
// Statements that might throw an exception
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
suppose you have several such methods that can cause exceptions, in that case it
would be tedious to write these try-catch for each method. The code will become
unnecessary long and will be less-readable.
306

Exception Handling In Java
Anymethodthatiscapableofcausingexceptionsmust
listalltheexceptionspossibleduringitsexecution,so
thatanyonecallingthatmethodgetsapriorknowledge
aboutwhichexceptionsaretobehandled.Amethodcan
dosobyusingthethrowskeyword.
Syntax
type method_name(parameter_list) throws exception_list
{
// definition of method
}
307

Exception Handling In Java
throw clause
1)It is used for throw an exception explicitly and catch it.
2)It is used in software testing to test whether a program
is handling all the exceptions as claimed by the
programmer
3)throw clause can be used to throw our own exceptions
308

Exception Handling In Java
Explicitly handling the exception
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
309

Exception Handling In Java
User defined exceptions/Custom exceptions
Rules to design user defined Exception
1)Createapackagewithvaliduserdefinedname.
2)Createanyuserdefinedclass.
3)Makethatuserdefinedclassasderivedclassof
ExceptionorRuntimeExceptionclass.
4)Declareparametrizedconstructorwithstringvariable.
5)callsuperclassconstructorbypassingstringvariable
withinthederivedclassconstructor.
6)Savetheprogramwithpublicclassname.java
310

Exception Handling In Java
311

Exception Handling In Java
Rethrowing an exception
Theremightbesituationsinyourprogramwhereyou
wanttobothcatchanexceptioninyourcodeandalso
wantitscallerbenotifiedabouttheexception.Thisis
possiblebyrethrowingtheexceptionusingthrow
statement.
312

Exception Handling In Java
Calling method Caller method
pubic void divide() {
int x,y,z;
try {
x = 6 ;
y = 0 ;
z = x/y ;
System.out.println(x + "/"+ y +" = " +
z); }
catch(ArithmeticExceptione) {
System.out.println("Exception
Caught in Divide()");
System.out.println("Cannot
Divide by Zero in Integer Division");
throw e; // Rethrows an exception
}
}
public static void main(String[] args) {
System.out.println("Start of main()");
try {
divide();
}
catch(ArithmeticExceptione) {
System.out.println("Rethrown Exception
Caught in Main()");
System.out.println(e);
}
}
313

Exception Handling In Java
Nested try catch block in Java
When a try catch block is present in another try block
then it is called the nested try catch block.
Nested try blocks are useful when different statements of
try block throw different types of exceptions.
Iftheexceptionthrownbytheinnertryblockcannotbe
caughtbyit’scatchblock,thenthisexceptionis
propagatedtooutertryblocks.Anyoneoftheoutercatch
blockshouldhandlethisexceptionotherwiseprogram
willterminateabruptly.
314

Exception Handling In Java
try { //Outer try block
//Some Statements
try { //Inner try block
//Some Statements
}
catch (Exception ex) { //Inner catch block
}
}
catch(Exception ex) { //Outer catch block
}
315

Exception Handling In Java
String[] s = {"abc", "123", null, "xyz"}; //String array containing one null object
for (int i = 0; i < s.length; i++){
try { //Outer try block
int a = s[i].length(); //may throw NullPointerException
try { //Inner try block
a = Integer.parseInt(s[i]); //may throw NumberFormatException
}
catch (NumberFormatException ex){ //Inner catch block
System.out.println("NumberFormatException will be caught here");
}
}
catch(NullPointerException ex){ //Outer catch block
System.out.println("NullPointerException will be caught here");
}
316

Exception Handling In Java
Exception Propagation
Consideringascenario,inwhichyourprogramstartsitsexecution
atthemain()method,main()callsmethod1(),method1()calls
method2(),method2()callsmethod3(),nowthecallstackshould
looklikethefigurebelow-:
317

Exception Handling In Java
Thecurrentlyexecutingmethodisatthetopofthecall
stack,whichinthisexampleismethod3().Let'ssaywhile
executingmethod3(),anexceptionisraised/thrown.Now
thisexceptionisthrowndowntothenextmethodinthe
callstack,i.e.method2(),whichinturnthrowsthe
exceptiondowntonextmethodinthecallstack,i.e.
method1().Theprocesscontinuesuntiltheexceptionis
throwntothemethodatthebottomofthecallstack,i.e.
main()method.Thisprocessiscalledexception
propagation
318

Exception Handling In Java
class Exp{
public static void main(String... ar){
Exp ob = new Exp();
ob.method1();
}
public void method1(){
method2();
}
public void method2(){
method3();
}
public void method3(){
System.out.println(100/0);//ArithmeticException is raised/thrown by the program.
System.out.println("Hello"); //This statement will not be executed.
}
}
319

Problem Statements

Student Party
Whenstudentsgettogetherforaparty,theyliketohave
beers.Astudentpartyissuccessfulwhenthenumberof
beersisbetween40and60inclusive.Ifitistheweekend
thereisnoupperboundonthenumberofbeers.Return
trueifthepartywiththegivenvaluesissuccessful,or
falseotherwise.Print‘PartyIsSuccessful’whenreturn
trueotherwiseprint‘PartyIsFailure’.
publicBooleanparty(intbeers,BooleanisWeekend)
{
}
321

Exception Handling In Java
322

323

324

Multithreading In Java

Multithreading In Java
Process Vs Thread
Anexecutingprogramiscalledaprocess.Eachprocesscanhavea
singlethreadormultiplethreads.Sothatthethreadisthesmallest
unitofaprocessthatcanrunconcurrentlywiththeotherparts
(otherthreads)ofthesameprocess.
326

Multithreading In Java
Process Thread
Anexecutingprogramiscalledaprocess.Athreadisasmallpartofaprocess.
Everyprocesshasitsseparateaddressspace.Allthethreadsofaprocesssharethesame
addressspaceofaprocess.
Process-basedmultitaskingallowsa
computertoruntwoormorethantwo
programsconcurrently.
Thread-basedmultitaskingallowsasingle
programtoruntwoormorethreads
concurrently.
Communicationbetweentwoprocessesis
expensiveandlimited.
Communicationbetweentwothreadsisless
expensiveascomparedtoprocess.
Contextswitchingfromoneprocessto
anotherprocessisexpensive.
Contextswitchingfromonethreadto
anotherthreadislessexpensiveascompared
toprocess.
Aprocesshasitsownaddressspace,global
variables,signalhandlers,openfiles,child
processes,accountinginformation.
Athreadhasitsownregister,state,stack,
programcounter.
327

Multithreading In Java
Multitasking
MultitaskingiswhenasingleCPUperformsseveraltasks
atthesametime.Toperformmultitasking,theCPU
switchesamongthesestasksveryfrequentlysothatuser
caninteractwitheachprogramsimultaneously.
328

Multithreading In Java
Multithreading
Aprocesscanhavemultiplethreadssimultaneously,and
theCPUswitchesamongthesethreadssofrequently
makinganimpressionontheuserthatallthreadsare
runningsimultaneouslyandthisiscalledmultithreading
329

Multithreading In Java
Multitasking Multithreading
Inmultitasking,thesystemallows
executingmultipleprogramsand
tasksatthesametime
Inmultithreading,thesystem
executesmultiplethreadsofthe
sameordifferentprocessesatthe
sametime.
Inmultitasking,CPUhasto
switchbetween multiple
programssothatitappearsthat
multipleprogramsarerunning
simultaneously.
InmultithreadingCPUhasto
switchbetweenmultiplethreads
tomakeitappearthatallthreads
arerunningsimultaneously.
Multitaskingallocatesseparate
memoryandresourcesforeach
process/program
Inmultithreadingthreads
belongingtothesameprocess
sharesthesamememoryand
resourcesasthatoftheprocess.
330

Multithreading In Java
Achieve multithreading in java
Injavalanguagemultithreadingcanbeachieveintwo
differentways.
1)UsingThreadclass
2)UsingRunnableinterface
331

Multithreading In Java
Using Thread Class
1)Create any user defined class and make that one as a derived
class of Thread class.
class MyThread extends Thread{ }
2)Override run() method of Thread class (It contains the logic of
perform any operation)
3)Create an object for user-defined thread class and attached that
object to predefined thread class object.
MyThread obj=new MyThread();
Thread t=new Thread(obj);
4)Call start() method of thread class to execute the thread
t.start();
332

Multithreading In Java
333

Multithreading In Java
Using Runnable Interface
1)DefinetheclassthatimplementstheRunnableinterface
andimplementtherun()methodoftheRunnable
interfaceintheclass.
2)Createaninstanceofthedefinedclass.
3)CreateaninstanceoftheThreadclassusingtheThread
(Runnabletarget)constructor.
4)Startthethreadbyinvokingthestart()methodonyour
Threadobject.
334

Multithreading In Java
Why don’t we call run() method directly, why call start() method?
1)Whenyoudirectlycalltherun()methodthenthecodeinsiderun()methodis
executedinthesamethreadwhichcallstherunmethod.JVMwillnotcreatea
newthreaduntilyoucallthestartmethod.
2)Ontheotherhand,whenyoucalltheThread.start()method,thenthecode
insiderun()methodwillbeexecutedonanewthread,whichisactually
createdbythestart()method.
3)Youcancalltherunmethodmultipletime,JVMwillnotthrowanyerrorbut
whenyoucannotcallthestart()methodonsamethreadinstance.
4)Thefirsttime,t.start()willcreateanewthreadbutthesecondtimeitwill
throwjava.lang.IllegalStateException,becausethethreadisalreadystarted
andyoucannotrestartitagain,youcanonlypauseathreadinJava.
335

Multithreading In Java
Directly calling the run() method
336
public void run(){
for(inti=1;i<=3;i++){
try{
Thread.sleep(1000);
}
catch(InterruptedExceptionie){
ie.printStackTrace();
}
System.out.println(i);
}
}
public static void main(String args[]){ Thread
th1 = new Thread(new RunMethodExample(),
"th1");
Thread th2 = new Thread(new
RunMethodExample(), "th2"); th1.run();
th2.run();
}

Multithreading In Java
Execute the thread by using start()method
337
public void run(){
for(inti=1;i<=3;i++){
try{
Thread.sleep(1000);
}
catch(InterruptedExceptionie){
ie.printStackTrace();
}
System.out.println(i);
}
public static void main(String args[]){
Thread th1 = new Thread(new
RunMethodExample(), "th1");
Thread th2 = new Thread(new
RunMethodExample(), "th2"); th1.start();
th2.start();
}

Multithreading In Java
Difference between Thread and Runnable
338
Thread Class Runnable Interface
Eachthreadcreatesauniqueobjectandgets
associatedwithitsomorememoryrequired.
Multiplethreadssharethesameobjects.
Solessmemoryisused.
InJava,multipleinheritancenotallowed
hence,afteraclassextendsThreadclass,it
cannotextendanyotherclass.
Ifaclassdefinethreadimplementingthe
Runnableinterfaceithasachanceof
extendingoneclass.
Ausermustextendthreadclassonlyifit
wantstooverridetheothermethodsin
Threadclass.
Ifyouonlywanttospecializerunmethod
thenimplementingRunnableisabetter
option.
ExtendingThreadclassintroducestight
couplingastheclasscontainscodeof
Threadclassandalsothejobassignedtothe
thread
ImplementingRunnableinterfaceintroduces
loosecouplingasthecodeofThreadis
separateformthejobofThreads.

Multithreading In Java
Thread Life Cycle
The various states of java thread
1) New
2) Runnable
3) Running
4) Waiting
5) Timed Waiting
6) Blocked
7) Terminated
339

Multithreading In Java
340

Multithreading In Java
New State
1)WheneverwecreateaninstanceofThread,Threadgets
astatecalled“New”state.
2)Inthiscase,Threadisjustcreatedbutnotstarted,in
otherwordswehaveathreadobjectbutthereisno
threadexecution.
Threadt1=newThread();
341

Multithreading In Java
Runnable State
1)Wheneverwestartthethreaditmovesfrom“New”
stateto“Runnable”state.
2)Inthiscase,threadisreadytobeexecutedbutit’sjust
waitingfortheThreadschedulertopickitfor
execution.
3)Inthisstate,anewcallstackwillbecreatedforthe
thread.
4)Belowlinetakesthethreadfrom“New”stateto“
Runnable”state.
t.start();
342

Multithreading In Java
Running State
1)This is not the standard thread state defined by Java but its used to indicate that the
thread is currently running or executing the logic.
2)Moving thread from “ Runnable ” state to “ Running ” state is entirely dependent
on Thread scheduler. Thread scheduler is the one which decides whether to move
the thread from “ Runnable ” state to “ Running ” state or put it on hold in “
Runnable ” state by giving chance to other Runnable threads.
3)Thread scheduler is operating system dependent most of the operating systems
follow Round-robin scheduling. In this case, each thread is given a fixed amount of
processor time called as “ quantum ” or “ time slice ” within which it has to
execute.
4)Any thread which has got this time slice to execute its task is said to be in “
Running ” state.
5)Once time slice expires, thread will be returned to “ Runnable ” state and another
thread will be assigned to the processor.
6)This process that operating system uses to determine which thread has to go from “
Runnable ” state to “ Running ” state is called “ Thread scheduling ”
343

Multithreading In Java
Waiting State
1)In this case,Thread will be moved from “ Running ”
state to “ Waiting ” state by calling its wait() method.
2)This can be done whenever we want currently running
thread to wait for some other thread to execute and
notify back to it to continue the execution.
3)Once the thread wait is notified , then the waited thread
will be moved to “ Runnable ” state.
344

Multithreading In Java
Timedwaitingstate
1)Inthiscase,Threadwillbemovedfrom“Running”
stateto“Waiting”statewithspecifiedwaitingtime.
2)Thiscanbedonewheneverwewantcurrentlyrunning
threadtowaitforsomespecifiedamountoftime.
3)Oncethespecifiedamountoftimeiscompleted,then
thewaitedthreadwillbemovedto“Runnable”state.
4)Wecanputthethreadto“Timedwaiting”bycalling
sleep(longmillis)orwait(longmillis)method
345

Multithreading In Java
BlockedState
1)Inthiscase,threadwillbemovedfrom“Running”
stateto“Blocked”state.
2)Thiscanhappenduetovariousreasonslike
1)CurrentthreadmighttrytoreaddatafromIOstreambut
thereisnotdatatoread.
2)Threadmightbewaitingtoacquirethelocktoenter
synchronizedblock.
3)Threadwillbemovedfrom"Blocked"stateto“
Runnable”stateoncethedataonthestreamis
availableorlockisreleasedbyotherthread.
346

Multithreading In Java
TerminatedState
1)ThreadwillbemovedtoTerminatedstate(alsocalled
Deadstate)whenitcompletesitsexecution
successfully.
2)Itcanalsobeterminatedforcefullybykillingit.
347

Multithreading In Java
Terminating the Thread
A thread will terminate automatically when it comes out of run() method.
To terminate the thread on our own the following steps can be used
1)Create a boolean type variable and initialize it to false
boolean stop=false;
2)Let us assume that we want to terminate the thread when the user
press<Enter>key. So, when the user press that button, make the boolean type
variable as true
stop=true;
3)Check this variable in run()method and when it is true, make the thread return
from the run() method.
public void run(){
if(stop==true)return;
}
348

Multithreading In Java
Single Tasking Using a Thread
1)Athreadcanbeemployedtoexecuteonetaskatatime.Suppose
thereare3taskstobeexecuted.Wecancreateasinglethread
andpassthese3tasksonebyonetothethreadiscalledassingle
taskingusingathread.
2)Forthispurpose,wecanwriteallthesetasksseparatelyin
separatemethods:task1(),task2(),task3().
3)Thenthesemethodsshouldbecalledfromrun()method,oneby
one.
4)Athreadexecutesonlythecodeinsidetherun()method.Itcan
neverexecuteothermethodsunlesstheyarecalledfromrun().
349

Multithreading In Java
Multi Tasking Using Threads
Inmultitasking,severaltasksareexecutedatatime.For
thispurposeweneedmorethanonethread.
Forexample,toperform2tasks,wecantake2threads
andattachthemtothe2tasks.Thenthosetasksare
simultaneouslyexecutedbytwothreads.Thisiscalled
asmultithreading
350

Multithreading In Java
Whenwegotoamovietheatre,generallyapersonisthereatthedoor-checkingand
cuttingthetickets.Whenweenterthehall,thereisanotherpersonwhoshowsthe
seatsforus.
Supposethereisonlyoneperson(1thread)doingthesetwotasks.Hehastofirst
cuttheticketandthencomealongwithustoshowtheseat.Thenhegoesbackto
thedoortocutthesecondticketandthenagainenterthehalltoshowtheseatfor
secondticket.
Likethis,ifheisdoesthethingsonebyone,ittakesalotoftime,andeventhough
theshowisover,therewillbestillafewpeopleleftoutsidethedoorwaitingto
enterthehall.
Thesolutionistheatremanagementemploytwopersons(2threads)forthispurpose.
Thefirstpersonwillcuttheticket,andthesecondpersonwillshowtheseat.
Whenthesecondpersonisshowingtheseat,thefirstpersoncutthesecondticket.
Likethis,boththepersonscanactsimultaneouslyandhencetherewillbeno
wastageoftime.
351

Multithreading In Java
Multiple Threads Acting on Single Object
•Multiplethreadsactingonsingleobjectmeanstwoormorethreadsshould
sharethesameobject(samerun()method).Inthiscasewegetunreliable
results
•Forexample,takethecaseofrailwayreservationsystem.Everydayseveral
peoplewantreservationofaberthforthem.Theproceduretoreservethe
berthissameforallthepeople.Soweneedsameobjectwithsamerun()
methodtobeexecutedrepeatedlyforallthepeople
•Letusthinkthatonlyoneberthisavailableinatrain,andtwopassengersare
askingthatberth.Inreservationcounterno.1,theclerkhassentarequestto
theservertoallotthatberthtohispassenger.Incounterno.2,thesecondclerk
hasalsosentarequesttotheservertoallotthatberthtohispassenger.Letus
seenowtowhomthatberthisallotted.
352

Multithreading In Java
Thread Synchronization
Whenevermultiplethreadsaretryingtousesameresourcethan
theymaybechancetoofgettingwrongoutput,toovercomethis
problemthreadsynchronizationcanbeused.
Allowingonlyonethreadatatimetoutilizedthesameresource
outofmultiplethreadsisknownasthreadsynchronizationor
threadsafe.
Injavathreadsynchronizationcanbeachieveintwodifferent
ways.
Synchronizedblock
Synchronizedmethod
353

Multithreading In Java
Synchronizedblock
•Wheneverwewanttoexecuteoneormorethanone
statementbyasinglethreadatatime(notallowingother
threaduntilthreadoneexecutioniscompleted)than
thosestatementshouldbeplacedinsidesynchronized
block.
354

Multithreading In Java
Synchronizedmethod
•Wheneverwewanttoallowonlyonethreadatatime
amongmultiplethreadforexecutionofamethodthan
thatshouldbedeclaredassynchronizedmethod.
355

Multithreading In Java
356

Multithreading In Java
Differencebetweensynchronizedkeywordandsynchronizedblock
Whenweusesynchronizedkeywordwithamethod,itacquiresalockinthe
objectforthewholemethod.Itmeansthatnootherthreadcanuseany
synchronizedmethoduntilthecurrentthread,whichhasinvokedit's
synchronizedmethod,hasfinisheditsexecution.
synchronizedblockacquiresalockintheobjectonlybetweenparenthesesafter
thesynchronizedkeyword.Thismeansthatnootherthreadcanacquirealock
onthelockedobjectuntilthesynchronizedblockexits.Butotherthreadscan
accesstherestofthecodeofthemethod.
Whichismorepreferred-SynchronizedmethodorSynchronizedblock?
InJava,synchronizedkeywordcausesaperformancecost.Asynchronized
methodinJavaisveryslowandcandegradeperformance.Sowemustuse
synchronizationkeywordinjavawhenitisnecessaryelse,weshoulduseJava
synchronizedblockthatisusedforsynchronizingcriticalsectiononly.
357

Multithreading In Java
Deadlockinthreads
•DeadlockisasituationofcompleteLock,whenno
threadcancompleteitsexecutionbecauselackof
resources.Inthebpicture,Thread1isholdinga
resourceR1,andneedanotherresourceR2tofinish
execution,butR2islockedbyThread2,whichneeds
R3,whichinturnislockedbyThread3.Hencenoneof
themcanfinishandarestuckinadeadlock.
358

Multithreading In Java
359

Multithreading In Java
•Tobookaticket,thethreadwillenterthetrainobjecttoverify
thattheticketisavailableornot.Whenthereisaticket,it
updatestheavailablenumberofticketsinthetrainobject.For
this,ittakes,150milliseconds.Thenitentersthecompartment
object.Incompartmentobject,itshouldallottheticketforthe
passengerandupdateitsstatustoreserved.Thismeansthethread
shouldgothroughboththetrainandcompartmentobjects.
•Letusthinkifathreadhastocancelaticket,itwillfirstenter
compartmentobject,andupdatesthestatusoftheticketas
available.Forthisitistaking200milliseconds.Thenitenters
trainobjectandupdatestheavailablenumberofticketsthere.
So,thisthreadalsoshouldgothroughboththecompartmentand
trainobjects
360

Multithreading In Java
•WhenBookTicketthreadisattrainobjectfor150milliseconds,the
CancelTicketthreadwillbeatcompartmentobjectfor200milliseconds.We
areusingmultiplethreadsweshouldsynchronizethem.So,thethreadswill
lockthoseobjects
•When150millisecondstimeisover,BookTicketthreadtriestocomeoutof
trainobjectandwantstolockoncompartmentobject,byenteringit.Atthat
time,itwillfindthatthecomaprtmentobjectisalreadylockedbyanother
thread(CancelTicket)andhenceitwillwait,BookTicketthreadwillwaitfor
compartmentobjectforanother50milliseconds.
•After200millisecondstimeisup,theCancelTicketthreadwhichisin
compartmentobjectcompletesitsexecutionandwantstoenterandlockon
trainobject.Butitwillfindthatthetrainobjectislareadyunderlockby
BookTicketthreadandhenceisnotavailable.Now,CancelTicketwillwaitfor
thetrainobjectwhichshouldbeunlockedbyBookTicket.
•Boththethreadswillwaitforeverinthisway,suspendinganyfurther
execution.Thissituationiscalled‘ThreadDeadlock’.
361

Multithreading In Java
Thread Priorities
1)EverythreadinJavahasaprioritythathelpsthethreadscheduler
todeterminetheorderinwhichthreadsscheduled.
2)Thethreadswithhigherprioritywillusuallyrunbeforethan
lowerprioritythreads.
3)Bydefault,allthethreadshadthesamepriority.
4)However,youcanexplicitlysetathread'spriorityatanytime
afteritscreationbycallingitssetPriority()method.
5)Thismethodacceptsanargumentoftypeintthatdefinesthenew
priorityofthethread.Itssyntaxis.
finalvoidsetPriority(intpriority)
362

Multithreading In Java
6)Priorityisanintegervaluethatmustrangebetween1and10,with10being
thehighestpriority,1beingthelowestand5beingthedefault.
7)Ifyouspecifyaprioritythatisoutofrange,thenan
IllegalArgumentExceptionexceptionthrown.
8)Somethreadprioritiesarestaticmembervariablesofjava.lang.Threadclass.
9)TheseincludeMIN_PRIORITY, NORM_PRIORITY, and
MAX_PRIORITYrepresentingvalues1,5and10respectively.
10)ThepriorityofthemainthreadisThread.NORM_PRIORITY,i.e.,5.
NOTE:Generallyhigherprioritythreadscanbeexpectedtobegivenpreference
bythethreadscheduleroverlowerprioritythreads.However,the
implementationofthreadschdulingisleftuptotheJVMimplementation.
363

Multithreading In Java
364

Multithreading In Java
The Methods to Prevent a Thread from Execution
Wecanprevent(stop)aThreadexecutionbyusingthe
followingmethods.
1)yield();
2)join();
3)sleep();
365

Multithreading In Java
yield() method
1)yield()methodcauses"topausecurrentexecutingThreadfor
givingthechanceofremainingwaitingThreadsofsame
priority".
2)IfallwaitingThreadshavethelowpriorityorifthereisno
waitingThreadsthenthesameThreadwillbecontinuedits
execution.
3)IfseveralwaitingThreadswithsamepriorityavailablethenwe
can'texpectexactwhichThreadwillgetchanceforexecution.
4)TheThreadwhichisyieldedwhenitgetchanceonceagainfor
executionisdependsonmercyoftheThreadscheduler.
publicstaticnativevoidyield()
Note:Someoperatingsystemsmaynotprovidepropersupport
foryield()method.
366

Multithreading In Java
367

Multithreading In Java
join() method
IfaThreadwantstowaituntilcompletingsomeother
Threadthenweshouldgoforjoin()method.
Example:IfaThreadt1executest2.join()thent1should
goforwaitingstateuntilcompletingt2.
Note
Everyjoin()methodthrowsInterruptedException,which
ischeckedexceptionhencecompulsoryweshould
handleeitherbytrycatchorbythrowskeyword.
368

Multithreading In Java
369

Multithreading In Java
YouhavethreethreadsT1,T2,andT3,Howdoyouensurethat
theyfinishinorderT1,T2,T3?.
Youcandothisbyusingjoinmethod,bycallingT1.join()fromT2
andT2.join()fromT3.Inthiscasethread,T1willfinishfirst,
followedbyT2andT3.
370

Multithreading In Java
sleep() method
IfaThreaddon'twanttoperformanyoperationfora
particularamountoftimethenweshouldgoforsleep()
method.
publicstaticnativevoidsleep(longms)throws
InterruptedException
publicstaticvoidsleep(longms,intns)throws
InterruptedException
371

Multithreading In Java
372

Multithreading In Java
Interrupting a Thread
HowaThreadcaninterruptanotherthread?
IfaThreadcaninterruptasleepingorwaitingThreadbyusinginterrupt()(break
off)methodofThreadclass.
publicvoidinterrupt()
Note
1)Wheneverwearecallinginterrupt()methodwemaynotseetheeffect
immediately,ifthetargetThreadisinsleepingorwaitingstateitwillbe
interruptedimmediately.
2)IfthetargetThreadisnotinsleepingorwaitingstatetheninterruptcallwill
waituntiltargetThreadwillenterintosleepingorwaitingstate.Oncetarget
Threadenteredintosleepingorwaitingstateitwilleffectimmediately.
3)InitslifetimeifthetargetThreadneverenteredintosleepingorwaitingstate
thenthereisnoimpactofinterruptcallsimplyinterruptcallwillbewasted.
373

Multithreading In Java
Daemon Thread
Javadefinestwotypesofthread:userthread(normal
thread)anddaemonthread.Bydefault,whenyoucreate
anewthreaditisuserthread.TheJavaVirtualMachine
(JVM)won’tterminateiftherearestilluserthreads
running.Butitwillexitifthereareonlydaemon
threadsrunning.
Daemonthreadshavelowerprioritythannormalones,so
theyareusedforrunningbackgroundservicesthat
serveuserthreads.Anexampleofdaemonthreadinthe
JVMisthegarbagecollectorthreadthatrunssilentlyin
thebackgroundtofreeunusedmemory.
374

Multithreading In Java
MethodsofThreadclassthatarerelatedtoDaemon
threads:
publicvoidsetDaemon(booleanstatus)
ThismethodisusedformakingauserthreadtoDaemonthreadorviceversa.
ForexampleifIhaveauserthreadtthent.setDaemon(true)wouldmakeit
Daemonthread.
OntheotherhandifIhaveaDaemonthreadtdthenbycalling
td.setDaemon(false)wouldmakeitnormalthread(userthread/non-daemon
thread).
publicbooleanisDaemon()
Thismethodisusedforcheckingthestatusofathread.Itreturnstrueifthe
threadisDaemonelseitreturnsfalse.
375

Multithreading In Java
Note
setDaemon()methodcanonlybecalledbeforestarting
thethread.Thismethodwouldthrow
IllegalThreadStateExceptionifyoucallthismethod
afterThread.start()method.
376

Multithreading In Java
Inter Thread Communication
Polling Problem
Theprocessoftestingaconditionrepeatedlytillitbecomestrueis
knownaspolling.
Example
Supposethattheproducerhastowaituntiltheconsumerisfinished
beforeitgeneratesmoredata.Inapollingsystem,theconsumer
wouldwastemanyCPUcycleswhileitwaitsfortheproducerto
produce.Oncetheproducerhasfinished,itwouldstartpolling,
wastingmoreCPUcycleswaitingfortheconsumertofinish,and
soon.
377

Multithreading In Java
Thesolutionforpollingproblemisinter-threadcommunication
Inter-threadcommunication
Inter-threadcommunicationisaprocessinwhichathreadis
pausedrunninginitscriticalregionandanotherthreadisallowed
toenter(orlock)inthesamecriticalregiontobeexecuted.i.e.
synchronizedthreadscommunicatewitheachother.
Forinter-threadcommunicationjavaprovidesthreemethodsthey
arewait(), notify() and notifyAll().
Allthesemethodsbelongtoobjectclassasfinalsothatallclasses
havethem.Theymustbeusedwithinasynchronizedblockonly.
378

Multithreading In Java
•wait()-Ittellsthecallingthreadtogiveupthelockandgoto
sleepuntilsomeotherthreadentersthesamemonitorandcalls
notify().
•notify()-Itwakesuponesinglethreadthatcalledwait()onthe
sameobject.Itshouldbenotedthatcallingnotify()doesnot
actuallygiveupalockonaresource.
•notifyAll()-Itwakesupallthethreadsthatcalledwait()onthe
sameobject.
379

Multithreading In Java
ThreadGroup in Java
1)AThreadGrouprepresentsasetofthreads.Sowecansuspend,
resumeorinterruptgroupofthreadsbyasinglemethodcall.
2)Athreadgroupcanalsoincludetheotherthreadgroup.The
threadgroupcreatesatreeinwhicheverythreadgroupexcept
theinitialthreadgrouphasaparent.
3)Athreadisallowedtoaccessinformationaboutitsownthread
group,butitcannotaccesstheinformationaboutitsthread
group'sparentthreadgrouporanyotherthreadgroups.
4)Javathreadgroupisimplementedbyjava.lang.ThreadGroup
class.
380

Multithreading In Java
381

Multithreading In Java
Constructors of ThreadGroup class
ThreadGroup(String name)
creates a thread group with given name.
ThreadGroup base = new ThreadGroup("Base");
ThreadGroup(ThreadGroup parent, String name)
creates a thread group with given parent group and
name.
ThreadGroup group1 = new ThreadGroup(base,
"Group1");
382

Multithreading In Java
Important methods of ThreadGroup class
activeCount():returnsanestimateofthenumberofactivethreadsin
thethreadgroupanditssubgroups.
destroy():destroysthethreadgroupandallofitssubgroups.
enumerate(Thread[]list):copiesintothespecifiedarrayeveryactive
threadinthisthreadgroupanditssubgroups.
getMaxPriority():returnsthemaximumpriorityofthethreadgroup.
interrupt():interruptsallthreadsinthethreadgroup.
isDaemon():testsifthethreadgroupisadaemonthreadgroup.
setMaxPriority(intpriority):setsthemaximumpriorityofthe
group.
383

Multithreading In Java
Thread Pool
1)Intermsofperformance,creatinganewthreadisanexpensive
operationbecauseitrequirestheoperatingsystemallocates
resourcesneedforthethread.
2)Insteadofcreatingnewthreadswhennewtasksarrive,athread
poolkeepsanumberofidlethreadsthatarereadyforexecuting
tasksasneeded.Afterathreadcompletesexecutionofatask,it
doesnotdie.Insteaditremainsidleinthepoolwaitingtobe
chosenforexecutingnewtasks.
3)Youcanlimitadefinitenumberofconcurrentthreadsinthe
pool,whichisusefultopreventoverload.Ifallthreadsarebusily
executingtasks,newtasksareplacedinaqueue,waitingfora
threadbecomesavailable.
384

Multithreading In Java
TheJavaConcurrencyAPIsupportsthefollowingtypesofthread
pools:
1)Cachedthreadpool:keepsanumberofalivethreadsandcreates
newonesasneeded.
2)Fixedthreadpool:limitsthemaximumnumberofconcurrent
threads.Additionaltasksarewaitinginaqueue.
3)Single-threadedpool:keepsonlyonethreadexecutingonetask
atatime.
4)Fork/Joinpool:aspecialthreadpoolthatusestheFork/Join
frameworktotakeadvantagesofmultipleprocessorstoperform
heavyworkfasterbybreakingtheworkintosmallerpieces
recursively.
385

Multithreading In Java
What is an Executor?
AnExecutorisanobjectthatisresponsibleforthreadsmanagementand
executionofRunnabletaskssubmittedfromtheclientcode.Itdecouplesthe
detailsofthreadcreation,scheduling,etcfromthetasksubmissionsoyoucan
focusondevelopingthetask’sbusinesslogicwithoutcaringaboutthethread
managementdetails.
Thatmeans,ratherthancreatingathreadtoexecuteatasklikethis:
Threadt=newThread(newRunnableTask());
t.start();
Yousubmittaskstoanexecutorlikethis:
Executorexecutor=anExecutorImplementation;
executor.execute(newRunnableTask1());
executor.execute(newRunnableTask2());
386

Multithreading In Java
TheJavaConcurrencyAPIdefinesthefollowing3baseinterfaces
forexecutors:
1)Executor:isthesupertypeofallexecutors.Itdefinesonlyone
methodexecute(Runnable).
2)ExecutorService:isanExecutorthatallowstrackingprogressof
value-returningtasks(Callable)viaFutureobject,andmanages
theterminationofthreads.Itskeymethodsincludesubmit()and
shutdown().
3)ScheduledExecutorService:isanExecutorServicethatcan
scheduletaskstoexecuteafteragivendelay,ortoexecute
periodically.Itskeymethodsareschedule(),
scheduleAtFixedRate()andscheduleWithFixedDelay().
387

Multithreading In Java
Youcancreateanexecutorbyusingoneofseveralfactorymethodsprovidedby
theExecutorsutilityclass.
1)newCachedThreadPool():createsanexpandablethreadpoolexecutor.New
threadsarecreatedasneeded,andpreviouslyconstructedthreadsarereused
whentheyareavailable.Idlethreadsarekeptinthepoolforoneminute.This
executorissuitableforapplicationsthatlaunchmanyshort-livedconcurrent
tasks.
2)newFixedThreadPool(intn):createsanexecutorwithafixednumberof
threadsinthepool.Thisexecutorensuresthattherearenomorethann
concurrentthreadsatanytime.Ifadditionaltasksaresubmittedwhenall
threadsareactive,theywillwaitinthequeueuntilathreadbecomesavailable.
Ifanythreadterminatesduetofailureduringexecution,itwillbereplacedby
anewone.Thethreadsinthepoolwillexistuntilitisexplicitlyshutdown.
Usethisexecutorifyouandtolimitthemaximumnumberofconcurrent
threads.
388

Multithreading In Java
3)newSingleThreadExecutor():createsanexecutorthatexecutesa
singletaskatatime.Submittedtasksareguaranteedtoexecute
sequentially,andnomorethanonetaskwillbeactiveatany
time.Considerusingthisexecutorifyouwanttoqueuetasksto
beexecutedinorder,oneafteranother.
4)newScheduledThreadPool(intcorePoolSize):createsan
executorthatcanscheduletaskstoexecuteafteragivendelay,
ortoexecuteperiodically.Considerusingthisexecutorifyou
wanttoscheduletaskstoexecuteconcurrently.
5)newSingleThreadScheduleExecutor():createsasingle-threaded
executorthatcanscheduletaskstoexecuteafteragivendelay,
ortoexecuteperiodically.Considerusingthisexecutorifyou
wanttoscheduletaskstoexecutesequentially.
389

Multithreading In Java
390

Multithreading In Java
391

Multithreading In Java
392

Multithreading In Java
393

394

Collection framework

Collection framework
What is a collection?
Intermsofprogramming,acollectionisadatastructure
thatholdsasetofobjectsinaspecificmanner.
Itlookslikearraysbutcollectionsaremoreadvancedand
moreflexible.
Anarraysimplystoresafixednumberofobjects,
whereasacollectionstoresvariablenumberofobjects
dynamically,i.e.youcanaddorremoveobjectsasyou
wish.
Acollectionalsoprovidesusefuloperationssuchas
adding,removing,retrievingobjects.
396

Collection framework
What is Collection Framework
1)ACollectionFrameworkinJavaisaunifiedarchitecturethat
representsacollectionofinterfacesandclasses.Ithelpsinstoring
andprocessingthedataefficiently.
2)JavaCollectionsFrameworkprovidesusefulandrobust
algorithmssuchassearchingandsortingoncollections,andthe
interoperabilitybetweencollectionsandarrays.
3)TheJavacollectionsframeworkprovidesvariousdatastructures
andalgorithmsthatcanbeuseddirectly.Itmeanswedonothave
towritecodetoimplementthesedatastructuresandalgorithms
manually.
4)ThetwoprincipalrootinterfacesofJavacollectionclassesare
CollectioninterfaceandMapinterface.
397

Collection framework
Collection Framework Hierarchy
398

Collection framework
Collection Interface
TheCollectioninterfaceisthefoundationuponwhichthe
collectionsframeworkisbuilt.Itdeclaresthecore
methodsthatallcollectionswillhave.
399

Collection framework
Some important methods of Collection interface
400
S.No Method Name Description
1 booleanadd(Objectobj) Addsobjtotheinvokingcollection.Returnstrue
ifobjwasaddedtothecollection.Returnsfalse
ifobjisalreadyamemberofthecollection,
whenthatcollectiondoesnotallowduplicates.
2 booleanaddAll(Collectionc) Addsalltheelementsofctotheinvoking
collection.Returnstrueiftheoperationsucceeds
(i.e.,theelementswereadded).Otherwise,
returnsfalse.
3 voidclear() Removesallelementsfromtheinvoking
collection.
4 booleancontains(Objectobj) Returnstrueifobjisanelementoftheinvoking
collection.Otherwise,returnsfalse.

Collection framework
5 booleancontainsAll(Collectionc)Returnstrueiftheinvokingcollectioncontainsall
elementsofc.Otherwise,returnsfalse.
6 booleanequals(Objectobj) Returnstrueiftheinvokingcollectionandobjare
equal.Otherwise,returnsfalse.
7 inthashCode() Returnsthehashcodefortheinvokingcollection.
8 booleanisEmpty() Returnstrueiftheinvokingcollectionisempty.
Otherwise,returnsfalse.
9 Iteratoriterator() Returnsaniteratorfortheinvokingcollection.
10booleanremove(Objectobj) Removesoneinstanceofobjfromtheinvoking
collection.Returnstrueiftheelementwas
removed.Otherwise,returnsfalse.
11booleanremoveAll(Collectionc)Removesallelementsofcfromtheinvoking
collection.Returnstrueifthecollectionchanged
(i.e.,elementswereremoved).Otherwise,returns
false. 401

Collection framework
12booleanretainAll(Collectionc) Removesallelementsfromtheinvoking
collectionexceptthoseinc.Returnstrueif
thecollectionchanged(i.e.,elementswere
removed).Otherwise,returnsfalse.
13intsize()
.
Returnsthenumberofelementsheldinthe
invokingcollection
14Object[]toArray() Returnsanarraythatcontainsalltheelements
storedintheinvokingcollection.Thearray
elementsarecopiesofthecollection
elements.
15Object[]toArray(Objectarray[]) Returnsanarraycontainingonlythose
collectionelementswhosetypematchesthat
ofarray.
402

Collection framework
403

Collection framework
404

Collection framework
405

Collection framework
406

Collection framework
407

Collection framework
408

Collection framework
409

Collection framework
410

Collection framework
411

Collection framework
412

Collection framework
413

Collection framework
414

Collection framework
415

Collection framework
416

Collection framework
417

Collection framework
418

Collection framework
419

Collection framework
420

Collection framework
421

Collection framework
422

Collection framework
423

Collection framework
424

Collection framework
425

426

427

428

JVM Architecture
•Firstofall,the.javaprogramisconvertedintoa.class
fileconsistingofbytecodeinstructionsbytheJava
compiler
•JVM(JavaVirtualMachine)isresponsiblefortaking
the.classfileandconvertingeachbytecodeinstruction
intothemachinelanguageinstructionthatcanbe
executedbytheprocessor
429

JVM Architecture
430

JVM Architecture
•InJVM,thereisaprogramcalledclassloadersub
system,whichperformsthefollowingfunctions
1)Firstofall,itloadsthe.classfileintomemory
2)Thenitverifieswhetherallbytecodeinstructionsare
properornot.Ifitfindsanyinstructionsuspicious,the
executionisrejectedimmediately
3)Ifthebytecodeinstructionsareproper,thenitallocates
necessarymemorytoexecutetheprogram
•Thismemorydividedinto5parts,calledruntimedata
areas
431

JVM Architecture
Methodarea
•Itisthememoryblock,whichstorestheclasscode,
codeofthevariables,andcodeofthemethodsinthe
Javaprogram
Heap
•Thisistheareawhereobjectsarecreated.Whenever
JVMloadsaclass,amethodandaheapareaare
immediatelycreatedinit.
432

JVM Architecture
JavaStacks
•MethodcodestoredonMethodarea.Butwhilerunning
amethod,itneedssomemorememorytostorethedata
andresults.ThismemoryisallocatedonJavastacks.
So,JavaStacksarememoryareaswhereJavamethods
areexecuted.
433

JVM Architecture
PC(ProgramCounter)registers
•Thesearetheregisterswhichcontainmemoryaddress
oftheinstructionsofthemethods.Ifthereare
3methods,3PCregisterswillbeusedtotrackthe
instructionsofthemethods
Nativemethodstacks
•JavamethodareexecutedonJavastacks.Similarly,
nativemethods(C/C++functions)areexecutedon
Nativemethodstacks.Toexecutenativemethods,
nativemethodlibrariesarerequired.Theseheaderfiles
arelocatedandconnectedtoJVMbyaprogram,called
Nativemethodinterface
434

Factory Methods

Factory Methods
•Factorymethodsarestaticmethodsonly
•Afactorymethodisamethodthatcreatesandreturnsan
objecttotheclasstowhichitbelongs.
•Theaimoffactorymethodistocreateanobject
dependingontheuseroption.
Example:publicstaticFeesgetFees(Stringcourse)
{}
Abovemethodtakesthecoursefromtheuserandcreatesan
objecteithertoCSEclassorECEclassdependingonthe
useroption
436

Different Ways Object
Creation In Java

Different Ways Object Creation In Java
1)Using new operator
Employee obj=new Employee();
2)Using factory methods
NumberFormat obj=NumberFormat.getNumberInstance();
3)Using newInstance() method
Class c=Class.forName(“Employee”);
Empoyee obj=(Employee)c.newInstance();
4)By cloning an already available object
Employee obj1=new Employee();
Employee obj2=(Employee)obj1.clone();
438

Object Class In Java

Object Class
1)Thereisaclasswiththename‘Object’Ijava.lang
packagewhichisthesuperclassofallclassesinJava
2)EveryclassinJavaisadirectorindirectsubclassof
theObjectclass
3)TheObjectclassdefinesthemethodstocompare
objects,toconvertanobjectintoString,etc.
440

Object Class
Methods of Object class
441
Method Description
equals()Compares the references of two objects return true when they are
equal otherwise return false
toString()Returns a string representation of an object
getClass()It gives an object that contains the name of a class to which an
object belongs
hashCode()Returns hashcodenumber of an object
notify()Sends a notification to a thread which is waiting for an object
notifyAll()Sends a notification forall waiting threads for the object
wait() Causes a thread to wait till a notification is received from a notify()
or notifyAll() methods

Object Class
equals() method
1)Thismethodnormallycomparesthereferencesoftwo
objects
2)Ifboththereferencesrefertosameobject,thenitgives
true,otherwiseitgivesfalse
3)ButincaseofStringobjectsandwrapperclassobjects
itcomparesthecontentsoftheobjects
4)Ifthecontentaresamethenitreturnstrue,otherwise
false
442

Object Class
hashCode() method
1)Wheneveritisinvokedonthesameobjectmorethan
onceduringanexecutionofaJavaapplication,the
hashCode()methodmustconsistentlyreturnthesame
integer
2)Iftwoobjectsareequalaccordingtotheequals()method,
thencallingthehashCode()methodoneachofthetwo
objectsmustproducethesameintegerresult
3)Iftwoobjectsareunequalaccordingtotheequals()
method,thencallingthehashCode()methodoneachofthe
twoobjectsmustproducedistinctintegerresults
443

Exception Propagation

Exception Propagation
•Consideringascenario,inwhichyourprogramstartsits
executionatthemain()method,main()callsmethod1(),
method1()callsmethod2(),method2()callsmethod3(),
nowthecallstackshouldlooklike
445

Exception Propagation
•The currently executing method is at the top of the call
stack, which in this example is method3(). Let's say
while executing method3(), an exception is
raised/thrown. Now this exception is thrown down to
the next method in the call stack, i.e. method2(), which
in turn throws the exception down to next method in the
call stack, i.e. method1(). The process continues until
the exception is thrown to the method at the bottom of
the call stack, i.e. main() method.
446

Exception Propagation
•Thecurrentlyexecutingmethodisatthetopofthecallstack,
whichinthisexampleismethod3().Let'ssaywhileexecuting
method3(),anexceptionisraised/thrown.
•Nowthisexceptionisthrowndowntothenextmethodinthecall
stack,i.e.method2(),whichinturnthrowstheexceptiondownto
nextmethodinthecallstack,i.e.method1().
•Theprocesscontinuesuntiltheexceptionisthrowntothe
methodatthebottomofthecallstack,i.e.main()method.Thisis
calledasexceptionpropagation
Note:
•Onlyuncheckedexceptionsarepropagated.Checkedexceptions
throwcompilationerror.
447

Try-With-Resource

Try-With-Resource
Syntax
try(resource-specification(there can be more than one
resource))
{
//use the resource
}
catch()
{
...
}
449

Try-With-Resource
•Thistrystatementcontainsaparenthesisinwhichone
ormoreresourcesisdeclared.
•Aresourceisanobjectthatisusedinprogramandmust
beclosedaftertheprogramisfinished.
•Thetry-with-resourcesstatementensuresthateach
resourceisclosedattheendofthestatementofthetry
block.Youdonothavetoexplicitlyclosetheresources.
450

Catch multiple
exceptions in Java1.7

Catch multiple exceptions
•In Java 7 it was made possible to catch multiple
different exceptions in the same catch block.
try {
// execute code that may throw 1 of the 3 exceptions
below.
} catch(SQLExceptione) {
e.printStackTrace();
} catch(IOExceptione) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
452

Catch multiple exceptions
try {
// execute code that may throw 1 of the 3 exceptions
below.
} catch(SQLException | IOException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
453

Rethrowing the
exception

Rethrowing The Exeption
•Theremightbesituationsinyourprogramwhereyou
wanttobothcatchanexceptioninyourcodeandalso
wantitscallerbenotifiedabouttheexception.
•Thisispossiblebyrethrowingtheexceptionusing
throwstatement.
455

Thread Deadlock

Thread Deadlock
•DeadlockisasituationofcompleteLock,whenno
threadcancompleteitsexecutionbecauselackof
resources.Intheabovepicture,Thread1isholdinga
resourceR1,andneedanotherresourceR2tofinish
execution,butR2islockedbyThread2,whichneeds
R3,whichinturnislockedbyThread3.Hencenoneof
themcanfinishandarestuckinadeadlock.
457

Thread Deadlock
458

Interthread
Communication

Interthread Communication
Polling Problem
Theprocessoftestingaconditionrepeatedlytillitbecomestrueis
knownaspolling.
Example
Supposethattheproducerhastowaituntiltheconsumerisfinished
beforeitgeneratesmoredata.Inapollingsystem,theconsumer
wouldwastemanyCPUcycleswhileitwaitsfortheproducerto
produce.Oncetheproducerhasfinished,itwouldstartpolling,
wastingmoreCPUcycleswaitingfortheconsumertofinish,and
soon.
460

Inter-thread communication
Thesolutionforpollingproblemisinter-threadcommunication
Inter-threadcommunication
Inter-threadcommunicationisaprocessinwhichathreadis
pausedrunninginitscriticalregionandanotherthreadisallowed
toenter(orlock)inthesamecriticalregiontobeexecuted.i.e.
synchronizedthreadscommunicatewitheachother.
Forinter-threadcommunicationjavaprovidesthreemethodsthey
arewait(), notify() and notifyAll().
Allthesemethodsbelongtoobjectclassasfinalsothatallclasses
havethem.Theymustbeusedwithinasynchronizedblockonly.
461

Interthread Communication
•wait()-Ittellsthecallingthreadtogiveupthelockandgoto
sleepuntilsomeotherthreadentersthesamemonitorandcalls
notify().
•notify()-Itwakesuponesinglethreadthatcalledwait()onthe
sameobject.Itshouldbenotedthatcallingnotify()doesnot
actuallygiveupalockonaresource.
•notifyAll()-Itwakesupallthethreadsthatcalledwait()onthe
sameobject.
462

Daemon thread

Daemon Thread
•Daemonthreadsarelowprioritythreadswhichareact
asaserviceproviderforuserthreads.Lifeofadaemon
threadisdependsupontheuserthreads.JVM
automaticallyterminatesdaemonthreadwhenalluser
threadsaredied.Daemonthreadsareusedfor
backgroundsupportingtasks.
Methodsusedfordaemonthreads:
1.publicfinalvoidsetDaemon(booleanon)
Marksthisthreadasdaemonthreadifonistrue.
2.publicfinalbooleanisDaemon()
Returnstrueifthreadisdaemon.
464

Java Annotations

Java Annotations
•JavaannotationswereaddedtoJavafromJava5.
•Javaannotationsareusedtoprovidethemetadatato
ourJavacode.
•Metadataistheadditionalinformationwhichcanbe
usedforanyclass,interface,methodorfield.
•Javaannotationscanbeusedasanalternativeoptionfor
XMLandjavamarkerinterfaces.
466

Java Annotations
Javaannotationsaremainlyusedforthefollowing:
Compilerinstructions
usedtogivecertaininstructionstothecompiler
Build-timeinstructions
canbeusedbythebuildtoolsforgeneratingsource
code,generatingXMLfiles,packagingthecompiledcode
andfilesintoaJARfileetc.
Runtimeinstructions
TheseannotationscanbeaccessedusingJava
Reflection.
467

Java Annotations
•Ajavaannotationalwaysstartswiththesymbol@and
followedbytheannotationname
Syntax: Example:
@AnnotationName @Entity
•Anannotationcancontainzero,oneormultiple
elements.Wehavetosetvaluesfortheseelements.
Example:
@Entity(tableName="USERS")
Wecanusejavaannotationsaboveclasses,interfaces,
methods,fieldsandlocalvariables.Hereisanexample
annotationaddedaboveaclassdefinition:
468

Java Annotations
Java Annotations List:
•@Deprecated
•@Override
•@SuppressWarnings
•@Target
•@Retention
•@Inherited
•@Documented
469

Java Annotations
@Deprecated java annotation
•Thedeprecatedtermsinsoftwaredevelopmentisrefers
toclasses,interfaces,functionsorelementsthatarein
theprocessofbeingreplacedbynewerones.
•The@Deprecatedjavaannotationsignalsthatthe
markedelementisdeprecatedandshouldnolongerbe
used.
470

Java Annotations
@Override java annotation
•The@Overridejavaannotationindicatesthatthe
subclassmethodisoverridingtheparentclassmethod.
•Ifwearenotusingoverrideannotationitmaybethe
casesomeonechangedthenameoftheoverridden
methodinthesuperclass,inthatcasesubclassmethod
wouldnolongeroverrideit.
471

Java Annotations
@SuppressWarningsjavaannotation
•The@SuppressWarningsannotationtypeallowsJava
programmerstodisablecompilationwarningsfora
certainpartofaprogram(type,field,method,
parameter,constructor,andlocalvariable).
472

473

Object Oriented Programming

Object Oriented Programming
What is object oriented programming?
•Object-OrientedProgrammingisaprogramming
patternthatmakesuseofobjectsandtheirinteractions
todesignandimplementapplications
•Objectsareentitiesthatserveasthebasicbuilding
blocksofanobject-orientedapplication
•Anobjectisaself-containedentitywithattributesand
behaviors
475

Object Oriented Programming
476

Object Oriented Programming
What is an Object?
Anentitywhichdoesexist,hasstateandbehaviorisknownasan
objecte.g.chair,bike,marker,pen,table,caretc.
Ifsomethingdoesnotreallyexist,thenitisnotanobjecte.g.our
thoughts,imagination,plans,ideasetc.,
AccordingtoSystemexistencemeanscontainsmemory.Soa
softwareobjectrepresentamemory.
Softwareobjectsalsohaveastateandabehavior.Asoftware
object'sstateisstoredinvariablesandbehaviorisshownvia
methods.Soanobjectcontainsvariablesandmethods
477

Object Oriented Programming
WhatisaClass?
Itispossiblethatsomeobjectsmayhavesimilarpropertiesand
actions.Suchobjectsbelongstosamecategorycalleda‘class’
Itisonlyanlogicalcomponentandnotthephysicalentitye.g.if
youhadaclasscalled“ExpensiveCars”itcouldhaveobjects
likeMercedes,BMW,Toyota,etc.
Itsproperties(data)canbepriceorspeedofthesecars.
Whilethemethodsmaybeperformedwiththesecarsaredriving,
reverse,brakingetc.
478

Object Oriented Programming
479

Object Oriented Programming
WhatisanabstractioninJava?
Inobjectorientedprogrammingabstractionisaprocessof
providingfunctionalitytotheusersbyhidingitsimplementation
detailsfromthem
Inotherwords,theuserwillhavejusttheknowledgeof
whatanentityisdoinginsteadofitsimplementation
480

Object Oriented Programming
ReallifeexampleofAbstractionisATMMachine;Allare
performingoperationsontheATMmachinelikecash
withdrawal,moneytransfer,retrievemini-statement…etc.
butwecan'tknowinternaldetailsaboutATM.
481

Object Oriented Programming
Advantages of Abstraction
482

Object Oriented Programming
How to Achieve Abstraction in Java?
InJava,wecanachieveDataAbstractionusingAbstract
classandInterface
Interfaceallow100%abstraction(completeabstraction).
Interfaceallowyoutoabstracttheimplementation
completely
Abstractclassallow0to100%abstraction(partialto
completeabstraction)becauseabstractclasscancontain
concretemethodsthathavetheimplementationwhich
resultsinapartialabstraction
483

Object Oriented Programming
What is an Encapsulation?
1)WecandefineitasEncapsulationisthewrappingupofdataand
functions(methodsthatoperateonthedata)intoasingleunit
(calledclass).
2)Thereisaprohibitionfordirectaccesstothedata.Functions
(thatcombinewiththedata)aretheonlywaytoaccessdata.
ThesefunctionsarethememberfunctionsormethodsinJava.It
basicallycreatesashieldduetowhichthecodeordatacannotbe
accessedoutsidetheshield.
3)InJavaclassbindthedatawithitsassociatedmethodsoclassis
anexampleofencapsulation
484

Object Oriented Programming
485

Object Oriented Programming
Achieving Encapsulation in Java
In order to achieve encapsulation in Java, we have to
1)declare the variables of a class as private, so that they cannot be
accessed directly from outside the class.
2)provide setter and getter methods that are declared as public, to
view and change the values of the variables.
486

Object Oriented Programming
Inheritance in Java
1)Theprocessbywhichoneclassacquirestheproperties(data
members)andfunctionalities(methods)ofanotherclassis
calledinheritance.
2)Intheinheritancetheclasswhichisgivedatamembersand
methodsisknownasbaseorsuperorparentclass.
3)Theclasswhichistakingthedatamembersandmethodsis
knownassuborderivedorchildclass
487

Object Oriented Programming
488

Object Oriented Programming
PolymorphisminJava
Polymorphismistheabilityforadataormessagetobeprocessed
inmorethanoneform.Itisaconceptbywhichasingle
operationcanbeperformedinmultipledifferentways.
Forexample,asecurityguardoutsideanorganizationbehaves
differentlywithdifferentpeopleenteringtheorganization.He
actsinadifferentwaywhentheBosscomesand,inanotherway
whentheemployeescome.Whenthecustomersenter,theguard
willresponddifferently.Sohere,thebehavioroftheguardisin
variousforms,whichdependsonthememberwhoiscoming.
489

Object Oriented Programming
490

Object Oriented Programming
WecandefinepolymorphisminthecontextofObject-Oriented
Programmingasfollows:
“Thevirtue(goodfuture)bywhichthesameactioncanbe
performedbyobjectsofdifferentclassesandeachobject
respondsinadifferentwaydependingonitsclassiscalled
Polymorphism”.
491

Object Oriented Programming
492

Object Oriented Programming
493

Object Oriented Programming
494

Object Oriented Programming
495

Object Oriented Programming
496

Wrapper Classes

Wrapper Classes
1)Awrapperclassisaclasswhoseobjectcontainsorwrapsa
primitivedatatype
2)Whenwecreateanobjecttoawrapperclass,itcontainsafield
andinthisfield,wecanstoreaprimitivedatatype
3)Forexample,ifwecreateanobjecttoCharacterwrapperclass,
itcontainsasinglefieldcharanditispossibletostorea
characterlike‘a’
NeedofWrapperclasses
1)Wrapperclassesconvertprimitivedatatypeintoobjectandthis
isneededoninternettocommunicatebetweentwoapplications
2)Theclassesinjava.utilpackagehandleonlyobjectshence
wrapperclasseshelpinthiscasealso
498

Wrapper Classes
499

Wrapper Classes
500

Wrapper Classes
Number class
Number is an abstract class whose sub classes are Byte,
Short,Integer,Long,Float and Double
So the methods of Number class are commonly available in all
these classes
Methods of Number class
byte byteValue()
Converts the calling object into byte value
short shortValue()
Converts the calling object into short value
int intValue()
Converts the calling object into int value
501

Wrapper Classes
longlongValue()
Convertsthecallingobjectintolongvalue
floatfloatValue()
Convertsthecallingobjectintofloatvalue
doubledoubleValue()
Convertsthecallingobjectintodoublevalue
Note
ThecallingobjectcanbeanobjectofByte,Short,Integer,Long,
FloatorDoubleclass
502

Wrapper Classes
Character Class
The character class wraps a value of the primitive type char in an object.
Character class has only one constructer which accepts primitive data type
Character obj=new Character('A');
Important methods of Character class
char charvalue( ):used to convert character object into character primitive
character obj=new character ('A');
char ch=objcharValue();
intcompare To (character obj):useful to compare two character objects
intx =obj1.compare (obj2);
if obj1==obj2,returns 0
if obj1<obj2,returns negative value
if obj1>obj2,returns positive value
String toString( ):converts character object into string object
503

Wrapper Classes
staticCharactervalueOf(charch)
convertasinglecharacterchintocharacterchintocharacter
object
staticbooleanisDigit(charch)
returnstrueifchisadigitotherwisereturnfalse
staticbooleanisLetter(charch)
returnstrueifchisaletter
staticbooleanisUpperCase(charch)
returnstrueifchisauppercaseletter
staticbooleanisLowerCase(charch)
returnstrueifchislowercaseletter
504

Wrapper Classes
static booleanisSpaceChar(char ch)
returns true if chis represents a white space
static booleanisLetterorDigit(char ch)
returns true if cheither a letter or digit
static char toUpperCase(char ch)
converts chinto uppercase
static char toLowerCase(char ch)
converts chinto lowercase
505

Wrapper Classes
Byte Class
The byte class wraps a value of primitive type 'byte‘ in an object.
Constructors
1)Byte(byte num):
create byte object as
Byte obj=new Byte(120);
2)Byte(String str):
create Byte object by converting a string that contains a byte
number
Byte obj=new Byte("120");
506

Wrapper Classes
Important methods of Byte class
int compareTo(Byte b)
useful to compare the contents of Byte class objects.
int x=obj1.comareTo(obj2);
obj1==obj2 returns 0
obj1<obj2 returns negative value
obj1>obj2 returns positive value
boolean equals(object obj)
compares the Byte object with any other object obj.If both have
same content then it returns true otherwise false.
static byte parseByte(String str)
returns the primitive byte number contained in the string str.
507

Wrapper Classes
String toString()
converts Byte object into string object and returns that string object
static Byte valueOf(String str)
converts string str that contains some byte number into Byte class
object
static Byte valueOf(byte b)
converts the primitive byte b into Byte object.
508

Wrapper Classes
Short Class
Short class wraps a value of primitive data type 'short' in its object.
Constructors
Short(short num)
Takes short number as its parameter and convert it into Short class
object.
short s=14007;
Short obj=new Short(s);
Short(String str)
Useful to construct the short class object by passing string str to it
as
String str="2756";
Short obj=new Short(str);
509

Wrapper Classes
Important methods of Short class
int compareTo(Short obj)
Compare the numeric value of two short class objects and return 0,-ve
value or +ve value.
boolean equals(Object o)
Compares the Short object with any other object o.if both have the same
content then it returns true otherwise false.
static short parseShort(String str)
returns short equivalent of the string str.
String toString()
returns a string form of the Short object.
static Short valueof(String str)
Converts a string str that contains some short number into Short class
object and returns that object.
510

Wrapper Classes
Integer Class
The integer class wraps a value of the primitive int number as its
parameter and converts it into integer class object
Constructors
Integer(int num): creates integer object
Integer obj= new Integer(123000);
here, we are converting a primitive int value into integer object.
This is called 'boxing’
Integer(String str):create an Integer object by converting a string
that contains as int number
Integer obj = new Integer("198663");
511

Wrapper Classes
Important methods of Integer class
int compareTo(Integer obj)
compares the numerical value of two integer class objects and returns
0,+ve value ,or -ve value
boolean equals(object obj)
compare the inter object with any other object if both have the same
content,then it returns true otherwise false.
static int parseInt(String str)
returns int equivalent of the string str.
String toString()
returns a string form of the integer object.
static Integer valueOf(String str)
convert a string str that contains some int number into integer class object
and returns that object.
512

Wrapper Classes
static String toBinaryString(int i)
converts decimal integer number i into binary umber system and returns
that binary number as a string
static String toHexString(int i)
converts decimal integer number i into hexadecimal number system and
returns that hexdecimal number as a string
static String toOctalString(int i)
converts decimal integer number i into octal number system and returns
that octal number as a string
int intValue()
converts integer object into primitive int type value. This is called
'unboxing'.
513

Wrapper Classes
Long Class
The Long contains a primitive long type data
Constructors
Long(long num)
Long object can be created
Long obj=new Long(1230044);
Long(String str)
Create Long object by converting a string that contains a long number
Strung str=“1230044”;
Long obj=new Long(str);
514

Wrapper Classes
Important methods of Long class
int compareTo(Long obj)
Compares the numeric value of two Long class objects and return 0, -ve
value, or +ve value
boolean equals(Object obj)
Compares the Long object with any other object obj. If both have same
content, then it returns true otherwise false
static long parseLong(String str)
Return long equivalent of the string str
String toString()
Converts Long object into String Object
static Long valueOf(String str)
Converts a string str that contains some long number into Long object
515

Wrapper Classes
Math Class
TheclassMathcontainsmethodsforperformingbasicnumeric
operations,suchastheelementaryexponential,squarerootetc..
AllthemethodsofMathclassarestatic
ImportantmethodsofMathclass
staticdoublesin(doublearg)
returnthesinevalueofthearg
Math.sin(0.5);//0.4794255
staticdoublecos(doublearg)
returnthecosinevalueofthearg
Math.cos(0.5);//0.87758256189
staticdoubletan(doublearg)
returnthetangetvalueofthearg
Math.tan(0.5);//0.54630248
516

Wrapper Classes
static double log(double arg)
return the natural logarithm value of the arg
Math.log(0.5);//-0.69314718055
static double log10(double arg)
return the base10 algorithm value of the arg
Math.log10(0.5);//-0.30102999566
static double pow(double x, double n)
return the x to the power of the n value
Math.pow(5,3);//125.0
static double sqrt(double arg)
return the square root of the arg
Math.sqrt(25);//5.0
517

Wrapper Classes
staticdoubleabs(doublearg)
returntheabsolutevalueofthearg.Absolutevaluepresentthepositive
quantity
Math.abs(-4.55);//4.55
staticdoubleceil(doublearg)
raisesthegivenargvaluetothenextintegervalue.Ifintegerisgivento
thismethod,itgivessamevalue
Math.ceil(4.5);//5.0
staticdoublefloor(doublearg)
decreasesthegivenargvaluetothepreviousintegervalue.Ifintegeris
giventothismethod,thenitgivesthesamevalue,
Math.floor(4.5);//4.0
staticdoublemin(arg1,arg2)
returnstheminimumofarg1andarg2
Math.min(5,10);//5.0
518

Wrapper Classes
staticdoublemax(arg1,arg2)
returnsthemaximumofarg1andarg2
Math.max(5,10);//10.0
staticlonground(arg)
returnstheroundedvalueofarg.Ifthefractionpartofthenumberis
moreorequalto0.5,then1isaddedtotheintegerpart;otherwisethe
sameintegerpartisreturned.
Math.round(4.6);//5
Math.round(4.4);//4
staticdoublerandom()
returnsarandomnumberbetween0and1.Arandomnumberisanumber
thatcannotbeguessedbyanyone.
Math.random();//0.2230762209
519

Wrapper Classes
static double toRadians(double angle)
converts the given value in degree into radians.
Math.toRadians(180);//3.141592653
static double to Degree(double angle)
converts angle in radians into degree.
Math.toDegree(3.14159);//179.9998479
520

Wrapper Classes
Double class
The Double class wraps a value of the primitive type double in an object.
The double class object contains a double type field that stores a
primitive double number
Constructors
Double (double num)
Double object can be created
double d=12.1223;
Double obj=new Double(d);
Double (String str)
This constructor is useful to create a Double object by converting a string
that contains a double number
String str=“12.1223”;
Double obj=new Double(str);
521

Wrapper Classes
Important methods of Double class
int compareTo(Double obj)
Compares the numeric value of two Double class objects and return 0, -
ve value, or +ve value
boolean equals(Object obj)
Compares the Double object with any other object obj. If both have same
content, then it returns true otherwise false
static double parseDouble(String str)
Return double equivalent of the string str
String toString()
Converts Double object into String Object
static Double valueOf(String str)
Converts a string str that contains some double number into Double
object
522

Wrapper Classes
Float class
The Float class wraps a value of the primitive type float in an object. The
Float class object contains a float type field that stores a primitive float
number
Constructors
Float (float num)
Float object can be created
float f=12.122f;
Float obj=new Float(f);
Float (String str)
This constructor is useful to create a Float object by converting a string
that contains a float number
String str=“12.122f”;
Float obj=new Float(str);
523

Wrapper Classes
Important methods of Float class
int compareTo(Float obj)
Compares the numeric value of two Float class objects and return 0, -ve
value, or +ve value
boolean equals(Object obj)
Compares the Float object with any other object obj. If both have same
content, then it returns true otherwise false
static float parseFloat(String str)
Return float equivalent of the string str
String toString()
Converts Float object into String Object
static Float valueOf(String str)
Converts a string str that contains some float number into Float object
524

Wrapper Classes
Boolean class
The Boolean class wraps a value of the primitive type boolean in an
object. The Boolean class object contains a boolean type field that
stores a primitive boolean
Constructors
Boolean (boolean value)
Boolean object can be created
Boolean obj=new Boolean(true);
Boolean (String str)
This constructor is useful to create a Boolean object by converting a
string that contains a boolean value
String str=“false”;
Boolean obj=new Boolean(str);
525

Wrapper Classes
Important methods of Boolean class
int compareTo(Boolean obj)
Compares the value of two Boolean class objects and return 0, -ve value,
or +ve value
boolean equals(Object obj)
Compares the Boolean object with any other object obj. If both have
same content, then it returns true otherwise false
static boolean parseBoolean(String str)
Return boolean equivalent of the string str
String toString()
Converts Boolean object into String Object
static Boolean valueOf(String str)
Converts a string str that contains some boolean value into Boolean
object
526

Wrapper Classes
527
Tags