Author(s): Nick Samoylov
Publisher: Praful Palekar
Year: 2019
Language: English
Pages: 656
Table of Contents
Preface 1
Section 1: Overview of Java Programming
Chapter 1: Getting Started with Java 12 9
How to install and run Java 10
What is JDK and why do we need it? 10
Installing Java SE 12
Commands, tools, and utilities 13
How to install and run an IDE 14
Selecting an IDE 14
Installing and configuring IntelliJ IDEA 15
Creating a project 16
Importing a project 26
Executing examples from the command line 33
Java primitive types and operators 34
Boolean type 35
Numeric types 35
Integral types 35
Floating-point types 37
Default values of primitive types 38
Literals of primitive types 39
New compact number format 41
Operators 42
Arithmetic unary (+ and -) and binary operators (+, -, *, /, and %) 43
Increment and decrement unary operators (++ and --) 43
Equality operators (== and !=) 44
Relational operators (<, >, <=, and >=) 44
Logical operators (!, &, and |) 44
Conditional operators (&&, ||, and ? :) 45
Assignment operators (=, +=, -=, *=, /=, and %=) 46
String types and literals 47
String literals 47
String immutability 50
Identifiers and variables 50
Identifier 51
Variable declaration (definition) and initialization 51
Type holder var 52
Java statements 52
Expression statements 53
Control flow statements 54
Table of Contents
[ ii ]
Selection statements 55
Iteration statements 59
Exception-handling statements 62
Branching statements 63
Summary 66
Quiz 66
Chapter 2: Java Object-Oriented Programming (OOP) 72
OOP concepts 73
Object/class 73
Inheritance 74
Abstraction/interface 76
Encapsulation 76
Polymorphism 77
Class 77
Method 79
Varargs 80
Constructor 81
The new operator 84
Class java.lang.Object 85
Instance and static properties and methods 90
Interface 92
Default methods 93
Private methods 94
Static fields and methods 95
Interface versus abstract class 95
Overloading, overriding, and hiding 96
Overloading 96
Overriding 98
Hiding 100
Final variable, method, and classes 103
Final variable 103
Final method 105
Final class 105
Polymorphism in action 105
Object factory 106
Operator instanceof 108
Summary 110
Quiz 110
Chapter 3: Java Fundamentals 115
Packages, importing, and access 115
Packages 116
Importing 116
Access modifiers 118
Java reference types 121
Table of Contents
[ iii ]
Class and interface 121
Array 123
Enum 124
Default values and literals 127
Reference type as a method parameter 127
equals() method 129
Reserved and restricted keywords 132
Reserved keywords 132
Restricted keywords 133
Usage of the this and super keywords 134
Usage of the this keyword 134
Usage of the super keyword 136
Converting between primitive types 136
Widening conversion 137
Narrowing conversion 138
Methods of conversion 139
Converting between primitive and reference types 141
Boxing 141
Unboxing 142
Summary 143
Quiz 144
Section 2: Building Blocks of Java
Chapter 4: Exception Handling 149
Java exceptions framework 150
Checked and unchecked exceptions 151
The try, catch, and finally blocks 154
The throws statement 156
The throw statement 157
The assert statement 159
Best practices of exceptions handling 159
Summary 160
Quiz 160
Chapter 5: Strings, Input/Output, and Files 163
Strings processing 163
Methods of the String class 163
Strings analysis 164
Strings comparison 164
Strings transformation 166
Methods added with Java 11 168
String utilities 169
I/O streams 172
Stream data 173
Table of Contents
[ iv ]
Class InputStream and its subclasses 174
ByteArrayInputStream 175
FileInputStream 176
ObjectInputStream 178
PipedInputStream 179
SequenceInputStream 181
FilterInputStream 182
javax.sound.sampled.AudioInputStream 183
Class OutputStream and its subclasses 184
PrintStream 185
Reader and Writer classes and their subclasses 188
Reader and its subclasses 188
Writer and its subclasses 189
Other classes of java.io package 190
Console 190
StreamTokenizer 194
ObjectStreamClass and ObjectStreamField 197
Class java.util.Scanner 199
File management 201
Creating and deleting files and directories 202
Listing files and directories 204
Apache Commons utilities FileUtils and IOUtils 205
Class FileUtils 206
Class IOUtils 207
Summary 207
Quiz 208
Chapter 6: Data Structures, Generics, and Popular Utilities 211
List, Set, and Map interfaces 211
Generics 213
How to initialize List and Set 214
java.lang.Iterable interface 217
Collection interface 217
List interface 220
Set interface 223
Map interface 223
Unmodifiable collections 226
Collections utilities 227
java.util.Collections class 228
CollectionUtils class 230
Arrays utilities 231
java.util.Arrays class 231
ArrayUtils class 232
Object utilities 234
java.util.Objects class 234
ObjectUtils class 238
Table of Contents
[ v ]
java.time package 239
LocalDate class 239
LocalTime class 242
LocalDateTime class 244
Period and Duration classes 244
Summary 246
Quiz 246
Chapter 7: Java Standard and External Libraries 253
Java Class Library 254
java.lang 255
java.util 256
java.time 257
java.io and java.nio 257
java.sql and javax.sql 258
java.net 258
java.lang.math and java.math 259
java.awt, javax.swing, and javafx 259
External libraries 260
org.junit 260
org.mockito 261
org.apache.log4j and org.slf4j 263
org.apache.commons 265
lang and lang3 266
collections4 267
codec.binary 269
Summary 270
Quiz 270
Chapter 8: Multithreading and Concurrent Processing 274
Thread versus process 274
User thread versus daemon 275
Extending class thread 275
Implementing interface Runnable 277
Extending thread vs implementing Runnable 278
Using pool of threads 279
Getting results from thread 287
Parallel vs concurrent processing 293
Concurrent modification of the same resource 293
Atomic variable 296
Synchronized method 298
Synchronized block 299
Concurrent collections 301
Addressing memory consistency error 303
Summary 303
Table of Contents
[ vi ]
Quiz 304
Chapter 9: JVM Structure and Garbage Collection 307
Java application execution 308
Using an IDE 308
Using the command line with classes 312
Using the command line with JAR files 315
Using the command line with an executable JAR file 316
Java processes 317
Class loading 319
Class linking 320
Class initialization 321
Class instantiation 322
Method execution 322
Garbage collection 322
Application termination 323
JVM structure 325
Runtime data areas 325
Classloaders 326
Execution engine 326
Garbage collection 326
Responsiveness, throughput, and stop-the-world 327
Object age and generations 327
When stop-the-world is unavoidable 328
Summary 329
Quiz 329
Chapter 10: Managing Data in a Database 333
Creating a database 333
Creating a database structure 335
Connecting to a database 338
Releasing the connection 340
CRUD data 341
The INSERT statement 342
The SELECT statement 342
The UPDATE statement 344
The DELETE statement 344
Using statements 345
The execute(String sql) method 345
The executeQuery(String sql) method 347
The executeUpdate(String sql) method 349
Using PreparedStatement 351
Using CallableStatement 352
Summary 354
Quiz 354
Table of Contents
[ vii ]
Chapter 11: Network Programming 358
Network protocols 358
UDP-based communication 360
TCP-based communication 364
The java.net.ServerSocket class 365
The java.net.Socket class 368
Running the examples 370
UDP versus TCP protocols 371
URL-based communication 372
The URL syntax 372
The java.net.URL class 373
Using the HTTP 2 Client API 380
Blocking HTTP requests 381
Non-blocking (asynchronous) HTTP requests 383
Server push functionality 388
WebSocket support 389
Summary 392
Quiz 392
Chapter 12: Java GUI Programming 394
Java GUI technologies 395
JavaFX fundamentals 395
Hello with JavaFX 399
Control elements 402
Charts 405
Applying CSS 407
Using FXML 409
Embedding HTML 415
Playing media 423
Adding effects 428
Summary 452
Quiz 452
Section 3: Advanced Java
Chapter 13: Functional Programming 454
What is functional programming? 454
What is a functional interface? 457
What is a lambda expression? 459
Local-variable syntax for lambda parameters 460
Standard functional interfaces 462
Consumer 463
Predicate 464
Supplier 466
Function 466
Table of Contents
[ viii ]
Other standard functional interfaces 469
Lambda expression limitations 470
Method references 472
Summary 474
Quiz 474
Chapter 14: Java Standard Streams 476
Streams as a source of data and operations 476
Stream initialization 478
Stream interface 478
empty() 478
of(T... values) 479
ofNullable(T t) 480
iterate(Object, UnaryOperator) 481
concat (Stream a, Stream b) 482
generate (Supplier) 482
Stream.Builder interface 483
Other classes and interfaces 484
Operations (methods) 487
Intermediate operations 488
Filtering 488
Mapping 489
Sorting 491
Peeking 492
Terminal operations 492
Processing each element 493
Counting all elements 496
Match all, any, none 497
Find any or first 498
Optional class 499
Min and max 500
To array 501
Reduce 503
Collect 507
Collectors 510
Numeric stream interfaces 514
Creating a stream 515
range(), rangeClosed() 515
Intermediate operations 515
boxed(), mapToObj() 516
mapToInt(), mapToLong(), mapToDouble() 517
flatMapToInt(), flatMapToLong(), flatMapToDouble() 518
Terminal operations 518
sum(), average() 519
Parallel streams 520
Stateless and stateful operations 520
Sequential or parallel processing? 520
Table of Contents
[ ix ]
Summary 521
Quiz 521
Chapter 15: Reactive Programming 524
Asynchronous processing 524
Sequential and parallel streams 525
Using the CompletableFuture object 526
Non-blocking API 528
The java.io package versus the java.nio package 528
The event/run loop 529
Reactive 530
Responsive 531
Resilient 532
Elastic 532
Message-driven 533
Reactive streams 533
RxJava 535
Observable types 537
Blocking versus non-blocking 538
Cold versus hot 541
Disposable 544
Creating an observable 546
Operators 548
Transforming 549
Filtering 550
Combining 551
Converting from XXX 552
Exceptions handling 553
Life cycle events handling 553
Utilities 555
Conditional and Boolean 557
Backpressure 558
Connectable 558
Multithreading (scheduler) 559
Summary 565
Quiz 565
Chapter 16: Microservices 567
What is a microservice? 567
The size of a microservice 569
How microservices talk to each other 570
The reactive system of microservices 573
The HTTP server 573
The EventBus message receiver 577
The EventBus message senders 579
The reactive system demonstration 582
Table of Contents
[ x ]
Summary 584
Quiz 585
Chapter 17: Java Microbenchmark Harness 586
What is JMH? 586
Creating a JMH benchmark 589
Running the benchmark 590
Using an IDE plugin 591
JMH benchmark parameters 594
Mode 594
Output time unit 595
Iterations 595
Forking 596
JMH usage examples 596
Using the @State annotation 598
Using the Blackhole object 599
Using the @CompilerControl annotation 599
Using the @Param annotation 600
A word of caution 601
Summary 602
Quiz 602
Chapter 18: Best Practices for Writing High-Quality Code 604
Java idioms, their implementation, and their usage 605
The equals() and hashCode() methods 605
The compareTo() method 608
The clone() method 610
The StringBuffer and StringBuilder classes 614
Try, catch, and finally clauses 614
Best design practices 615
Identifying loosely coupled functional areas 615
Breaking the functional area into traditional tiers 615
Coding to an interface 616
Using factories 616
Preferring composition over inheritance 616
Using libraries 617
Code is written for people 617
Testing is the shortest path to quality code 619
Summary 619
Quiz 620
Chapter 19: Java - Getting New Features 621
Java continues to evolve 621
Panama project 622
Valhalla project 623
Table of Contents
[ xi ]
Amber project 624
Data class 624
Pattern match 625
Raw string literals 626
Concise method bodies 627
Lambda leftovers 628
Using an underscore instead of a parameter name 628
Shadowing a local variable 629
Better disambiguation of functional expressions 629
Loom project 630
Skara project 631
Summary 632
Appendix A: Assessments 633
Chapter 1 – Getting Started with Java 12 633
Chapter 2 – Java Object-Oriented Programming (OOP) 634
Chapter 3 – Java Fundamentals 634
Chapter 4 – Exception Handling 635
Chapter 5 – Strings, Input/Output, and Files 635
Chapter 6 – Data Structures, Generics, and Popular Utilities 636
Chapter 7 – Java Standard and External Libraries 636
Chapter 8 – Multithreading and Concurrent Processing 637
Chapter 9 – JVM Structure and Garbage Collection 637
Chapter 10 – Managing Data in a Database 638
Chapter 11 – Network Programming 639
Chapter 12 – Java GUI Programming 639
Chapter 13 – Functional Programming 640
Chapter 14 – Java Standard Streams 640
Chapter 15 – Reactive Programming 641
Chapter 16 – Microservices 642
Chapter 17 – Java Microbenchmark Harness 642
Chapter 18 – Best Practices for Writing High-Quality Code 643
Other Books You May Enjoy 644
Index 647