Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

Learn the fundamentals of the Java 17 LTS or Java Standard Edition version 17 Long Term Support release, including basic programming concepts and the object-oriented fundamentals necessary at all levels of Java development. Authors Kishori Sharan and Adam L. Davis walk you through writing your first Java program step-by-step. Armed with that practical experience, you'll be ready to learn the core of the Java language. Beginning Java 17 Fundamentals provides over 90 diagrams and 240 complete programs to help you learn the topics faster.

While this book teaches you the basics, it also has been revised to include the latest from Java 17 including the following: value types (records), immutable objects with an efficient memory layout; local variable type inference (var); pattern matching, a mechanism for testing and deconstructing values; sealed types, a mechanism for declaring all possible subclasses of a class; multiline text values; and switch expressions.

The book continues with a series of foundation topics, including using data types, working with operators, and writing statements in Java. These basics lead onto the heart of the Java language: object-oriented programming. By learning topics such as classes, objects, interfaces, and inheritance you'll have a good understanding of Java's object-oriented model. The final collection of topics takes what you've learned and turns you into a real Java programmer.

You'll see how to take the power of object-oriented programming and write programs that can handle errors and exceptions, process strings and dates, format data, and work with arrays to manipulate data. 

What You Will Learn

  • Write your first Java programs with emphasis on learning object-oriented programming
  • How to work with switch expressions, value types (records), local variable type inference, pattern matching switch and more from Java 17
  • Handle exceptions, assertions, strings and dates, and object formatting
  • Learn about how to define and use modules
  • Dive in depth into classes, interfaces, and inheritance in Java
  • Use regular expressions
  • Take advantage of the JShell REPL tool

Who This Book Is For

Those who are new to Java programming, who may have some or even no prior programming experience.

Author(s): Kishori Sharan, Adam L. Davis
Edition: 3
Publisher: Apress
Year: 2021

Language: English
Pages: 1033
Tags: Java; Java 17; Object-Oriented Programming;

Table of Contents
About the Authors
About the Technical Reviewer
Acknowledgments
Introduction
Chapter 1: Programming Concepts
What Is Programming?
Components of a Programming Language
Programming Paradigms
Imperative Paradigm
Procedural Paradigm
Declarative Paradigm
Functional Paradigm
Logic Paradigm
Object-Oriented Paradigm
What Is Java?
The Object-Oriented Paradigm and Java
Abstraction
Abstraction for Hiding Complexities
Data Abstraction
Encapsulation and Information Hiding
Inheritance
Polymorphism
Overloading Polymorphism
Coercion Polymorphism
Inclusion Polymorphism
Parametric Polymorphism
Summary
Chapter 2: Setting Up the Environment
System Requirements
Installing JDK 17
The JDK Directory Structure
Verifying the JDK Installation
Starting the JShell Tool
Installing NetBeans 12
Configuring NetBeans
Summary
Chapter 3: Writing Java Programs
The Goal Statement
Using the JShell Tool
What Is a Java Program?
Writing the Source Code
Writing Comments
Declaring a Module
Declaring Types
Package Declaration
Import Declarations
Class Declaration
Types Have Two Names
Compiling the Source Code
Packaging the Compiled Code
Running a Java Program
Playing with Module Options
Listing Observable Modules
Limiting the Observable Modules
Describing a Module
Printing Module Resolution Details
Dry-Running Your Program
Enhancing a Module Descriptor
Running Java Programs in Legacy Mode
Duplicate Modules on a Module Path
Syntax for Command-Line Options
Writing Java Programs Using the NetBeans IDE
Creating a Java Project
Creating Modular JARs in NetBeans
NetBeans Project Directory Structure
Adding Classes to a Module
Customizing NetBeans Project Properties
Opening an Existing NetBeans Project
Behind the Scenes
Summary
Chapter 4: Data Types
What Is a Data Type
What Is an Identifier?
Keywords
Data Types in Java
Local Variable Type Inference
Primitive Data Types in Java
Integral Data Types
The int Data Type
The long Data Type
The byte Data Type
The short Data Type
The char Data Type
Character Literals in Single Quotes
Character Escape Sequence
Unicode Character Escape Sequence
Octal Character Escape Sequence
The boolean Data Type
Floating-Point Data Types
The float Data Type
The double Data Type
Underscores in Numeric Literals
Java Compiler and Unicode Escape Sequence
A Short Break
Binary Representation of Integers
Diminished Radix Complement
Radix Complement
Binary Representation of Floating-Point Numbers
32-Bit Single-Precision Floating-Point Format
Sign
Exponent
Significand
Special Floating-Point Numbers
Signed Zeros
Signed Infinities
NaN
Denormals
Rounding Modes
Rounding Toward Zero
Rounding Toward Positive Infinity
Rounding Toward Negative Infinity
Rounding Toward Nearest
IEEE Floating-Point Exceptions
Division by Zero Exception
Invalid Operation Exception
Overflow Exception
Underflow Exception
Inexact Exception
Java and IEEE Floating-Point Standards
Little-Endian and Big-Endian
Summary
Chapter 5: Operators
What Is an Operator?
Assignment Operator
Declaration, Initialization, and Assignment
Arithmetic Operators
Addition Operator (+)
Subtraction Operator (-)
Multiplication Operator (*)
Division Operator (/)
Modulus Operator (%)
Rule #1
Rule #2
Rule #1
Rule #2
Rule #3
Rule #4
Rule #5
Unary Plus Operator (+)
Unary Minus Operator (-)
Compound Arithmetic Assignment Operators
Increment (++) and Decrement (--) Operators
String Concatenation Operator (+)
Relational Operators
Equality Operator (==)
Rule #1
Rule #2
Rule #3
Inequality Operator (!=)
Greater Than Operator (>)
Greater Than or Equal to Operator (>=)
Less Than Operator (<)
Less Than or Equal to Operator (<=)
Boolean Logical Operators
Logical NOT Operator (!)
Logical Short-Circuit AND Operator (&&)
Logical AND Operator (&)
Logical Short-Circuit OR Operator (||)
Logical OR Operator (|)
Logical XOR Operator (^)
Compound Boolean Logical Assignment Operators
Ternary Operator (?:)
Bitwise Operators
Operator Precedence
Summary
Chapter 6: Statements
What Is a Statement?
Types of Statements
Declaration Statement
Expression Statement
Control Flow Statement
A Block Statement
The if-else Statement
The switch Statement
The switch Expression
The for Statement
Initialization
Condition Expression
Expression List
The for-each Statement
The while Statement
The do-while Statement
The break Statement
The continue Statement
An Empty Statement
Summary
Chapter 7: Classes
What Is a Class?
Declaring a Class
Declaring Fields in a Class
Creating Instances of a Class
The null Reference Type
Using Dot Notation to Access Fields of a Class
Default Initialization of Fields
Access Level Modifiers for a Class
Import Declarations
Single-Type Import Declaration
Import-on-Demand Declaration
Import Declarations and Type Search Order
Automatic Import Declarations
Static Import Declarations
Static Import Rule #1
Static Import Rule #2
Static Import Rule #3
Declaring a Record
Summary
Chapter 8: Methods
What Is a Method?
Declaring Methods of a Class
Local Variables
Rule #1
Rule #2
Rule #3
Rule #4
Instance Methods and Class Methods
Invoking a Method
The Special main() Method
What Is this?
Access Levels for Class Members
Access Level: A Case Study
What Is a Var-Args Method?
Overloading a Var-Args Method
Var-Args Methods and the main() Method
Parameter-Passing Mechanisms
Pass by Value
Pass by Constant Value
Pass by Reference
Pass by Reference Value
Pass by Constant Reference Value
Pass by Result
Pass by Value Result
Pass by Name
Pass by Need
Parameter-Passing Mechanisms in Java
Summary
Chapter 9: Constructors
What Is a Constructor?
Declaring a Constructor
Overloading a Constructor
Writing Code for a Constructor
Calling a Constructor from Another Constructor
Using a return Statement Inside a Constructor
Access Level Modifier for a Constructor
Default Constructor
A static Constructor
Instance Initialization Block
Static Initialization Block
The final Keyword
final Local Variables
final Parameters
final Instance Variables
final Class Variables
final Reference Variables
Compile-Time vs. Runtime final Variables
Generic Classes
Summary
Chapter 10: Modules
What Is a Module?
Declaring Modules
Declaring Module Dependence
An Example of Module Dependence
Troubleshooting
Empty Package Error
Module Not Found Error
Package Does Not Exist Error
Module Resolution Exception
Implicit Dependence
Optional Dependence
Opening Modules and Packages
Open Modules
Opening Packages
Splitting Packages Across Modules
Restrictions in Module Declarations
Types of Modules
Normal Modules
Open Modules
Automatic Modules
Unnamed Modules
Aggregator Modules
Knowing About Modules at Runtime
Migration Path to Modules
Java Class Dependency Analyzer
Disassembling Module Definitions
Summary
Chapter 11: Object and Objects Classes
The Object Class
Rule #1
Rule #2
What Is the Class of an Object?
Computing the Hash Code of an Object
Comparing Objects for Equality
String Representation of an Object
Cloning Objects
Finalizing an Object
Immutable Objects
The Objects Class
Bounds Checks
Comparing Objects
Computing Hash Code
Checking for Null
Validating Arguments
Obtaining String Representation of Objects
Using the Objects Class
Summary
Chapter 12: Wrapper Classes
Wrapper Classes
Numeric Wrapper Classes
The Character Wrapper Class
The Boolean Wrapper Class
Unsigned Numeric Operations
Autoboxing and Unboxing
Beware of Null Values
Overloaded Methods and Autoboxing/Unboxing
Comparison Operators and Autoboxing/Unboxing
Collections and Autoboxing/Unboxing
Summary
Chapter 13: Exception Handling
What Is an Exception?
An Exception Is an Object
Using a try-catch Block
Transfer of Control
Exception Class Hierarchy
Arranging Multiple catch Blocks
A Multi-catch Block
Checked and Unchecked Exceptions
Checked Exception: Catch or Declare
Checked Exceptions and Initializers
Throwing an Exception
Creating an Exception Class
The finally Block
Rethrowing an Exception
Analysis of Rethrown Exceptions
Throwing Too Many Exceptions
Accessing the Stack of a Thread
The try-with-resources Block
Summary
Chapter 14: Assertions
What Is an Assertion?
Testing Assertions
Enabling/Disabling Assertions
Using Assertions
Checking for Assertion Status
Summary
Chapter 15: Strings
What Is a String?
String Literals
Escape Sequence Characters in String Literals
Unicode Escapes in String Literals
What Is a CharSequence?
Creating String Objects
Length of a String
String Literals Are String Objects
String Objects Are Immutable
Comparing Strings
String Pool
String Operations
Getting the Character at an Index
Testing Strings for Equality
Testing a String to Be Empty
Changing the Case
Searching for a String
Representing Values as Strings
Getting a Substring
Trimming a String
Replacing Part of a String
Matching the Start and End of a String
Splitting and Joining Strings
Strings in a switch Statement
Testing a String for Palindrome
StringBuilder and StringBuffer
String Concatenation Operator (+)
Multiline Strings
Language-Sensitive String Comparison
Summary
Chapter 16: Dates and Times
The Date-Time API
Design Principles
A Quick Example
Evolution of Timekeeping
Time Zones and Daylight Savings Time
Calendar Systems
The Julian Calendar
The Gregorian Calendar
ISO-8601 Standards for Datetime
Exploring the Date-Time API
The ofXxx() Methods
The from() Methods
The withXxx() Methods
The getXxx() Methods
The toXxx() Methods
The atXxx() Methods
The plusXxx() and minusXxx() Methods
The multipliedBy(), dividedBy(), and negated() Methods
Instants and Durations
Dividing a Duration by Another Duration
Converting and Retrieving Duration Parts
Truncating a Duration
Human-Scale Time
The ZoneOffset Class
The ZoneId Class
Useful Datetime-Related Enums
Representing Months
Representing the Day of the Week
Representing Datetime Fields
Representing the Units of Datetime Fields
Local Date, Time, and Datetime
Offset Time and Datetime
Zoned Datetime
Same Instant, Different Times
Clocks
Periods
Period Between Two Dates and Times
Partials
Adjusting Dates
Querying Datetime Objects
Non-ISO Calendar Systems
Formatting Dates and Times
Using Predefined Formatters
Using the format() Method of Datetime Classes
Using User-Defined Patterns
Using Locale-Specific Formats
Using the DateTimeFormatterBuilder Class
Parsing Dates and Times
Legacy Datetime Classes
The Date Class
The Calendar Class
The add() Method
The roll() Method
Interoperability with Legacy Datetime Classes
Summary
Chapter 17: Formatting Data
Formatting Dates
Using Predefined Date Formats
Using Custom Date Formats
Parsing Dates
Formatting Numbers
Using Predefined Number Formats
Using Custom Number Formats
Parsing Numbers
printf-Style Formatting
The Big Picture
The Details
Referencing an Argument Inside a Format Specifier
Ordinary Indexing
Explicit Indexing
Relative Indexing
Using Flags in a Format Specifier
Conversion Characters
General Formatting
Writing a Custom Formatter
Character Formatting
Numeric Formatting
Integral Number Formatting
Floating-Point Number Formatting
Formatting Dates and Times
Summary
Chapter 18: Regular Expressions
What Is a Regular Expression?
Metacharacters
Character Classes
Predefined Character Classes
More Powers to Regular Expressions
Compiling Regular Expressions
Creating a Matcher
Matching the Pattern
Querying a Match
Beware of Backslashes
Quantifiers in Regular Expressions
Matching Boundaries
Groups and Back Referencing
Using Named Groups
Resetting the Matcher
Final Words on Email Validations
Find-and-Replace Using Regular Expressions
Streams of Matched Results
Summary
Chapter 19: Arrays
What Is an Array?
Arrays Are Objects
Accessing Array Elements
Length of an Array
Initializing Array Elements
Beware of Reference-Type Arrays
Explicit Array Initialization
Limitations of Using Arrays
Simulating Variable-Length Arrays
Passing an Array as a Parameter
Array Parameter Reference
Elements of the Array Parameter
The Objects Referred To by the Array Parameter Elements
Command-Line Arguments
Multidimensional Arrays
Accessing Elements of a Multidimensional Array
Initializing Multidimensional Arrays
Enhanced for Loop for Arrays
Array Declaration Syntax
Runtime Array Bounds Checks
What Is the Class of an Array Object?
Array Assignment Compatibility
Converting a List to an Array
Performing Array Operations
Converting Arrays to Another Type
Searching an Array
Comparing Arrays
Copying Arrays
Filling Arrays
Computing Hash Code
Performing Parallel Accumulation
Sorting Arrays
Summary
Chapter 20: Inheritance
What Is Inheritance?
Inheriting Classes
The Object Class Is the Default Superclass
Inheritance and Hierarchical Relationship
What Is Inherited by a Subclass?
Upcasting and Downcasting
The instanceof Operator
Binding
Early Binding
Late Binding
Method Overriding
Method Overriding Rule #1
Method Overriding Rule #2
Method Overriding Rule #3
Method Overriding Rule #4
Method Overriding Rule #5
Method Overriding Rule #6
Accessing an Overridden Method
Method Overloading
Inheritance and Constructors
Method Hiding
Field Hiding
Disabling Inheritance
Sealed Classes
Abstract Classes and Methods
Method Overriding and Generic Method Signatures
Typo Danger in Method Overriding
Is-a, Has-a, and Part-of Relationships
Pattern-Matching Switch
No Multiple Inheritance of Classes
Summary
Chapter 21: Interfaces
What Is an Interface?
Proposed Solution #1
Proposed Solution #2
Proposed Solution #3
An Ideal Solution
Declaring an Interface
Declaring Interface Members
Constant Field Declarations
Method Declarations
Abstract Method Declarations
Static Method Declarations
Default Method Declarations
Private Methods in an Interface
Nested Type Declarations
An Interface Defines a New Type
Implementing an Interface
Implementing Interface Methods
Implementing Multiple Interfaces
Implementing an Interface Partially
The Supertype-Subtype Relationship
Interface Inheritance
The Superinterface-Subinterface Relationship
Inheriting Conflicting Implementations
The Superclass Always Wins
Example #1
Example #2
Example #3
The Most Specific Superinterface Wins
The Class Must Override the Conflicting Method
The instanceof Operator
Marker Interfaces
Functional Interfaces
Comparing Objects
Using the Comparable Interface
Using the Comparator Interface
Polymorphism: One Object, Many Views
Dynamic Binding and Interfaces
Summary
Chapter 22: Enum Types
What Is an Enum Type?
The Superclass of an Enum Type
Using Enum Types in switch Statements
Associating Data and Methods to Enum Constants
Associating a Body to an Enum Constant
Comparing Two Enum Constants
Nested Enum Types
Implementing an Interface to an Enum Type
Reverse Lookup for Enum Constants
Range of Enum Constants
Summary
Chapter 23: Java Shell
What Is the Java Shell?
The JShell Architecture
Starting the JShell Tool
Exiting the JShell Tool
What Are Snippets and Commands?
Evaluating Expressions
Listing Snippets
Editing Snippets
Rerunning Previous Snippets
Declaring Variables
Import Statements
Method Declarations
Type Declarations
Setting the Execution Environment
No Checked Exceptions
Auto-completion
History of Snippets and Commands
Reading JShell Stack Trace
Reusing JShell Sessions
Resetting the JShell State
Reloading the JShell State
Configuring JShell
Setting the Snippet Editor
Setting Feedback Mode
Creating Custom Feedback Modes
Setting Up Startup Snippets
Using JShell Documentation
The JShell API
Creating a JShell
Working with Snippets
Handling Snippet Events
An Example
Summary
Appendix A: Character Encodings
ASCII
8-Bit Character Sets
Universal Multiple-Octet Coded Character Set (UCS)
UCS-2
UCS-4
UTF-16 (UCS Transformation Format 16)
UTF-8 (UCS Transformation Format 8)
Java and Character Encodings
Appendix B: Documentation Comments
Writing Documentation Comments
List of Block and Inline Tags
@author
@deprecated
@exception
@param
@return
@see
@serial
@serialData
@serialField
@since
@throws
@version
{@code }
{@docRoot}
{@inheritDoc}
{@link