Learn Java 17 Programming: Learn the fundamentals of Java Programming with this updated guide with the latest features
5/5
()
About this ebook
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.
Read more from Nick Samoylov
Introduction to Programming: Learn to program in Java with data structures, algorithms, and logic Rating: 0 out of 5 stars0 ratingsLearning RxJava: Build concurrent applications using reactive programming with the latest features of RxJava 3, 2nd Edition Rating: 0 out of 5 stars0 ratingsJava 11 Cookbook: A definitive guide to learning the key concepts of modern application development, 2nd Edition Rating: 0 out of 5 stars0 ratingsLearn Java 12 Programming: A step-by-step guide to learning essential concepts in Java SE 10, 11, and 12 Rating: 0 out of 5 stars0 ratingsJava: High-Performance Apps with Java 9: Boost your application's performance with the new features of Java 9 Rating: 0 out of 5 stars0 ratingsJava 9 Cookbook: Solutions for Modular, Functional, Reactive, and Multithreaded programming Rating: 0 out of 5 stars0 ratings
Related to Learn Java 17 Programming
Related ebooks
Java: High-Performance Apps with Java 9: Boost your application's performance with the new features of Java 9 Rating: 0 out of 5 stars0 ratingsMastering JavaScript Rating: 4 out of 5 stars4/5Learn Java 12 Programming: A step-by-step guide to learning essential concepts in Java SE 10, 11, and 12 Rating: 0 out of 5 stars0 ratingsCode with Java 21: A practical approach for building robust and efficient applications (English Edition) Rating: 0 out of 5 stars0 ratingsCloud-Native Development and Migration to Jakarta EE: Transform your legacy Java EE project into a cloud-native application Rating: 0 out of 5 stars0 ratingsJAVA 9.0 To 13.0 New Features: Learn, Implement and Migrate to New Version of Java. Rating: 0 out of 5 stars0 ratingsLearn LLVM 12: A beginner's guide to learning LLVM compiler tools and core libraries with C++ Rating: 0 out of 5 stars0 ratingsJava EE 8 and Angular: A practical guide to building modern single-page applications with Angular and Java EE Rating: 0 out of 5 stars0 ratingsIntroducing Play Framework: Java Web Application Development Rating: 0 out of 5 stars0 ratingsSwing Extreme Testing Rating: 4 out of 5 stars4/5Java 11 and 12 – New Features: Learn about Project Amber and the latest developments in the Java language and platform Rating: 0 out of 5 stars0 ratingsDjango 1.1 Testing and Debugging Rating: 4 out of 5 stars4/5Modular Programming in Java 9: Build large scale applications using Java modularity and Project Jigsaw Rating: 0 out of 5 stars0 ratingsBasic Java Programming for Kids and Beginners Rating: 0 out of 5 stars0 ratingsCore Java: Made Simple: A popular language for Android smart phone application, favoured for edge device and Rating: 0 out of 5 stars0 ratingsJava for Developers Pocket Primer: A Concise Guide to Mastering Java Programming Rating: 0 out of 5 stars0 ratingsHands-On Microservices with Django: Build cloud-native and reactive applications with Python using Django 5 Rating: 0 out of 5 stars0 ratingsEasy Web Development with WaveMaker Rating: 0 out of 5 stars0 ratingsModern Frontend Development with Node.js: A compendium for modern JavaScript web development within the Node.js ecosystem Rating: 0 out of 5 stars0 ratingsLearning Java Functional Programming Rating: 0 out of 5 stars0 ratingsLearning Underscore.js Rating: 0 out of 5 stars0 ratingsTest-Driven Development with Java: Create higher-quality software by writing tests first with SOLID and hexagonal architecture Rating: 0 out of 5 stars0 ratingsNode.js for Beginners: A comprehensive guide to building efficient, full-featured web applications with Node.js Rating: 0 out of 5 stars0 ratingsMastering the Java Virtual Machine: An in-depth guide to JVM internals and performance optimization Rating: 0 out of 5 stars0 ratingsJasmine JavaScript Testing - Second Edition Rating: 0 out of 5 stars0 ratingsJava Concurrency and Parallelism: Master advanced Java techniques for cloud-based applications through concurrency and parallelism Rating: 0 out of 5 stars0 ratings
Computers For You
Elon Musk Rating: 4 out of 5 stars4/5Mastering ChatGPT: 21 Prompts Templates for Effortless Writing Rating: 4 out of 5 stars4/5The ChatGPT Millionaire Handbook: Make Money Online With the Power of AI Technology Rating: 4 out of 5 stars4/5Alan Turing: The Enigma: The Book That Inspired the Film The Imitation Game - Updated Edition Rating: 4 out of 5 stars4/5The Invisible Rainbow: A History of Electricity and Life Rating: 5 out of 5 stars5/5CompTIA Security+ Get Certified Get Ahead: SY0-701 Study Guide Rating: 5 out of 5 stars5/5Standard Deviations: Flawed Assumptions, Tortured Data, and Other Ways to Lie with Statistics Rating: 4 out of 5 stars4/5The Innovators: How a Group of Hackers, Geniuses, and Geeks Created the Digital Revolution Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsUncanny Valley: A Memoir Rating: 4 out of 5 stars4/5Slenderman: Online Obsession, Mental Illness, and the Violent Crime of Two Midwestern Girls Rating: 4 out of 5 stars4/5ChatGPT 4 $10,000 per Month #1 Beginners Guide to Make Money Online Generated by Artificial Intelligence Rating: 0 out of 5 stars0 ratingsHow to Create Cpn Numbers the Right way: A Step by Step Guide to Creating cpn Numbers Legally Rating: 4 out of 5 stars4/5The Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5Procreate for Beginners: Introduction to Procreate for Drawing and Illustrating on the iPad Rating: 5 out of 5 stars5/5101 Awesome Builds: Minecraft® Secrets from the World's Greatest Crafters Rating: 4 out of 5 stars4/5Deep Search: How to Explore the Internet More Effectively Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5The Professional Voiceover Handbook: Voiceover training, #1 Rating: 5 out of 5 stars5/5Tor and the Dark Art of Anonymity Rating: 5 out of 5 stars5/5An Ultimate Guide to Kali Linux for Beginners Rating: 3 out of 5 stars3/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5CompTIA IT Fundamentals (ITF+) Study Guide: Exam FC0-U61 Rating: 0 out of 5 stars0 ratings
Reviews for Learn Java 17 Programming
1 rating0 reviews
Book preview
Learn Java 17 Programming - Nick Samoylov
BIRMINGHAM—MUMBAI
Learn Java 17 Programming
Second Edition
Copyright © 2022 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Publishing Product Manager: Gebin George
Senior Editor: Kinnari Chohan
Technical Editor: Pradeep Sahu
Copy Editor: Safis Editing
Project Coordinator: Manisha Singh
Proofreader: Safis Editing
Indexer: Manju Arasan
Production Designer: Vijay Kamble
Marketing Coordinator: Pooja Yadav
Business Development Executive: Kriti Sharma
First published: April 2019
Second edition: July 2022
Production reference: 1060722
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80324-143-2
www.packt.com
To my wife, Luda, a software developer too, who was the source of my inspiration and the sound technical advice for this book.
– Nick Samoylov
Contributors
About the author
Nick Samoylov graduated from Moscow Institute of Physics and Technology, working as a theoretical physicist and learning to program as a tool for testing his mathematical models. After the demise of the USSR, Nick created and successfully ran a software company, but was forced to close it under the pressure of governmental and criminal rackets. In 1999, with his wife Luda and two daughters, he emigrated to the USA and has been living in Colorado since then, working as a Java programmer. In his free time, Nick likes to write and hike in the Rocky Mountains.
About the reviewers
Alain Trottier loves to drive struggling people, processes, and products to their better versions. He finds immense joy in taking the efforts to help a person find their version 2.0. He believes that there’s a thrill in taking a jackhammer to an industrial process and building a more effective version in its place. He finds it invigorating to deconstruct a product or service to reveal key principles and then innovate something way better. He finds delight in smashing everything that makes a client feel awful and turning them into family. These all, he believes are ways to manhandle technology into doing what is right and best.
Fabrizio Marmitt has been a software development engineer for the past 15 years, building web applications as a full-stack software development engineer, from setting up servers to styling frontends. He currently works at Epic Games.
Table of Contents
Preface
Part 1: Overview of Java Programming
Chapter 1: Getting Started with Java 17
Technical requirements
How to install and run Java
What is the JDK and why do we need it?
Installing Java SE
Commands, tools, and utilities
How to install and run an IDE
Selecting an IDE
Installing and configuring IntelliJ IDEA
Creating a project
Importing a project
Executing examples from the command line
Java primitive types and operators
Boolean types
Numeric types
Default values of primitive types
Literals of primitive types
New compact number format
Operators
String types and literals
String literals
String immutability
IDs and variables
ID
Variable declaration (definition) and initialization
Java statements
Expression statements
Control flow statements
Summary
Quiz
Chapter 2: Java Object-Oriented Programming (OOP)
Technical requirements
OOP concepts
Object/class
Inheritance
Abstraction/interface
Encapsulation
Polymorphism
Class
Method
Constructor
The new operator
Class java.lang.Object
Instance and static properties and methods
Interface
Default methods
Private methods
Static fields and methods
Interface versus abstract class
Overloading, overriding, and hiding
Overloading
Overriding
Hiding
The final variable, method, and classes
The final variable
Final method
Final class
The record class
Sealed classes and interfaces
Polymorphism in action
The object factory
The instanceof operator
Summary
Quiz
Chapter 3: Java Fundamentals
Technical requirements
Packages, importing, and access
Packages
Importing
Access modifiers
Java reference types
Class and interface
Array
Enum
Default values and literals
A reference type as a method parameter
equals() method
Reserved and restricted keywords
Reserved keywords
Reserved identifiers
Reserved words for literal values
Restricted keywords
Usage of the this and super keywords
Usage of the this keyword
Usage of the super keyword
Converting between primitive types
Widening conversion
Narrowing conversion
Methods of conversion
Converting between primitive and reference types
Boxing
Unboxing
Summary
Quiz
Part 2: Building Blocks of Java
Chapter 4: Exception Handling
Technical requirements
The Java exceptions framework
Checked and unchecked exceptions
The try, catch, and finally blocks
The throws statement
The throw statement
The assert statement
Best practices of exception handling
Summary
Quiz
Chapter 5: Strings, Input/Output,and Files
Technical requirements
String processing
Methods of the String class
String utilities
I/O streams
Stream data
The InputStream class and its subclasses
The OutputStream class and its subclasses
The Reader and Writer classes and their subclasses
Other classes of the java.io package
The java.util.Scanner class
File management
Creating and deleting files and directories
Listing files and directories
Apache Commons’ FileUtils and IOUtils utilities
The FileUtils class
The IOUtils class
Summary
Quiz
Chapter 6: Data Structures, Generics, and Popular Utilities
Technical requirements
List, Set, and Map interfaces
Generics
How to initialize List and Set
java.lang.Iterable interface
Collection interface
List interface
Set interface
Map interface
Unmodifiable collections
Collections utilities
java.util.Collections class
CollectionUtils class
Arrays utilities
java.util.Arrays class
ArrayUtils class
Objects utilities
java.util.Objects class
ObjectUtils class
The java.time package
LocalDate class
LocalTime class
LocalDateTime class
Period and Duration classes
Period of day
Summary
Quiz
Chapter 7: Java Standard and External Libraries
Technical requirements
Java Class Library (JCL)
java.lang
java.util
java.time
java.io and java.nio
java.sql and javax.sql
java.net
java.lang.math and java.math
java.awt, javax.swing, and javafx
External libraries
org.junit
org.mockito
org.apache.log4j and org.slf4j
org.apache.commons
Summary
Quiz
Chapter 8: Multithreading and Concurrent Processing
Technical requirements
Thread versus process
User thread versus daemon
Extending the Thread class
Implementing the Runnable interface
Extending Thread versus implementing Runnable
Using a pool of threads
Getting results from a thread
Parallel versus concurrent processing
Concurrent modification of the same resource
Atomic variable
Synchronized method
Synchronized block
Concurrent collections
Addressing memory consistency errors
Summary
Quiz
Chapter 9: JVM Structure and Garbage Collection
Technical requirements
Java application execution
Using an IDE
Using the command line with classes
Using the command line with JAR files
Using the command line with an executable JAR file
Java processes
Classloading
Class linking
Class initialization
Class instantiation
Method execution
Garbage collection
Application termination
JVM’s structure
Runtime data areas
Classloaders
Execution engine
Garbage collection
Responsiveness, throughput, and stop-the-world
Object age and generation
When stop-the-world is unavoidable
Summary
Quiz
Chapter 10: Managing Data in a Database
Technical requirements
Creating a database
Creating a database structure
Connecting to a database
Releasing the connection
CRUD data
The INSERT statement
The SELECT statement
The UPDATE statement
The DELETE statement
Using statements
Using PreparedStatement
Using CallableStatement
Using a shared library JAR file to access a database
Summary
Quiz
Chapter 11: Network Programming
Technical requirements
Network protocols
UDP-based communication
TCP-based communication
The java.net.ServerSocket class
The java.net.Socket class
Running the examples
UDP versus TCP protocols
URL-based communication
The URL syntax
The java.net.URL class
Using the HTTP 2 Client API
Blocking HTTP requests
Non-blocking (asynchronous) HTTP requests
Server push functionality
WebSocket support
Summary
Quiz
Chapter 12: Java GUI Programming
Technical requirements
Java GUI technologies
JavaFX fundamentals
HelloWorld with JavaFX
Control elements
Charts
Applying CSS
Using FXML
Embedding HTML
Playing media
Adding effects
Summary
Quiz
Part 3: Advanced Java
Chapter 13: Functional Programming
Technical requirements
What is functional programming?
What is a functional interface?
What is a Lambda expression?
Standard functional interfaces
Consumer
Predicate
Supplier
Function
Other standard functional interfaces
Lambda expression limitations
Method references
Summary
Quiz
Chapter 14: Java Standard Streams
Technical requirements
Streams as a source of data and operations
Stream initialization
Stream interface
The Stream.Builder interface
Other classes and interfaces
Operations (methods)
Intermediate operations
Terminal operations
Numeric stream interfaces
Creating a stream
Intermediate operations
Terminal operations
Parallel streams
Stateless and stateful operations
Sequential or parallel processing?
Summary
Quiz
Chapter 15: Reactive Programming
Technical requirements
Asynchronous processing
Sequential and parallel streams
Using the CompletableFuture object
Non-blocking APIs
The java.io package versus the java.nio package
The event/run loop
Reactive
Responsive
Resilient
Elastic
Message-driven
Reactive streams
RxJava
Observable types
Disposable
Creating an observable
Operators
Multithreading (scheduler)
Summary
Quiz
Chapter 16: Java Microbenchmark Harness
Technical requirements
What is JMH?
Creating a JMH benchmark
Running the benchmark
Using an IDE plugin
JMH benchmark parameters
Mode
Output time unit
Iterations
Forking
JMH usage examples
Using the @State annotation
Using the Blackhole object
Using the @CompilerControl annotation
Using the @Param annotation
A word of caution
Summary
Quiz
Chapter 17: Best Practices for Writing High-Quality Code
Technical requirements
Java idioms, their implementation, and their usage
The equals() and hashCode() methods
The compareTo() method
The clone() method
The StringBuffer and StringBuilder classes
The try, catch, and finally clauses
Best design practices
Identifying loosely coupled functional areas
Breaking the functional area into traditional tiers
Coding to an interface
Using factories
Preferring composition over inheritance
Using libraries
Code is written for people
Use well-established frameworks and libraries
Testing is the shortest path to quality code
Summary
Quiz
Assessments
Chapter 1 – Getting Started with Java 17
Chapter 2 – Java Object-Oriented Programming (OOP)
Chapter 3 – Java Fundamentals
Chapter 4 – Exception Handling
Chapter 5 – Strings, Input/Output, and Files
Chapter 6 – Data Structures, Generics, and Popular Utilities
Chapter 7 – Java Standard and External Libraries
Chapter 8 – Multithreading and Concurrent Processing
Chapter 9 – JVM Structure and Garbage Collection
Chapter 10 – Managing Data in a Database
Chapter 11 – Network Programming
Chapter 12 – Java GUI Programming
Chapter 13 – Functional Programming
Chapter 14 – Java Standard Streams
Chapter 15 – Reactive Programming
Chapter 16 – Java Microbenchmark Harness
Chapter 17 – Best Practices for Writing High-Quality Code
Other Books You May Enjoy
Preface
The purpose of this book is to equip the readers with a solid understanding of Java fundamentals and to lead them through a series of practical steps from the basics to the actual real programming. The discussion and examples aim to stimulate the growth of the reader’s professional intuition by using proven programming principles and practices. The book starts with the basics and brings the readers up to the latest programming technologies, considered on a professional level.
After finishing this book, you will be able to do the following:
Install and configure your Java development environment.
Install and configure your Integrated Development Environment (IDE)–essentially, your editor.
Write, compile, and execute Java programs and tests.
Understand and use Java language fundamentals.
Understand and apply object-oriented design principles.
Master the most frequently used Java constructs.
Learn how to access and manage data in the database from Java application.
Enhance your understanding of network programming.
Learn how to add graphical user interface for better interaction with your application.
Become familiar with the functional programming.
Understand the most advanced data processing technologies—streams, including parallel and reactive streams.
Learn and practice creating microservices and building a reactive system.
Learn the best design and programming practices.
Envision Java’s future and learn how you can become part of it.
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.
What this book covers
Chapter 1, Getting Started with Java 17, begins with the basics, first explaining what Java
is and defining its main terms, then going on to how to install the necessary tools to write and run (execute) a program. This chapter also describes the basic Java language constructs, illustrating them with examples that can be executed immediately.
Chapter 2, Java Object-Oriented Programming (OOP), presents the concepts of object-oriented programming and how they are implemented in Java. Each concept is demonstrated with specific code examples. The Java language constructs of class and interface are discussed in detail, as well as overloading, overriding, hiding, and use of the final keyword. The last section of the chapter is dedicated to presenting the power of polymorphism.
Chapter 3, Java Fundamentals, presents to the reader a more detailed view of Java as a language. It starts with the code organization in packages and a description of the accessibility levels of classes (interfaces) and their methods and properties (fields). The reference types as the main types of Java’s object-oriented nature are presented in much detail, followed by a list of reserved and restricted keywords and a discussion of their usage. The chapter ends with the methods of conversion between primitive types, and from a primitive type to the corresponding reference type and back.
Chapter 4, Exception Handling, tells the reader about the syntax of the Java constructs related to exception handling and the best practices to address (handle) exceptions. The chapter ends with the related topic of the assertion statement that can be used to debug the application code in production.
Chapter 5, Strings, Input/Output, and Files, discusses the String class methods, as well as popular string utilities from standard libraries and the Apache Commons project. An overview of Java input/output streams and related classes of the java.io package follow along with some classes of the org.apache.commons.io package. The file-managing classes and their methods are described in a dedicated section.
Chapter 6, Data Structures, Generics, and Popular Utilities, presents the Java collections framework and its three main interfaces, List, Set, and Map, including discussion and demonstration of generics. The equals() and hashCode() methods are also discussed in the context of Java collections. Utility classes for managing arrays, objects, and time/date values have corresponding dedicated sections, too.
Chapter 7, Java Standard and External Libraries, provides an overview of the functionality of the most popular packages of Java Class Library (JCL): java.lang, java.util, java.time, java.io and java.nio, java.sql and javax.sql, java.net, java.lang.math, java.math, java.awt, javax.swing, and javafx. The most popular external libraries are represented by the org.junit, org.mockito, org.apache.log4j, org.slf4j, and org.apache.commons packages. This chapter helps the reader to avoid writing custom code in cases where such functionality already exists and can be just imported and used out of the box.
Chapter 8, Multithreading and Concurrent Processing, presents the ways to increase Java application performance by using workers (threads) that process data concurrently. It explains the concept of Java threads and demonstrates their usage. It also talks about the difference between parallel and concurrent processing, and how to avoid unpredictable results caused by the concurrent modification of a shared resource.
Chapter 9, JVM Structure and Garbage Collection, provides the readers with an overview of JVM’s structure and behavior, which are more complex than we usually expect. One of the service threads, called garbage collection, performs an important mission of releasing the memory from unused objects. After reading this chapter, the readers will understand better what constitutes Java application execution, Java processes inside JVM, garbage collection, and how JVM works in general.
Chapter 10, Managing Data in a Database, explains and demonstrates how to manage—that is, insert, read, update, and delete–data in a database from a Java application. It also provides a short introduction to the SQL language and basic database operations: how to connect to a database, how to create a database structure, how to write a database expression using SQL, and how to execute them.
Chapter 11, Network Programming, describes and discusses the most popular network protocols, User Datagram Protocol (UDP), Transmission Control Protocol (TCP), HyperText Transfer Protocol (HTTP), and WebSocket, and their support for JCL. It demonstrates how to use these protocols and how to implement client-server communication in Java code. The APIs reviewed include URL-based communication and the latest Java HTTP Client API.
Chapter 12, Java GUI Programming, provides an overview of Java GUI technologies and demonstrates how the JavaFX kit can be used to create a GUI application. The latest versions of JavaFX not only provide many helpful features, but also allow preserving and embedding legacy implementations and styles.
Chapter 13, Functional Programming, explains what a functional interface is, provides an overview of functional interfaces that come with JDK, and defines and demonstrates lambda expressions and how to use them with functional interfaces, including using method reference.
Chapter 14, Java Standard Streams, talks about the processing of data streams, which are different from the I/O streams reviewed in Chapter 5, Strings, Input/Output, and Files. It defines what data streams are, how to process their elements using methods (operations) of the java.util.stream.Stream object, and how to chain (connect) stream operations in a pipeline. It also discusses the stream’s initialization and how to process the stream in parallel.
Chapter 15, Reactive Programming, introduces the Reactive Manifesto and the world of reactive programming. It starts with defining and discussing the main related concepts – asynchronous
, non-blocking
, responsive
, and so on. Using them, it then defines and discusses reactive programming, the main reactive frameworks, and talks about RxJava in more details.
Chapter 16, Java Microbenchmark Harness, presents the Java Microbenchmark Harness (JMH) project that allows us to measure various code performance characteristics. It defines what JMH is, how to create and run a benchmark, what the benchmark parameters are, and outlines supported IDE plugins. The chapter ends with some practical demo examples and recommendations.
Chapter 17, Best Practices for Writing High-Quality Code, introduces Java idioms and the most popular and useful practices for designing and writing application code.
To get the most out of this book
Read the chapters systematically and answer the quiz questions at the end of each chapter. Clone or just download the source code repository (see the following sections) and run all the code samples that demonstrate the discussed topics. For getting up to speed in programming, there is nothing better than executing the provided examples, modifying them, and trying your own ideas. Code is truth.
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book's GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
Download the example code files
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Learn-Java-17-Programming. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Download the color images
We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/CQqKD.
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: When an exception is thrown inside a try block, it redirects control flow to the first catch clause.
A block of code is set as follows:
void someMethod(String s){
try {
method(s);
} catch (NullPointerException ex){
//do something
} catch (Exception ex){
//do something else
}
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
class TheParentClass {
private int prop;
public TheParentClass(int prop){
this.prop = prop;
}
// methods follow
}
Any command-line input or output is written as follows:
--module-path /path/JavaFX/lib \
:-add-modules=javafx.controls,javafx.fxml
Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: Select a value for Project SDK (java version 12, if you have installed JDK 12 already) and click Next
.
Tips or important notes
Appear like this.
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Share Your Thoughts
Once you’ve read Learn Java 17 Programming, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Part 1: Overview of Java Programming
Get up and running with fundamental concepts of Java and OOP with practical examples and sample programs. This will build a base, which will help the readers get started with some core/advanced concepts of Java.
This part contains the following chapters:
Chapter 1, Getting Started with Java 17
Chapter 2, Java Object-Oriented Programming (OOP)
Chapter 3, Java Fundamentals
Chapter 1: Getting Started with Java 17
This chapter is about how to start learning Java 17 and Java in general. We will begin with the basics, first explaining what Java is and its main terms, followed by how to install the necessary tools to write and run (execute) a program. In this respect, Java 17 is not much different from the previous Java versions, so this chapter’s content applies to the older versions too.
We will describe and demonstrate all the necessary steps for building and configuring a Java programming environment. This is the bare minimum that should have on your computer to start programming. We also describe the basic Java language constructs and illustrate them with examples that can be executed immediately.
The best way to learn a programming language—or any language, for that matter—is to use it, and this chapter guides readers on how they can do this with Java. We will cover the following topics in this chapter:
How to install and run Java
How to install and run an integrated development environment (IDE)
Java primitive types and operators
String types and literals
Identifiers (IDs) and variables
Java statements
Technical requirements
To be able to execute the code examples provided in this chapter, you will need the following:
A computer with a Microsoft Windows, Apple macOS, or Linux operating system
Java SE version 17 or later
An IDE or your preferred code editor
The instructions for how to set up a Java Standard Edition (SE) and IntelliJ IDEA editor will be provided later in this chapter. The files with the code examples for this chapter are available on GitHub in the https://github.com/PacktPublishing/Learn-Java-17-Programming.git repository, in the examples/src/main/java/com/packt/learnjava/ch01_start folder.
How to install and run Java
When somebody says "Java", they may mean quite different things. They could be referring to any of the following:
Java programming language: A high-level programming language that allows an intent (a program) to be expressed in a human-readable format that can be translated into binary code that is executable by a computer
Java compiler: A program that can read a text written in the Java programming language and translate it into bytecode that can be interpreted by the Java Virtual Machine (JVM) into binary code that is executable by a computer
JVM: A program that reads bytecode of the compiled Java program and interprets it into binary code that is executable by a computer
Java Development Kit (JDK): A collection of programs (tools and utilities), including the Java compiler, the JVM, and supporting libraries, which allow the compilation and execution of a program written in the Java language
The following section walks you through the installation of the JDK of Java 17 and the basic related terms and commands.
What is the JDK and why do we need it?
As we have mentioned already, the JDK includes a Java compiler and the JVM. The task of the compiler is to read a .java file that contains the text of a program written in Java (called source code) and transform (compile) it into bytecode stored in a .class file. The JVM can then read the .class file, interpret the bytecode into binary code, and send it to the operating system for execution. Both the compiler and the JVM have to be invoked explicitly from the command line.
The hierarchy of languages used by Java programs goes like this:
You write Java code (.java file).
The compiler converts your Java code into bytecode (.class file).
The JVM converts the bytecode into machine-level assembly instructions (run on hardware).
Have a look at the following example:
int a = b + c;
When you write the preceding code, the compiler adds the following bytecode to the .class file:
ILOAD b
ILOAD c
IADD
ISTORE a
Write once, run anywhere is the most famous programming marketing jingle driving worldwide adoption. Oracle claims more than 10 million developers use Java, which runs on 13 billion devices. You write Java and compile it into bytecode in .class files. There is a different JVM for Windows, Mac, Unix, Linux, and more, but the same .class file works on all of them.
To support the .java file compilation and its bytecode execution, the JDK installation also includes standard Java libraries called the Java Class Library (JCL). If the program uses a third-party library, it has to be present during compilation and execution. It has to be referred from the same command line that invokes the compiler, and later when the bytecode is executed by the JVM. JCL, on the other hand, does not need to be referred to explicitly. It is assumed that the standard Java libraries reside in the default location of the JDK installation so that the compiler and the JVM know where to find them.
If you do not need to compile a Java program and would like to run only the already compiled .class files, you can download and install the Java Runtime Environment (JRE). For example, it consists of a subset of the JDK and does not include a compiler.
Sometimes, the JDK is referred to as a software development kit (SDK), which is a general name for a collection of software tools and supporting libraries that allow the creation of an executable version of source code written using a certain programming language. So, the JDK is an SDK for Java. This means it is possible to call the JDK an SDK.
You may also hear the terms Java platform and Java edition applied to the JDK. A typical platform is an operating system that allows a software program to be developed and executed. Since the JDK provides its own operating environment, it is called a platform too. An edition is a variation of a Java platform (JDK) assembled for a specific purpose. There are four Java platform editions, as listed here:
Java Platform SE (Java SE): This includes the JVM, JCL, and other tools and utilities.
Java Platform Enterprise Edition (Java EE): This includes Java SE, servers (computer programs that provide services to the applications), JCL, other libraries, code samples, tutorials, and other documentation for developing and deploying large-scale, multi-tiered, and secure network applications.
Java Platform Micro Edition (Java ME): This is a subset of Java SE with some specialized libraries for developing and deploying Java applications for embedded and mobile devices, such as phones, personal digital assistants, TV set-top boxes, printers, and sensors. A variation of Java ME (with its own JVM implementation) is called the Android SDK, which was developed by Google for Android programming.
Java Card: This is the smallest of the Java editions and is intended for developing and deploying Java applications onto small embedded devices such as smart cards. It has two editions: Java Card Classic Edition, for smart cards, (based on International Organization for Standardization (ISO) 7816 and ISO 14443 communication), and Java Card Connected Edition, which supports a web application model and Transmission Control Protocol/Internet Protocol (TCP/IP) as a basic protocol and runs on high-end secure microcontrollers.
So, to install Java means to install the JDK, which also means to install the Java platform on one of the listed editions. In this book, we are going to talk about and use only Java SE (which includes the JVM, JCL, and other tools and utilities necessary to compile your Java program into bytecode, interpret it into binary code, and automatically send it to your operating system for execution).
Installing Java SE
All the recently released JDKs are listed on the official Oracle page at https://www.oracle.com/java/technologies/downloads/#java17 (we will call this the installation home page for further references in later chapters).
Here are the steps that need to be followed to install Java SE:
Select the Java SE tab with your operating system.
Click on the link to the installer that fits your operating system and the format (extension) you are familiar with.
If in doubt, click the Installation Instructions link below and read the installation instructions for your operating system.
Follow the steps that correspond to your operating system.
The JDK is installed successfully when the java -version command on your computer displays the correct Java version, as demonstrated in the following example screenshot:
Commands, tools, and utilities
If you follow the installation instructions, you may have noticed a link (Installed Directory Structure of the JDK) given under Table of Contents. This brings you to a page that describes the location of the installed JDK on your computer and the content of each directory of the JDK root directory. The bin directory contains all executables that constitute Java commands, tools, and utilities. If the bin directory is not added to the PATH environment variable automatically, consider doing so manually so that you can launch a Java executable from any directory.
In the previous section, we have already demonstrated the java -version Java command. A list of the other Java executables available (commands, tools, and utilities) can be found in the Java SE documentation (https://www.oracle.com/technetwork/java/javase/documentation/index.html) by clicking the Java Platform Standard Edition Technical Documentation site link, and then the Tools Reference link on the next page. You can learn more about each executable tool by clicking its link.
You can also run each of the listed executables on your computer using one of the following options:
-?, -h, --help, or -help
These will display a brief description of the executable and all its options.
The most important Java commands are listed here:
javac: This reads a .java file, compiles it, and creates one or more corresponding .class files, depending on how many Java classes are defined in the .java file.
java: This executes a .class file.
These are the commands that make programming possible. Every Java programmer must have a good understanding of their structure and capabilities, but if you are new to Java programming and use an IDE (see the How to install and run an IDE section), you do not need to master these commands immediately. A good IDE hides them from you by compiling a .java file automatically every time you make a change to it. It also provides a graphical element that runs the program every time you click it.
Another very useful Java tool is jcmd. This facilitates communication with, and diagnosis of, any currently running Java processes (JVM) and has many options. But in its simplest form, without any option, it lists all currently running Java processes and their process IDs (PIDs). You can use it to see whether you have runaway Java processes. If you have, you can then kill such a process using the PID provided.
How to install and run an IDE
What used to be just a specialized editor that allowed checking the syntax of a written program the same way a Word editor checks the syntax of an English sentence gradually evolved into an IDE. This bears its main function in the name. It integrates all the tools necessary for writing, compiling, and then executing a program under one graphical user interface (GUI). Using the power of Java compiler, the IDE identifies syntax errors immediately and then helps to improve code quality by providing context-dependent help and suggestions.
Selecting an IDE
There are several IDEs available for a Java programmer, such as NetBeans, Eclipse, IntelliJ IDEA, BlueJ, DrJava, JDeveloper, JCreator, jEdit, JSource, and jCRASP, to name a few. You can read a review of the top Java IDEs and details about each by following this link: https://www.softwaretestinghelp.com/best-java-ide-and-online-compilers. The most popular ones are NetBeans, Eclipse, and IntelliJ IDEA.
NetBeans development started in 1996 as a Java IDE student project at Charles University in Prague. In 1999, the project and the company created around the project were acquired by Sun Microsystems. After Oracle acquired Sun Microsystems, NetBeans became open source, and many Java developers have since contributed to the project. It was bundled with JDK 8 and became an official IDE for Java development. In 2016, Oracle donated it to the Apache Software Foundation.
There is a NetBeans IDE for Windows, Linux, Mac, and Oracle Solaris. It supports multiple programming languages and can be extended with plugins. As of the time of writing, NetBeans is bundled only with JDK 8, but NetBeans 8.2 can work with JDK 9 too and uses features introduced with JDK 9 such as Jigsaw, for example. On netbeans.apache.org, you can read more about the NetBeans IDE and download the latest version, which is 12.5 as of the time of this writing.
Eclipse is the most widely used Java IDE. The list of plugins that add new features to the IDE is constantly growing, so it is not possible to enumerate all the IDE’s capabilities. The Eclipse IDE project has been developed since 2001 as open source software (OSS). A non-profit, member-supported corporation Eclipse Foundation was created in 2004 to provide the infrastructure (version control systems (VCSs), code review systems, build servers, download sites, and so on) and a structured process. None of the 30-something employees of the Eclipse Foundation is working on any of the 150 Eclipse-supported projects.
The sheer number and variety of Eclipse IDE plugins create a certain challenge for a beginner because you have to find your way around different implementations of the same—or similar—features that can, on occasion, be incompatible and may require deep investigation, as well as a clear understanding of all the dependencies. Nevertheless, the Eclipse IDE is very popular and has solid community support. You can read about the Eclipse IDE and download the latest release from www.eclipse.org/ide.
IntelliJ IDEA has two versions: a paid one and a free community edition. The paid version is consistently ranked as the best Java IDE, but the community edition is listed among the three leading Java IDEs too. The JetBrains software company that develops the IDE has offices in Prague, Saint Petersburg, Moscow, Munich, Boston, and Novosibirsk. The IDE is known for its deep intelligence that is "giving relevant suggestions in every context: instant and clever code completion, on-the-fly code analysis, and reliable refactoring tools", as stated by the authors while describing the product on their website (www.jetbrains.com/idea). In the Installing and configuring IntelliJ IDEA section, we will walk you through the installation and configuration of IntelliJ IDEA’s community edition.
Installing and configuring IntelliJ IDEA
These are the steps you need to follow in order to download and install IntelliJ IDEA:
Download an installer of the IntelliJ community edition from www.jetbrains.com/idea/download.
Launch the installer and accept all the default values.
Select .java on the Installation Options screen. We assume you have installed the JDK already, so you do not check the Download and install JRE option.
The last installation screen has a Run IntelliJ IDEA checkbox that you can check to start the IDE automatically. Alternatively, you can leave the checkbox unchecked and launch the IDE manually once the installation is complete.
When the IDE starts for the first time, it provides you with an Import IntelliJ IDEA settings option. Check the Do not import settings checkbox if you have not used IntelliJ IDEA before.
The next couple of screens ask whether you accept the JetBrains Privacy Policy and whether you would like to pay for the license or prefer to continue to use the free community edition or free trial (this depends on the particular download you get).
Answer the questions whichever way you prefer, and if you accept the privacy policy, the Customize IntelliJ IDEA screen will ask you to choose a theme: white (IntelliJ) or dark (Darcula).
Accept the default settings.
If you decide to change the set values, you can do so later by selecting from the topmost menu, File | Settings, on Windows, or Preferences on Linux and macOS.
Creating a project
Before you start writing your program, you need to create a project. There are several ways to create a project in IntelliJ IDEA, which is the same for any IDE, as follows:
New Project: This creates a new project from scratch.
Open: This facilitates reading of the existing project from the filesystem.
Get from VCS: This facilitates reading of the existing project from the VCS.
In this book, we will walk you through the first option only—using the sequence of guided steps provided by the IDE. Options 2 and 3 include many settings that are automatically set by importing an existing project that has those settings. Once you have learned how to create a new project from scratch, the other ways to bring up a project in the IDE will be very easy for you.
Start by clicking the New Project link and proceed further as follows:
Select Maven in the left panel and a value for Project SDK (Java Version 17, if you have installed JDK 17 already), and click Next.
Maven is a project configuration tool whose primary function is to manage project dependencies. We will talk about it shortly. For now, we will use its other responsibility: to define and hold the project code identity using three Artifact Coordinates properties (see next).
Type the project name—for example, myproject.
Select the desired project location in the Location field setting (this is where your new code will reside).
Click Artifact Coordinates, and the following properties will appear:
GroupId: This is the base package name that identifies a group of projects within an organization or an open source community. In our case, l et's type com.mywork.
ArtifactId: To identify a particular project within the group. Leave it as myproject.
Version: To identify the version of the project. Leave it as 1.0-SNAPSHOT.
The main goal is to make the identity of a project unique among all projects in the world. To help avoid a GroupId clash, the convention requires that you start building it from the organization domain name in reverse. For example, if a company has a company.com domain name, the GroupId properties of its projects should start with com.company. That is why for this demonstration we use com.mywork, and for the code in this book, we use the com.packt.learnjava GroupID value.
Click Finish.
You will see the following project structure and generated pom.xml file:
Now, if somebody would like to use the code of your project in their application, they would refer to it by the three values shown, and Maven (if they use it) will bring it in (if you upload your project to the publicly shared Maven repository, of course). Read more about Maven at https://maven.apache.org/guides. Another function of the GroupId value is to define the root directory of the folders tree that holds your project code. The java folder under main will hold the application code, while the java folder under test will hold the test code.
Let’s create our first program using the following steps:
Right-click on java, select New, and then click Package, as illustrated in the following screenshot:
In the New Package window provided, type com.mywork.myproject and press Enter.
You should see in the left panel the following set of new folders:
Right-click on com.mywork.myproject, select New, and then click Java Class, as illustrated in the following screenshot:
In the input window provided, type HelloWorld, as follows:
Press Enter and you will see your first Java class, HelloWorld, created in the com.mywork.myproject package, as illustrated in the following screenshot:
The package reflects the Java class location in the filesystem. We will talk about this more in Chapter 2, Java Object-Oriented Programming (OOP). Now, in order to run a program, we create a main() method. If present, this method can be executed to serve as an entry point into the application. It has a certain format, as shown here:
This has to have the following attributes:
public: Freely accessible from outside the package
static: Should be able to be called without creating an object of the class it belongs to
It should also have the following:
Return void (nothing)
Accept a String array as an input, or varargs, as we have done. We will talk about varargs in Chapter 2, Java Object-Oriented Programming (OOP). For now, suffice to say that String[] args and String... args essentially define the same input format.
We explain how to run the main class using a command line in the Executing examples from the command line section. You can read more about Java command-line arguments in the official Oracle documentation at https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html. It is also possible to run the examples from IntelliJ IDEA.
Notice the two green triangles to the left in the screenshot shown next. By clicking any of them, you can execute the main() method. For example, let’s display Hello, world!.
In order to do this, type the following line inside the main() method:
System.out.println(Hello, world!
);
The following screenshot shows how the program should look afterward:
Then, click one of the green triangles, and you should get the following output in the Terminal area:
From now on, every time we are going to discuss code examples, we will run them the same way, by using the main() method. While doing this, we will not capture a screenshot but put the result in comments, because such a style is easier to follow. For example, the following code snippet displays how the previous code demonstration would look in this style:
System.out.println(Hello, world!
); //prints: Hello, world!
It is possible to add a comment (any text) to the right of the code line separated by a double slash //. The compiler does not read this text and just keeps it