Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

19
Beginning Java 8 Fundamentals Language Syntax, Arrays, Data Types, Objects, and Regular Expressions Kishori Sharan Apress*

Transcript of Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

Page 1: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

Beginning Java 8

Fundamentals

Language Syntax, Arrays, Data Types,

Objects, and Regular Expressions

Kishori Sharan

Apress*

Page 2: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

Contents

J

Foreword xxv

About the Author xxvii

About the Technical Reviewer xxix

Acknowledgments xxxi

Introduction xxxiii

Chapter 1: Programming Concepts 1

What Is Programming? 1

Components of a Programming Language 3

Programming Paradigms 4

Imperative Paradigm 5

Procedural Paradigm 6

Declarative Paradigm 7

Functional Paradigm 7

Logic Paradigm 8

Object-Oriented Paradigm 8

What Is Java? 11

The Object-Oriented Paradigm and Java 12

Abstraction 13

Encapsulation and Information Hiding 22

Inheritance 23

Polymorphism 25

Summary 29

vii

Page 3: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

m CONTENTS

Chapter 2: Writing Java Programs 31

What is a Java Program? 31

System Requirements 31

Writing the Source Code 32

Package Declaration 33

Import Declarations 34

Class Declaration 35

Compiling the Source Code 42

Running the Compiled Code 43

Using NetBeans IDE 48

Creating a Java Project 48

Adding Classes to the Project 52

Customizing Project Properties 54

Opening an Existing NetBeans Project 55

Behind the Scenes 56

Summary 59

Chapter 3: Data Types 61

What Is a Data Type? 61

What Is an Identifier? 62

Data Types in Java 63

Primitive Data Types in Java 67

Integral Data Types 67

Floating-Point Data Types 76

Underscores in Numeric Literals 80

Java Compiler and Unicode Escape Sequence 81

A Short Break 82

Binary Representation of Integers 83

Diminished Radix Complement 84

Radix Complement 85

Page 4: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

Wi CONTENTS

Binary Representation of Floating-Point Numbers 86

32-bit Single-Precision Floating-Point Format 88

Special Floating-Point Numbers 90

Signed Zeros 90

Signed Infinities 91

NaN 91

Denormals 92

Rounding Modes 93

Rounding Toward Zero 93

Rounding Toward Positive Infinity 93

Rounding Toward Negative Infinity 94

Rounding Toward Nearest 94

IEEE Floating-Point Exceptions 94

Division by Zero Exception 95

Invalid Operation Exception 95

Overflow Exception 95

Underflow Exception 95

Inexact Exception 96

Java and IEEE Floating-Point Standards 96

Little-Endian and Big-Endian 96

Summary 97

Chapter 4: Operators 99

What Is an Operator? 99

Assignment Operator (=) 100

Declaration, Initialization, and Assignment 102

Arithmetic Operators 103

Addition Operator (+) 104

Subtraction Operator (-) 107

Multiplication Operator (*) 107

Division Operator (I) 108

ix

Page 5: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

M CONTENTS

Modulus Operator (%) 110

Unary Plus Operator (+) 112

Unary Minus Operator (-) 112

Compound Arithmetic Assignment Operators 113

Increment (++) and Decrement (-) Operators 114

String Concatenation Operator (+) 117

Relational Operators 122

Equality Operator (==) 122

Inequality Operator (!=) 124

Greater Than Operator (>) 125

Greater Than or Equal to Operator (>=) 125

Less Than Operator (<) 126

Less Than or Equal to Operator (<=) 126

Boolean Logical Operators 126

Logical NOT Operator (!) 127

Logical Short-Circuit AND Operator (&&) 127

Logical AND Operator (&) 129

Logical Short-Circuit OR Operator (II) 129

Logical OR Operator (I) 130

Logical XOR Operator (A) 130

Compound Boolean Logical Assignment Operators 131

Ternary Operator (?:) 131

Operator Precedence 132

Bitwise Operators 134

Summary 137

Chapter 5: Statements 139

What Is a Statement? 139

Types of Statements 139

Declaration Statement 139

Expression Statement 140

Control Flow Statement 140

Page 6: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

H CONTENTS

A Block Statement 140

The if-else Statement 142

The switch Statement 146

The for Statement 150

Initialization 152

Condition-expression 152

Expression-list 153

The for-each Statement 156

The while Statement 156

The do-while Statement 158

The break Statement 158

The continue Statement 160

An Empty Statement 162

Summary 163

Chapter 6: Classes and Objects 165

What Is a Class? 165

Declaring a Class 166

Declaring Fields in a Class 167

Creating Instances of a Class 168

The null Reference Type 170

Using Dot Notation to Access Fields of a Class 171

Default Initialization of Fields 173

Access Level Modifiers for a Class 174

Import Declarations 177

Single-Type Import Declaration 178

Import-on-Demand Declaration 179

Import Declarations and Type Search Order 182

Automatic Import Declarations 187

Page 7: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

W CONTENTS

Static Import Declarations 188

Declaring Methods of a Class 192

Local Variables 196

Instance Method and Class Method 199

Invoking a Method 201

The Special mainQ Method 202

What Is this? 205

Access Levels for Class Members 210

Access Level—A Case Study 216

Parameter Passing Mechanisms 222

Pass By Value 223

Pass By Constant Value 226

Pass By Reference 226

Pass By Reference Value 230

Pass by Constant Reference Value 230

Pass by Result 231

Pass by Value Result 231

Pass By Name 232

Pass by Need 233

Parameter Passing Mechanisms in Java 233

Constructors 245

Declaring a Constructor 245

Overloading a Constructor 247

Writing Code for a Constructor 249

Calling a Constructor from another Constructor 252

Using a return Statement Inside a Constructor 254

Access Level Modifier for a Constructor 254

Default Constructor 258

Astatic Constructor 259

Page 8: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

m CONTENTS

Instance Initialization Block 260

static Initialization Block 261

The final Keyword 263

final Local Variables 264

final Parameters 264

final Instance Variables 265

final Class Variables 267

final Reference Variables 268

Compile-time vs. Runtime final Variables 268

What is a varargs Method? 269

Overloading a Varargs Method 274

Varargs Methods and the main() Method 275

Generic Classes 276

Summary 278

Chapter 7: The Object and Objects Classes 281

The Object Class 281

Rule #1 281

Rule #2 283

What Is the Class of an Object? 284

Computing Hash Code of an Object 285

Comparing Objects for Equality 289

String Representation of an Object 295

Cloning Objects 299

Finalizing an Object 306

Immutable Objects 308

The Objects Class 313

Summary 316

Page 9: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

m CONTENTS

Chapter 8: Wrapper Classes 317

Wrapper Classes 317

Numeric Wrapper Classes 320

The Character Wrapper Class 322

The Boolean Wrapper Class 323

Unsigned Numeric Operations 324

Autoboxing and Unboxing 326

Beware of Null Values 328

Overloaded Methods and Autoboxing/Unboxing 329

Comparison Operators and AutoBoxing/Unboxing 331

Collections and Autoboxing/Unboxing 333

Summary 334

Chapter 9: Exception Handling 335

What Is an Exception? 335

An Exception Is an Object 337

Using a try-catch Block 338

Transfer of Control 341

Exception Class Hierarchy 341

Arranging Multiple catch Blocks 343

Checked and Unchecked Exceptions 346

Checked Exception - Catch or Declare 349

Checked Exceptions and Initializers 355

Throwing an Exception 357

Creating an Exception Class 357

The finally Block 361

Rethrowing an Exception 365

Analysis of Rethrown Exceptions 368

Throwing too Many Exceptions 368

Page 10: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

n CONTENTS

Accessing the Stack of a Thread 369

The try-with-resources Block 372

A Multi-Catch Block 376

Summary 377

Chapter 10: Assertions 379

What Is an Assertion? 379

Testing Assertions 381

Enabling/Disabling Assertions 382

Using Assertions 384

Checking for Assertion Status 385

Summary 386

Chapter 11: Strings 387

What is a String? 387

String Literals 387

Escape Sequence Characters in String Literals 388

Unicode Escapes in String Literals 388

What is a CharSequence? 389

Creating String Objects 389

Length of a String 390

String Literals Are String Objects 390

String Objects Are Immutable 391

Comparing Two Strings 392

String Pool 393

String Operations 395

Getting the Character at an Index 395

Testing Strings for Equality 396

Testing a String to be Empty 397

Changing the Case 397

Page 11: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

a CONTENTS

Searching for a String 398

Representing Values as Strings 398

Getting a Substring 398

Trimming a String 398

Replacing Part of a String 399

Matching Start and End of a String 399

Splitting and Joining Strings 400

Strings in a switch Statement... 401

Testing a String for Palindrome 403

StringBuilder and StringBuffer 404

String Concatenation Operator (+) 408

Language-Sensitive String Comparison 408

Summary 409

Chapter 12: Dates and Times 411

The Date-Time API 411

Design Principles 412

A Quick Example 412

Evolution of Timekeeping 414

Time Zones and Daylight Saving Time 416

Calendar Systems 417

The Julian Calendar 418

The Gregorian Calendar 418

ISO-8601 Standards for Datetime 419

Exploring the New Date-Time API 421

The ofXXX() Methods 421

The from() Methods 422

The withXXX() Methods 422

The getXXX() Methods 422

Page 12: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

m CONTENTS

The toXXX() Methods 422

The atXXX() Methods 423

The plusXXXO and minusXXX() Methods 423

The multipliedByO, dividedBy(), and negated() Methods 424

Instants and Durations 424

Human-Scale Time 427

The ZoneOffset Class 427

TheZoneld Class 429

Useful Datetime-Related Enums 431

Local Date, Time, and Datetime 436

Offset Time and Datetime 439

Zoned Datetime 440

Same Instant, Different Times 443

Clocks 444

Periods 445

Period Between Two Dates and Times 448

Partials 449

Adjusting Dates 452

Querying Datetime Objects 457

Non-ISO Calendar Systems 462

Formatting Dates and Times 463

Using Predefined Formatters 463

Using the format() Method of Datetime Classes 465

Using User-Defined Patterns 466

Using Locale Specific Formats 471

Using the DateTimeFormatterBuilder Class 473

Parsing Dates and Times 474

Page 13: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

m CONTENTS

Legacy Datetime Classes 477

The Date Class 477

The Calendar Class 478

The add() Method 479

The roll() Method 479

Interoperability with Legacy Datetime Classes 481

Summary 484

Chapter 13: Formatting Data 485

Formatting Dates 485

Formatting Numbers 492

Printf-style Formatting 495

The Big Picture 495

The Details 498

Referencing an Argument inside a Format Specifier 500

Using Flags in a Format Specifier 504

Conversion Characters 505

Summary 518

Chapter 14: Regular Expressions 519

What Is a Regular Expression? 519

Metacharacters 522

Character Classes 523

Predefined Character Classes 523

More Powers to Regular Expressions 524

Compiling Regular Expressions 524

Creating a Matcher 526

Matching the Pattern 526

Beware of Backslashes 529

Quantifiers in Regular Expressions 529

Matching Boundaries 530

Page 14: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

m CONTENTS

Groups and Back Referencing 531

Using Named Groups 535

Resetting the Matcher 538

Final Words on E-mail Validations 538

Find-and-Replace Using Regular Expressions 538

Summary 542

Chapter 15: Arrays 543

What Is an Array? 543

Arrays Are Objects 544

Accessing Array Elements 546

Length of an Array 546

Initializing Array Elements 547

Beware of Reference Type Arrays 549

Explicit Array Initialization 551

Limitations of Using Arrays 552

Variable-Length Arrays 554

Passing an Array as a Parameter 558

Array Parameter Reference 562

Elements of the Array Parameter 563

The Object Referred by the Array Parameter Elements 564

Command-Line Arguments 566

Multi-Dimensional Arrays 570

Accessing Elements of a Multi-Dimensional Array 573

Initializing Multi-Dimensional Arrays 574

Enhanced for Loop for Arrays 574

Array Declaration Syntax 575

Runtime Array Bounds Checks 576

What Is the Class of an Array Object 577

xix

Page 15: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

CONTENTS

Array Assignment Compatibility 579

Converting an ArrayList/Vector to an Array 581

Summary 582

Chapter 16: Inheritance 583

What is Inheritance? 583

Object Class is the Default Superclass 586

Inheritance and Hierarchical Relationship 587

What Is Inherited by a Subclass? 588

Upcasting and Downcasting 589

The instanceof Operator 593

Binding 596

Early Binding 596

Late Binding 599

Method Overriding 602

Method Overriding Rule #1 604

Method Overriding Rule #2 604

Method Overriding Rule #3 604

Method Overriding Rule #4 604

Method Overriding Rule #5 605

Method Overriding Rule #6 605

Accessing Overridden Method 608

Method Overloading 610

Inheritance and Constructors 615

Method Hiding 622

Field Hiding 624

Disabling Inheritance 628

Abstract Classes and Methods 629

Method Overriding and Generic Method Signatures 636

Typo Danger in Method Overriding 638

Page 16: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

CONTENTS

ls-a, has-a, and part-of Relationships 639

No Multiple Inheritance of Classes 641

Summary 642

Chapter 17: Interfaces 643

What Is an Interface? 643

Proposed Solution #1 645

Proposed Solution #2 647

Proposed Solution #3 647

An Ideal Solution 648

Declaring an Interface 652

Declaring Interface Members 653

Constant Fields Declarations 653

Methods Declarations 655

Nested Type Declarations 662

An Interface Defines a New Type 664

Implementing an Interface 666

Implementing Interface Methods 670

Implementing Multiple Interfaces 673

Partially Implementing an Interface 676

The Supertype-Subtype Relationship 677

Interface Inheritance 678

The Superinterface-Subinterface Relationship 684

Inheriting Conflicting Implementations 685

The Superclass Always Wins 685

The Most Specific Superinterface Wins 687

The Class Must Override the Conflicting Method 688

The instanceof Operator 689

Marker Interfaces 692

Functional Interfaces 693

xxi

Page 17: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

m CONTENTS

Comparing Objects 694

Using the Comparable Interface 694

Using the Comparator Interface 696

Polymorphism—One Object, Many Views 701

Dynamic Binding and Interfaces 703

Summary 704

Chapter 18: Enum Types 705

What Is an Enum Type? 705

Superclass of an Enum Type 709

Using Enum Types in switch Statements 712

Associating Data and Methods to Enum Constants 713

Associating a Body to an Enum Constant 715

Comparing Two Enum Constants 719

Nested Enum Types 720

Implementing an Interface to an Enum Type 722

Reverse Lookup for Enum Constants 723

Range of Enum Constants 724

Summary 725

Appendix A: Character Encodings 727

ASCII 728

8-bit Character Sets 733

Universal Multiple-Octet Coded Character Set (UCS) 733

UCS-2 734

UCS-4 734

UTF-16 (UCS Transformation Format 16) 734

UTF-8 (UCS Transformation Format 8) 735

Java and Character Encodings 735

Page 18: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

n CONTENTS

Appendix B: Documentation Comments 739

Writing Documentation Comments 740

List of Block and Inline Tags 742

©author <author-name(s)> 742

©deprecated <explanation-text> 743

©exception <class-name> <description> 743

©param <parameter-name> <description> 743

©return <description> 744

©see <reference> 744

©serial <field-description or include/exclude> 745

©serialData <data-description> 746

©serialField <field-name> <field-type> <field-description> 746

©since <description> 747

©throws <class-name> <description> 747

©version <version-text> 748

{©code <text>} 748

{©docRoot} 748

{©inheritDoc} 748

{©link <package.class#member> <label>} 750

{©linkplain <package.class#member> <label>} 750

{©literal <text>} 750

{©value <package.class#field>} 750

Documenting Packages 751

com/jdojo/utility/package-info.java file 751

com/jdojo/utility/package.html file 752

Overview Documentation 752

Including Unprocessed Files in Documentation 752

Skipping Source Files Processing 752

An Example of Documentation Comments 753

Running the javadoc Tool 755

xxiii

Page 19: Beginning Java 8 fundamentals : language syntax, arrays ...LessThanOperator(

m CONTENTS

Generated Documentation Files 757

Viewing Generated HTML Documentation 758

Summary 758

Appendix C: Compact Profiles 759

Enhancement in the javac Command 762

Enhancement in Java API Documentation 765

Checking for Profile Dependencies 765

Creating Custom JREs Using the EJDK 768

Installing EJDK 768

Running the jrecreate Command 769

Deploying the Custom JRE 773

Running the Custom JRE 773

Index 775