Learn Java 17 Programming, 2nd Edition / Изучите программирование на Java 17, 2-е издание
Год издания: 2022
Автор: Samoylov Nick / Самойлов Ник
Издательство: Packt Publishing
ISBN: 978-1-80324-143-2
Язык: Английский
Формат: PDF, EPUB
Качество: Издательский макет или текст (eBook)
Интерактивное оглавление: Да
Количество страниц: 748
Описание: Explore the essential concepts of programming such as object-oriented, functional, and reactive programming by writing code and building projects using the latest LTS version of Java
Key Features:
A step-by-step guide for beginners to get started with programming in Java 17
Explore core programming topics including GUI programming, concurrency, and error handling
Write efficient code and build projects while learning the fundamentals of programming
Book Description:
Java is one of the most preferred languages among developers. It is used in everything right from smartphones and game consoles to even supercomputers, and its new features simply add to the richness of the language.
This book on Java programming begins by helping you learn how to install the Java Development Kit. You'll then focus on understanding object-oriented programming (OOP), with exclusive insights into concepts such as abstraction, encapsulation, inheritance, and polymorphism, which will help you when programming for real-world apps. Next, you'll cover fundamental programming structures of Java such as data structures and algorithms that will serve as the building blocks for your apps with the help of sample programs and practice examples. You'll also delve into core programming topics that will assist you with error handling, debugging, and testing your apps. As you progress, you'll move on to advanced topics such as Java libraries, database management, and network programming and also build a sample project to help you understand the applications of these concepts.
By the end of this Java book, you'll not only have become well-versed with Java 17 but also gained a perspective into the future of this language and have the skills to code efficiently with best practices.
What You Will Learn:
Understand and apply object-oriented principles in Java
Explore Java design patterns and best practices to solve everyday problems
Build user-friendly and attractive GUIs with ease
Understand the usage of microservices with the help of practical examples
Discover techniques and idioms for writing high-quality Java code
Get to grips with the usage of data structures in Java
Who this book is for:
This book is for those who would like to start a new career in the modern Java programming profession, as well as those who do it professionally already and would like to refresh their knowledge of the latest Java and related technologies and ideas.
Изучите основные концепции программирования, такие как объектно-ориентированное, функциональное и реактивное программирование, путем написания кода и создания проектов с использованием последней версии Java LTS
Ключевые функции:
Пошаговое руководство для начинающих по началу работы с программированием на Java 17
Изучите основные темы программирования, включая графический интерфейс, параллелизм и обработку ошибок
Пишите эффективный код и создавайте проекты, изучая основы программирования
Описание книги:
Java - один из самых популярных языков среди разработчиков. Он используется буквально во всем, начиная от смартфонов и игровых консолей и заканчивая суперкомпьютерами, а его новые возможности только увеличивают богатство языка.
Эта книга по программированию на Java начинается с того, что поможет вам научиться устанавливать Java Development Kit. Затем вы сосредоточитесь на понимании объектно-ориентированного программирования (ООП), получив эксклюзивное представление о таких понятиях, как абстракция, инкапсуляция, наследование и полиморфизм, которые помогут вам при программировании для реальных приложений. Далее вы познакомитесь с фундаментальными структурами программирования на Java, такими как структуры данных и алгоритмы, которые будут служить строительными блоками для ваших приложений, с помощью примеров программ и практических примеров. Вы также познакомитесь с основными разделами программирования, которые помогут вам в обработке ошибок, отладке и тестировании ваших приложений. По мере продвижения вы будете переходить к более сложным темам, таким как библиотеки Java, управление базами данных и сетевое программирование, а также создадите примерный проект, который поможет вам понять применение этих концепций.
К концу прочтения этой книги по Java вы не только хорошо освоитесь с Java 17, но и получите представление о будущем этого языка и приобретете навыки эффективного программирования с использованием лучших практик.
Что вы узнаете:
Понимать и применять объектно-ориентированные принципы Java
Изучите шаблоны проектирования Java и лучшие практики для решения повседневных задач
С легкостью создавать удобные и привлекательные графические интерфейсы
Разберетесь с использовании микросервисов с помощью практических примеров
Изучите методы и идиомы для написания высококачественного Java-кода
Познакомьтесь с использованием структур данных в Java
Для кого предназначена эта книга:
Эта книга предназначена для тех, кто хотел бы начать новую карьеру в современной профессии программиста на Java, а также для тех, кто уже занимается этим профессионально и хотел бы освежить свои знания о новейших разработках Java и связанных с ними технологиях и идеях.
Примеры страниц (скриншоты)
Оглавление
Preface
Part 1: Overview of Java Programming
1
Getting Started with Java 17
Technical requirements 4
How to install and run Java 4
What is the JDK and why do we need it? 5
Installing Java SE 7
Commands, tools, and utilities 7
How to install and run an IDE 8
Selecting an IDE 9
Installing and configuring
IntelliJ IDEA 10
Creating a project 11
Importing a project 17
Executing examples from the command line 22
Java primitive types
and operators 23
Boolean types 23
Numeric types 24
Default values of primitive types 27
Literals of primitive types 28
New compact number format 31
Operators 32
String types and literals 37
String literals 38
String immutability 41
IDs and variables 41
ID 42
Variable declaration (definition)
and initialization 42
Java statements 43
Expression statements 45
Control flow statements 46
Summary 59
Quiz 59
2
Java Object-Oriented Programming (OOP)
Technical requirements 66
OOP concepts 67
Object/class 67
Inheritance 68
Abstraction/interface 69
Encapsulation 70
Polymorphism 71
Class 71
Method 73
Constructor 75
The new operator 78
Class java.lang.Object 80
Instance and static properties
and methods 85
Interface 87
Default methods 88
Private methods 90
Static fields and methods 91
Interface versus abstract class 91
Overloading, overriding,
and hiding 92
Overloading 92
Overriding 94
Hiding 96
The final variable, method,
and classes 100
The final variable 100
Final method 102
Final class 103
The record class 103
Sealed classes and interfaces 105
Polymorphism in action 109
The object factory 109
The instanceof operator 112
Summary 114
Quiz 114
3
Java Fundamentals
Technical requirements 120
Packages, importing,
and access 120
Packages 120
Importing 121
Access modifiers 123
Java reference types 127
Class and interface 127
Array 128
Enum 130
Default values and literals 133
A reference type
as a method parameter 133
equals() method 136
Reserved and
restricted keywords 139
Reserved keywords 139
Reserved identifiers 140
Reserved words for literal values 140
Restricted keywords 140
Usage of the this and
super keywords 141
Usage of the this keyword 141
Usage of the super keyword 143
Converting between
primitive types 144
Widening conversion 144
Narrowing conversion 145
Methods of conversion 146
Converting between
primitive and reference types 149
Boxing 149
Unboxing 150
Summary 151
Quiz 152
Part 2: Building Blocks of Java
4
Exception Handling
Technical requirements 158
The Java exceptions
framework 158
Checked and unchecked
exceptions 160
The try, catch, and
finally blocks 162
The throws statement 165
The throw statement 167
The assert statement 168
Best practices of
exception handling 168
Summary 169
Quiz 170
5
Strings, Input/Output,and Files
Technical requirements 174
String processing 174
Methods of the String class 174
String utilities 181
I/O streams 184
Stream data 185
The InputStream class
and its subclasses 186
The OutputStream class
and its subclasses 197
The Reader and Writer
classes and their subclasses 201
Other classes of the java.io package 203
The java.util.Scanner class 213
File management 216
Creating and deleting files
and directories 216
Listing files and directories 219
Apache Commons’
FileUtils and IOUtils utilities 220
The FileUtils class 221
The IOUtils class 222
Summary 222
Quiz 223
6
Data Structures, Generics, and Popular Utilities
Technical requirements 228
List, Set, and Map interfaces 228
Generics 229
How to initialize List and Set 230
java.lang.Iterable interface 234
Collection interface 235
List interface 238
Set interface 241
Map interface 242
Unmodifiable collections 245
Collections utilities 246
java.util.Collections class 247
CollectionUtils class 249
Arrays utilities 251
java.util.Arrays class 251
ArrayUtils class 253
Objects utilities 254
java.util.Objects class 254
ObjectUtils class 259
The java.time package 260
LocalDate class 260
LocalTime class 264
LocalDateTime class 266
Period and Duration classes 267
Period of day 269
Summary 270
Quiz 270
7
Java Standard and External Libraries
Technical requirements 278
Java Class Library (JCL) 278
java.lang 279
java.util 280
java.time 281
java.io and java.nio 282
java.sql and javax.sql 282
java.net 282
java.lang.math and java.math 283
java.awt, javax.swing, and javafx 283
External libraries 284
org.junit 284
org.mockito 286
org.apache.log4j and org.slf4j 287
org.apache.commons 290
Summary 295
Quiz 295
8
Multithreading and Concurrent Processing
Technical requirements 300
Thread versus process 300
User thread versus daemon 301
Extending the Thread class 301
Implementing the
Runnable interface 303
Extending Thread versus
implementing Runnable 305
Using a pool of threads 306
Getting results from a thread 314
Parallel versus
concurrent processing 321
Concurrent modification
of the same resource 321
Atomic variable 325
Synchronized method 328
Synchronized block 329
Concurrent collections 330
Addressing memory
consistency errors 333
Summary 333
Quiz 334
9
JVM Structure and Garbage Collection
Technical requirements 338
Java application execution 338
Using an IDE 338
Using the command line
with classes 344
Using the command line
with JAR files 345
Using the command line
with an executable JAR file 346
Java processes 347
Classloading 350
Class linking 351
Class initialization 352
Class instantiation 352
Method execution 353
Garbage collection 353
Application termination 353
JVM’s structure 355
Runtime data areas 355
Classloaders 356
Execution engine 356
Garbage collection 357
Responsiveness, throughput,
and stop-the-world 357
Object age and generation 358
When stop-the-world is unavoidable 358
Summary 359
Quiz 359
10
Managing Data in a Database
Technical requirements 364
Creating a database 364
Creating a database structure 366
Connecting to a database 369
Releasing the connection 372
CRUD data 373
The INSERT statement 373
The SELECT statement 374
The UPDATE statement 375
The DELETE statement 376
Using statements 376
Using PreparedStatement 383
Using CallableStatement 385
Using a shared library
JAR file to access a database 387
Summary 392
Quiz 392
11
Network Programming
Technical requirements 398
Network protocols 398
UDP-based communication 399
TCP-based communication 404
The java.net.ServerSocket class 405
The java.net.Socket class 408
Running the examples 410
UDP versus TCP protocols 412
URL-based communication 413
The URL syntax 413
The java.net.URL class 414
Using the HTTP 2 Client API 424
Blocking HTTP requests 426
Non-blocking (asynchronous)
HTTP requests 428
Server push functionality 434
WebSocket support 436
Summary 438
Quiz 439
12
Java GUI Programming
Technical requirements 442
Java GUI technologies 442
JavaFX fundamentals 443
HelloWorld with JavaFX 447
Control elements 450
Charts 454
Applying CSS 456
Using FXML 458
Embedding HTML 468
Playing media 478
Adding effects 484
Summary 510
Quiz 510
Part 3: Advanced Java
13
Functional Programming
Technical requirements 514
What is functional
programming? 514
What is a functional interface? 517
What is a Lambda expression? 519
Standard functional
interfaces 523
Consumer<T> 523
Predicate<T> 525
Supplier<T> 527
Function<T, R> 528
Other standard functional interfaces 531
Lambda expression
limitations 532
Method references 534
Summary 537
Quiz 538
14
Java Standard Streams
Technical requirements 540
Streams as a source
of data and operations 540
Stream initialization 542
Stream interface 542
The Stream.Builder interface 547
Other classes and interfaces 549
Operations (methods) 551
Intermediate operations 553
Terminal operations 557
Numeric stream interfaces 581
Creating a stream 582
Intermediate operations 582
Terminal operations 586
Parallel streams 587
Stateless and stateful operations 587
Sequential or parallel processing? 588
Summary 591
Quiz 592
15
Reactive Programming
Technical requirements 596
Asynchronous processing 596
Sequential and parallel streams 597
Using the CompletableFuture object 599
Non-blocking APIs 600
The java.io package versus
the java.nio package 600
The event/run loop 601
Reactive 602
Responsive 603
Resilient 603
Elastic 604
Message-driven 604
Reactive streams 605
RxJava 606
Observable types 609
Disposable 618
Creating an observable 620
Operators 622
Multithreading (scheduler) 634
Summary 641
Quiz 641
16
Java Microbenchmark Harness
Technical requirements 644
What is JMH? 644
Creating a JMH benchmark 647
Running the benchmark 649
Using an IDE plugin 649
JMH benchmark parameters 652
Mode 652
Output time unit 653
Iterations 653
Forking 653
JMH usage examples 654
Using the @State annotation 656
Using the Blackhole object 657
Using the @CompilerControl
annotation 658
Using the @Param annotation 658
A word of caution 659
Summary 660
Quiz 660
17
Best Practices for Writing High-Quality Code
Technical requirements 664
Java idioms, their
implementation,
and their usage 664
The equals() and hashCode() methods 665
The compareTo() method 668
The clone() method 670
The StringBuffer and
StringBuilder classes 676
The try, catch, and finally clauses 676
Best design practices 676
Identifying loosely coupled
functional areas 677
Breaking the functional
area into traditional tiers 677
Coding to an interface 677
Using factories 678
Preferring composition
over inheritance 678
Using libraries 678
Code is written for people 679
Use well-established
frameworks and libraries 680
Testing is the shortest
path to quality code 687
Summary 687
Quiz 688
Assessments
Chapter 1 – Getting Started
with Java 17 689
Chapter 2 – Java Object-
Oriented Programming (OOP) 690
Chapter 3 – Java Fundamentals 690
Chapter 4 – Exception Handling 691
Chapter 5 – Strings, Input/
Output, and Files 691
Chapter 6 – Data Structures,
Generics, and Popular Utilities 692
Chapter 7 – Java Standard
and External Libraries 692
Chapter 8 – Multithreading
and Concurrent Processing 693
Chapter 9 – JVM Structure
and Garbage Collection 694
Chapter 10 – Managing Data
in a Database 694
Chapter 11 – Network
Programming 695
Chapter 12 – Java GUI
Programming 696
Chapter 13 – Functional
Programming 696
Chapter 14 – Java Standard
Streams 697
Chapter 15 – Reactive
Programming 697
Chapter 16 – Java
Microbenchmark Harness 698
Chapter 17 – Best Practices
for Writing High-Quality Code 699
Index
Other Books You May Enjoy