📄 Page
1
(This page has no text content)
📄 Page
2
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter Blind Folio: i Java™ A Beginner’s Guide Ninth Edition 00-FM.indd 1 12/11/21 9:20 PM
📄 Page
3
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter Blind Folio: ii About the Author Best-selling author Herbert Schildt has written extensively about programming for over three decades and is a leading authority on the Java language. Called “one of the world’s foremost authors of books about programming” by International Developer magazine, his books have sold millions of copies worldwide and have been translated into all major foreign languages. He is the author of numerous books on Java, including Java: The Complete Reference; Herb Schildt’s Java Programming Cookbook; Introducing JavaFX 8 Programming; and Swing: A Beginner’s Guide. He has also written extensively about C, C++, and C#. Featured as one of the rock star programmers in Ed Burns’ book Secrets of the Rock Star Programmers: Riding the IT Crest, Schildt is interested in all facets of computing, but his primary focus is computer languages. Schildt holds both BA and MCS degrees from the University of Illinois. His website is www.HerbSchildt.com. About the Technical Editor Dr. Danny Coward has worked on all editions of the Java platform. He led the definition of Java Servlets into the first version of the Java EE platform and beyond, web services into the Java ME platform, and the strategy and planning for Java SE 7. He founded JavaFX technology and, most recently, designed the largest addition to the Java EE 7 standard, the Java WebSocket API. From coding in Java, to designing APIs with industry experts, to serving for several years as an executive to the Java Community Process, he has a uniquely broad perspective into multiple aspects of Java technology. In addition, he is the author of two books on Java programming: Java WebSocket Programming and Java EE 7: The Big Picture. Most recently, he has been applying his knowledge of Java to helping scale massive Java-based services for one of the world’s most successful software companies. Dr. Coward holds a bachelor’s, master’s, and doctorate in mathematics from the University of Oxford. 00-FM.indd 2 12/11/21 9:20 PM
📄 Page
4
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter Blind Folio: iii Java™ A Beginner’s Guide Ninth Edition Herbert Schildt New York Chicago San Francisco Athens London Madrid Mexico City Milan New Delhi Singapore Sydney Toronto 00-FM.indd 3 12/11/21 9:20 PM
📄 Page
5
Copyright © 2022 by McGraw Hill. All rights reserved. Except as permitted under the United States Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval sys- tem, without the prior written permission of the publisher, with the exception that the program listings may be entered, stored, and executed in a computer system, but they may not be reproduced for publication. ISBN: 978-1-26-046356-9 MHID: 1-26-046356-7 The material in this eBook also appears in the print version of this title: ISBN: 978-1-26-046355-2, MHID: 1-26-046355-9. eBook conversion by codeMantra Version 1.0 All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark. Where such designations appear in this book, they have been printed with initial caps. McGraw-Hill Education eBooks are available at special quantity discounts to use as premiums and sales promotions or for use in corporate training programs. To contact a representative, please visit the Contact Us page at www.mhprofessional.com. Information has been obtained by McGraw Hill from sources believed to be reliable. However, because of the possibility of human or mechanical error by our sources, McGraw Hill, or others, McGraw Hill does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omissions or the results obtained from the use of such information. Oracle Corporation does not make any representations or warranties as to the accuracy, adequacy, or completeness of any in- formation contained in this Work, and is not responsible for any errors or omissions. TERMS OF USE This is a copyrighted work and McGraw-Hill Education and its licensors reserve all rights in and to the work. Use of this work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill Education’s prior consent. You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited. Your right to use the work may be terminated if you fail to comply with these terms. THE WORK IS PROVIDED “AS IS.” McGRAW-HILL EDUCATION AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, IN- CLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICU- LAR PURPOSE. McGraw-Hill Education and its licensors do not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free. Neither McGraw-Hill Education nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom. McGraw-Hill Education has no responsibility for the content of any information ac- cessed through the work. Under no circumstances shall McGraw-Hill Education and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages. This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise.
📄 Page
6
v BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter Contents INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii 1 Java Fundamentals .......................................................................................... 1 The History and Philosophy of Java ............................................................................... 3 The Origins of Java ............................................................................................... 3 Java’s Lineage: C and C++ ................................................................................... 4 How Java Impacted the Internet ............................................................................ 4 Java’s Magic: The Bytecode ................................................................................. 6 Moving Beyond Applets ....................................................................................... 8 A Faster Release Schedule .................................................................................... 8 The Java Buzzwords ............................................................................................. 9 Object-Oriented Programming ....................................................................................... 10 Encapsulation ........................................................................................................ 11 Polymorphism ....................................................................................................... 11 Inheritance ............................................................................................................ 12 The Java Development Kit ............................................................................................. 12 A First Simple Program .................................................................................................. 13 Entering the Program ............................................................................................ 14 Compiling the Program ......................................................................................... 14 The First Sample Program Line by Line .............................................................. 15 00-FM.indd 5 12/11/21 9:20 PM
📄 Page
7
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter vi Java: A Beginner’s Guide Handling Syntax Errors .................................................................................................. 17 A Second Simple Program ............................................................................................. 18 Another Data Type ......................................................................................................... 20 Try This 1-1: Converting Gallons to Liters .................................................................... 21 Two Control Statements ................................................................................................. 22 The if Statement .................................................................................................... 23 The for Loop ......................................................................................................... 24 Create Blocks of Code .................................................................................................... 26 Semicolons and Positioning ........................................................................................... 27 Indentation Practices ...................................................................................................... 28 Try This 1-2: Improving the Gallons-to-Liters Converter .............................................. 28 The Java Keywords ......................................................................................................... 29 Identifiers in Java ............................................................................................................ 30 The Java Class Libraries ................................................................................................. 31 Chapter 1 Self Test ......................................................................................................... 31 2 Introducing Data Types and Operators ........................................................ 33 Why Data Types Are Important ...................................................................................... 34 Java’s Primitive Types .................................................................................................... 34 Integers .................................................................................................................. 35 Floating-Point Types ............................................................................................. 37 Characters ............................................................................................................. 37 The Boolean Type ........................................................................................................... 39 Try This 2-1: How Far Away Is the Lightning? .............................................................. 40 Literals ............................................................................................................................ 41 Hexadecimal, Octal, and Binary Literals .............................................................. 42 Character Escape Sequences ................................................................................. 42 String Literals ....................................................................................................... 43 A Closer Look at Variables ............................................................................................. 44 Initializing a Variable ............................................................................................ 44 Dynamic Initialization .......................................................................................... 45 The Scope and Lifetime of Variables ............................................................................. 45 Operators ........................................................................................................................ 48 Arithmetic Operators ...................................................................................................... 48 Increment and Decrement ..................................................................................... 49 Relational and Logical Operators ................................................................................... 50 Short-Circuit Logical Operators ..................................................................................... 52 The Assignment Operator ............................................................................................... 53 Shorthand Assignments .................................................................................................. 53 Type Conversion in Assignments ................................................................................... 55 Casting Incompatible Types ........................................................................................... 56 Operator Precedence ....................................................................................................... 58 Try This 2-2: Display a Truth Table for the Logical Operators ...................................... 59 00-FM.indd 6 12/11/21 9:20 PM
📄 Page
8
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter Contents vii Expressions ..................................................................................................................... 60 Type Conversion in Expressions ........................................................................... 60 Spacing and Parentheses ....................................................................................... 62 Chapter 2 Self Test ......................................................................................................... 62 3 Program Control Statements ......................................................................... 65 Input Characters from the Keyboard .............................................................................. 66 The if Statement ............................................................................................................. 67 Nested ifs ........................................................................................................................ 69 The if-else-if Ladder ....................................................................................................... 70 The Traditional switch Statement ................................................................................... 71 Nested switch Statements ............................................................................................... 75 Try This 3-1: Start Building a Java Help System ........................................................... 75 The for Loop ................................................................................................................... 77 Some Variations on the for Loop .................................................................................... 79 Missing Pieces ................................................................................................................ 80 The Infinite Loop .................................................................................................. 81 Loops with No Body ...................................................................................................... 81 Declaring Loop Control Variables Inside the for Loop .................................................. 82 The Enhanced for Loop .................................................................................................. 83 The while Loop .............................................................................................................. 83 The do-while Loop ......................................................................................................... 85 Try This 3-2: Improve the Java Help System ................................................................. 87 Use break to Exit a Loop ................................................................................................ 90 Use break as a Form of goto ........................................................................................... 91 Use continue ................................................................................................................... 96 Try This 3-3: Finish the Java Help System .................................................................... 97 Nested Loops .................................................................................................................. 101 Chapter 3 Self Test ......................................................................................................... 102 4 Introducing Classes, Objects, and Methods .................................................. 105 Class Fundamentals ........................................................................................................ 106 The General Form of a Class ................................................................................ 107 Defining a Class .................................................................................................... 108 How Objects Are Created ............................................................................................... 110 Reference Variables and Assignment ............................................................................. 111 Methods .......................................................................................................................... 112 Adding a Method to the Vehicle Class .................................................................. 112 Returning from a Method ............................................................................................... 114 Returning a Value ........................................................................................................... 115 Using Parameters ............................................................................................................ 117 Adding a Parameterized Method to Vehicle ......................................................... 119 Try This 4-1: Creating a Help Class ............................................................................... 121 00-FM.indd 7 12/11/21 9:20 PM
📄 Page
9
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter viii Java: A Beginner’s Guide Constructors ................................................................................................................... 126 Parameterized Constructors ............................................................................................ 128 Adding a Constructor to the Vehicle Class ..................................................................... 128 The new Operator Revisited ........................................................................................... 130 Garbage Collection ......................................................................................................... 130 The this Keyword ........................................................................................................... 131 Chapter 4 Self Test ......................................................................................................... 133 5 More Data Types and Operators ................................................................... 135 Arrays ............................................................................................................................. 136 One-Dimensional Arrays ...................................................................................... 137 Try This 5-1: Sorting an Array ....................................................................................... 140 Multidimensional Arrays ................................................................................................ 142 Two-Dimensional Arrays ...................................................................................... 142 Irregular Arrays ..................................................................................................... 143 Arrays of Three or More Dimensions ................................................................... 144 Initializing Multidimensional Arrays .................................................................... 144 Alternative Array Declaration Syntax ............................................................................ 145 Assigning Array References ........................................................................................... 146 Using the length Member ............................................................................................... 147 Try This 5-2: A Queue Class .......................................................................................... 149 The For-Each Style for Loop .......................................................................................... 153 Iterating Over Multidimensional Arrays ............................................................... 156 Applying the Enhanced for ................................................................................... 157 Strings ............................................................................................................................. 158 Constructing Strings ............................................................................................. 159 Operating on Strings ............................................................................................. 160 Arrays of Strings ................................................................................................... 162 Strings Are Immutable .......................................................................................... 162 Using a String to Control a switch Statement ....................................................... 163 Using Command-Line Arguments .................................................................................. 166 Using Type Inference with Local Variables .................................................................... 167 Local Variable Type Inference with Reference Types .......................................... 169 Using Local Variable Type Inference in a for Loop .............................................. 171 Some var Restrictions ........................................................................................... 171 The Bitwise Operators .................................................................................................... 172 The Bitwise AND, OR, XOR, and NOT Operators .............................................. 173 The Shift Operators ............................................................................................... 177 Bitwise Shorthand Assignments ........................................................................... 179 Try This 5-3: A ShowBits Class ..................................................................................... 180 The ? Operator ................................................................................................................ 182 Chapter 5 Self Test ......................................................................................................... 184 00-FM.indd 8 12/11/21 9:20 PM
📄 Page
10
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter Contents ix 6 A Closer Look at Methods and Classes ......................................................... 187 Controlling Access to Class Members ........................................................................... 188 Java’s Access Modifiers ........................................................................................ 189 Try This 6-1: Improving the Queue Class ...................................................................... 193 Pass Objects to Methods ................................................................................................. 194 How Arguments Are Passed .................................................................................. 196 Returning Objects ........................................................................................................... 198 Method Overloading ....................................................................................................... 200 Overloading Constructors ............................................................................................... 205 Try This 6-2: Overloading the Queue Constructor ......................................................... 207 Recursion ........................................................................................................................ 210 Understanding static ....................................................................................................... 212 Static Blocks ......................................................................................................... 215 Try This 6-3: The Quicksort ........................................................................................... 216 Introducing Nested and Inner Classes ............................................................................ 219 Varargs: Variable-Length Arguments ............................................................................. 222 Varargs Basics ....................................................................................................... 223 Overloading Varargs Methods .............................................................................. 226 Varargs and Ambiguity ......................................................................................... 227 Chapter 6 Self Test ......................................................................................................... 228 7 Inheritance ....................................................................................................... 231 Inheritance Basics ........................................................................................................... 232 Member Access and Inheritance ..................................................................................... 235 Constructors and Inheritance .......................................................................................... 238 Using super to Call Superclass Constructors ................................................................. 240 Using super to Access Superclass Members .................................................................. 244 Try This 7-1: Extending the Vehicle Class ..................................................................... 245 Creating a Multilevel Hierarchy ..................................................................................... 248 When Are Constructors Executed? ................................................................................. 250 Superclass References and Subclass Objects ................................................................. 252 Method Overriding ......................................................................................................... 256 Overridden Methods Support Polymorphism ................................................................. 259 Why Overridden Methods? ............................................................................................ 261 Applying Method Overriding to TwoDShape ....................................................... 261 Using Abstract Classes ................................................................................................... 265 Using final ...................................................................................................................... 269 final Prevents Overriding ...................................................................................... 269 final Prevents Inheritance ..................................................................................... 269 Using final with Data Members ............................................................................ 270 The Object Class ............................................................................................................ 271 Chapter 7 Self Test ......................................................................................................... 272 00-FM.indd 9 12/11/21 9:20 PM
📄 Page
11
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter x Java: A Beginner’s Guide 8 Packages and Interfaces .................................................................................. 275 Packages ......................................................................................................................... 276 Defining a Package ............................................................................................... 277 Finding Packages and CLASSPATH .................................................................... 278 A Short Package Example .................................................................................... 278 Packages and Member Access ........................................................................................ 280 A Package Access Example .................................................................................. 281 Understanding Protected Members ................................................................................ 282 Importing Packages ........................................................................................................ 284 Java’s Class Library Is Contained in Packages .............................................................. 286 Interfaces ........................................................................................................................ 286 Implementing Interfaces ................................................................................................. 287 Using Interface References ............................................................................................ 291 Try This 8-1: Creating a Queue Interface ....................................................................... 293 Variables in Interfaces .................................................................................................... 298 Interfaces Can Be Extended ........................................................................................... 299 Default Interface Methods .............................................................................................. 300 Default Method Fundamentals ............................................................................. 301 A More Practical Example of a Default Method .................................................. 303 Multiple Inheritance Issues ................................................................................... 304 Use static Methods in an Interface ................................................................................. 305 Private Interface Methods ............................................................................................... 306 Final Thoughts on Packages and Interfaces ................................................................... 307 Chapter 8 Self Test ......................................................................................................... 307 9 Exception Handling ......................................................................................... 309 The Exception Hierarchy ................................................................................................ 311 Exception Handling Fundamentals ................................................................................ 311 Using try and catch ............................................................................................... 312 A Simple Exception Example ............................................................................... 312 The Consequences of an Uncaught Exception ............................................................... 314 Exceptions Enable You to Handle Errors Gracefully ............................................ 316 Using Multiple catch Statements .................................................................................... 317 Catching Subclass Exceptions ........................................................................................ 318 Try Blocks Can Be Nested ............................................................................................. 319 Throwing an Exception .................................................................................................. 320 Rethrowing an Exception ...................................................................................... 321 A Closer Look at Throwable .......................................................................................... 322 Using finally ................................................................................................................... 324 Using throws ................................................................................................................... 326 Three Additional Exception Features ............................................................................. 327 Java’s Built-in Exceptions .............................................................................................. 329 Creating Exception Subclasses ....................................................................................... 331 Try This 9-1: Adding Exceptions to the Queue Class .................................................... 333 Chapter 9 Self Test ......................................................................................................... 337 00-FM.indd 10 12/11/21 9:20 PM
📄 Page
12
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter Contents xi 10 Using I/O .......................................................................................................... 339 Java’s I/O Is Built upon Streams .................................................................................... 341 Byte Streams and Character Streams ............................................................................. 341 The Byte Stream Classes ................................................................................................ 341 The Character Stream Classes ........................................................................................ 342 The Predefined Streams .................................................................................................. 343 Using the Byte Streams .................................................................................................. 344 Reading Console Input ......................................................................................... 345 Writing Console Output ........................................................................................ 346 Reading and Writing Files Using Byte Streams ............................................................. 347 Inputting from a File ............................................................................................. 347 Writing to a File .................................................................................................... 351 Automatically Closing a File .......................................................................................... 353 Reading and Writing Binary Data .................................................................................. 356 Try This 10-1: A File Comparison Utility ...................................................................... 359 Random-Access Files ..................................................................................................... 360 Using Java’s Character-Based Streams .......................................................................... 362 Console Input Using Character Streams ............................................................... 364 Console Output Using Character Streams ............................................................ 368 File I/O Using Character Streams .................................................................................. 369 Using a FileWriter ................................................................................................ 369 Using a FileReader ............................................................................................... 370 Using Java’s Type Wrappers to Convert Numeric Strings ............................................. 372 Try This 10-2: Creating a Disk-Based Help System ...................................................... 374 Chapter 10 Self Test ....................................................................................................... 381 11 Multithreaded Programming ......................................................................... 383 Multithreading Fundamentals ........................................................................................ 384 The Thread Class and Runnable Interface ...................................................................... 385 Creating a Thread ........................................................................................................... 386 One Improvement and Two Simple Variations ..................................................... 389 Try This 11-1: Extending Thread ................................................................................... 393 Creating Multiple Threads .............................................................................................. 396 Determining When a Thread Ends ................................................................................. 399 Thread Priorities ............................................................................................................. 402 Synchronization .............................................................................................................. 406 Using Synchronized Methods ........................................................................................ 406 The synchronized Statement .......................................................................................... 409 Thread Communication Using notify( ), wait( ), and notifyAll( ) ................................. 412 An Example That Uses wait( ) and notify( ) ......................................................... 413 Suspending, Resuming, and Stopping Threads .............................................................. 418 Try This 11-2: Using the Main Thread ........................................................................... 422 Chapter 11 Self Test ....................................................................................................... 424 00-FM.indd 11 12/11/21 9:20 PM
📄 Page
13
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter xii Java: A Beginner’s Guide 12 Enumerations, Autoboxing, Annotations, and More .................................... 425 Enumerations .................................................................................................................. 426 Enumeration Fundamentals .................................................................................. 427 Java Enumerations Are Class Types ............................................................................... 429 The values( ) and valueOf( ) Methods ............................................................................ 429 Constructors, Methods, Instance Variables, and Enumerations ..................................... 431 Two Important Restrictions .................................................................................. 433 Enumerations Inherit Enum ............................................................................................ 433 Try This 12-1: A Computer-Controlled Traffic Light .................................................... 435 Autoboxing ..................................................................................................................... 440 Type Wrappers ................................................................................................................ 440 Autoboxing Fundamentals ............................................................................................. 442 Autoboxing and Methods ............................................................................................... 443 Autoboxing/Unboxing Occurs in Expressions ............................................................... 445 A Word of Warning ............................................................................................... 446 Static Import ................................................................................................................... 447 Annotations (Metadata) .................................................................................................. 450 Introducing instanceof .................................................................................................... 453 Chapter 12 Self Test ....................................................................................................... 455 13 Generics ............................................................................................................ 457 Generics Fundamentals .................................................................................................. 458 A Simple Generics Example .......................................................................................... 459 Generics Work Only with Reference Types .......................................................... 463 Generic Types Differ Based on Their Type Arguments ........................................ 463 A Generic Class with Two Type Parameters ......................................................... 464 The General Form of a Generic Class .................................................................. 465 Bounded Types ............................................................................................................... 466 Using Wildcard Arguments ............................................................................................ 469 Bounded Wildcards ........................................................................................................ 472 Generic Methods ............................................................................................................ 475 Generic Constructors ...................................................................................................... 477 Generic Interfaces ........................................................................................................... 478 Try This 13-1: Create a Generic Queue .......................................................................... 480 Raw Types and Legacy Code ......................................................................................... 485 Type Inference with the Diamond Operator ................................................................... 488 Local Variable Type Inference and Generics .................................................................. 489 Erasure ............................................................................................................................ 489 Ambiguity Errors ............................................................................................................ 490 Some Generic Restrictions ............................................................................................. 491 Type Parameters Can’t Be Instantiated ................................................................. 491 Restrictions on Static Members ............................................................................ 491 Generic Array Restrictions ................................................................................... 492 Generic Exception Restriction .............................................................................. 493 00-FM.indd 12 12/11/21 9:20 PM
📄 Page
14
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter Contents xiii Continuing Your Study of Generics ................................................................................ 493 Chapter 13 Self Test ....................................................................................................... 493 14 Lambda Expressions and Method References ............................................... 495 Introducing Lambda Expressions ................................................................................... 496 Lambda Expression Fundamentals ....................................................................... 497 Functional Interfaces ............................................................................................. 498 Lambda Expressions in Action ............................................................................. 500 Block Lambda Expressions ............................................................................................ 505 Generic Functional Interfaces ........................................................................................ 506 Try This 14-1: Pass a Lambda Expression as an Argument ........................................... 508 Lambda Expressions and Variable Capture .................................................................... 513 Throw an Exception from Within a Lambda Expression ............................................... 514 Method References ......................................................................................................... 516 Method References to static Methods ................................................................... 516 Method References to Instance Methods .............................................................. 518 Constructor References .................................................................................................. 522 Predefined Functional Interfaces .................................................................................... 525 Chapter 14 Self Test ....................................................................................................... 527 15 Modules ............................................................................................................ 529 Module Basics ................................................................................................................ 531 A Simple Module Example .................................................................................. 532 Compile and Run the First Module Example ....................................................... 536 A Closer Look at requires and exports ................................................................ 537 java.base and the Platform Modules ............................................................................... 538 Legacy Code and the Unnamed Module ........................................................................ 540 Exporting to a Specific Module ...................................................................................... 541 Using requires transitive ................................................................................................. 542 Try This 15-1: Experiment with requires transitive ....................................................... 543 Use Services ................................................................................................................... 546 Service and Service Provider Basics .................................................................... 547 The Service-Based Keywords ............................................................................... 548 A Module-Based Service Example ....................................................................... 548 Additional Module Features ........................................................................................... 555 Open Modules ....................................................................................................... 555 The opens Statement ............................................................................................. 556 requires static ........................................................................................................ 556 Continuing Your Study of Modules ................................................................................ 556 Chapter 15 Self Test ....................................................................................................... 557 16 Switch Expressions, Records, and Other Recently Added Features ........... 559 Enhancements to switch ................................................................................................. 561 Use a List of case Constants ................................................................................. 563 Introducing the switch Expression and the yield Statement ................................. 563 00-FM.indd 13 12/11/21 9:20 PM
📄 Page
15
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter xiv Java: A Beginner’s Guide Introducing the Arrow in a case Statement ........................................................... 565 A Closer Look at the Arrow case .......................................................................... 567 Try This 16-1: Use a switch Expression to Obtain a City’s Time Zone ......................... 571 Records ........................................................................................................................... 573 Record Basics ....................................................................................................... 574 Create Record Constructors .................................................................................. 576 A Closer Look at Record Getter Methods ............................................................ 581 Pattern Matching with instanceof ................................................................................... 581 Sealed Classes and Interfaces ......................................................................................... 583 Sealed Classes ....................................................................................................... 583 Sealed Interfaces ................................................................................................... 586 Future Directions ............................................................................................................ 587 Chapter 16 Self Test ....................................................................................................... 588 17 Introducing Swing ........................................................................................... 591 The Origins and Design Philosophy of Swing ............................................................... 593 Components and Containers ........................................................................................... 595 Components .......................................................................................................... 595 Containers ............................................................................................................. 596 The Top-Level Container Panes ............................................................................ 596 Layout Managers ............................................................................................................ 597 A First Simple Swing Program ...................................................................................... 597 The First Swing Example Line by Line ................................................................ 599 Swing Event Handling .................................................................................................... 602 Events .................................................................................................................... 603 Event Sources ....................................................................................................... 603 Event Listeners ..................................................................................................... 603 Event Classes and Listener Interfaces .................................................................. 604 Use JButton .................................................................................................................... 604 Work with JTextField ..................................................................................................... 608 Create a JCheckBox ....................................................................................................... 611 Work with JList .............................................................................................................. 615 Try This 17-1: A Swing-Based File Comparison Utility ................................................ 619 Use Anonymous Inner Classes or Lambda Expressions to Handle Events .................... 624 Chapter 17 Self Test .................................................................................................. 626 A Answers to Self Tests ....................................................................................... 627 Chapter 1: Java Fundamentals ........................................................................................ 628 Chapter 2: Introducing Data Types and Operators ......................................................... 630 Chapter 3: Program Control Statements ......................................................................... 631 Chapter 4: Introducing Classes, Objects, and Methods .................................................. 634 Chapter 5: More Data Types and Operators ................................................................... 635 Chapter 6: A Closer Look at Methods and Classes ........................................................ 640 Chapter 7: Inheritance .................................................................................................... 645 00-FM.indd 14 12/11/21 9:20 PM
📄 Page
16
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter Contents xv Chapter 8: Packages and Interfaces ................................................................................ 647 Chapter 9: Exception Handling ...................................................................................... 649 Chapter 10: Using I/O .................................................................................................... 652 Chapter 11: Multithreaded Programming ....................................................................... 656 Chapter 12: Enumerations, Autoboxing, Annotations, and More .................................. 658 Chapter 13: Generics ...................................................................................................... 662 Chapter 14: Lambda Expressions and Method References ............................................ 666 Chapter 15: Modules ...................................................................................................... 670 Chapter 16: Switch Expressions, Records, and Other Recently Added Features ........... 671 Chapter 17: Introducing Swing ...................................................................................... 675 B Using Java’s Documentation Comments ....................................................... 683 The javadoc Tags ............................................................................................................ 684 @author ................................................................................................................ 685 {@code} ............................................................................................................... 685 @deprecated ......................................................................................................... 685 {@docRoot} ......................................................................................................... 685 @exception ........................................................................................................... 686 @hidden ................................................................................................................ 686 {@index} .............................................................................................................. 686 {@inheritDoc} ...................................................................................................... 686 {@link} ................................................................................................................. 686 {@linkplain} ......................................................................................................... 687 {@literal} ............................................................................................................. 687 @param ................................................................................................................. 687 @provides ............................................................................................................. 687 @return ................................................................................................................. 687 @see ...................................................................................................................... 687 @since .................................................................................................................. 688 {@summary} ........................................................................................................ 688 @throws ................................................................................................................ 688 @uses .................................................................................................................... 688 {@value} .............................................................................................................. 688 @version ............................................................................................................... 689 The General Form of a Documentation Comment ......................................................... 689 What javadoc Outputs .................................................................................................... 689 An Example That Uses Documentation Comments ....................................................... 689 C Compile and Run Simple Single-File Programs in One Step ...................... 691 D Introducing JShell ........................................................................................... 693 JShell Basics ................................................................................................................... 694 List, Edit, and Rerun Code ............................................................................................. 696 Add a Method ................................................................................................................. 697 Create a Class ................................................................................................................. 698 00-FM.indd 15 12/11/21 9:20 PM
📄 Page
17
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter xvi Java: A Beginner’s Guide Use an Interface .............................................................................................................. 699 Evaluate Expressions and Use Built-in Variables ........................................................... 700 Importing Packages ........................................................................................................ 701 Exceptions ...................................................................................................................... 702 Some More JShell Commands ....................................................................................... 702 Exploring JShell Further ................................................................................................ 703 E More Java Keywords ....................................................................................... 705 The transient and volatile Modifiers ............................................................................... 706 strictfp ............................................................................................................................. 706 assert ............................................................................................................................... 707 Native Methods .............................................................................................................. 708 Another Form of this ...................................................................................................... 708 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711 00-FM.indd 16 12/11/21 9:20 PM
📄 Page
18
xvii BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter Introduction The purpose of this book is to teach you the fundamentals of Java programming. It uses a step-by-step approach complete with numerous examples, self tests, and projects. It assumes no previous programming experience. The book starts with the basics, such as how to compile and run a Java program. It then discusses the keywords, features, and constructs that form the core of the Java language. You’ll also find coverage of some of Java’s most advanced features, including multithreaded programming, generics, lambda expressions, records, and modules. An introduction to the fundamentals of Swing concludes the book. By the time you finish, you will have a firm grasp of the essentials of Java programming. It is important to state at the outset that this book is just a starting point. Java is more than just the elements that define the language. Java also includes extensive libraries and tools that aid in the development of programs. To be a top-notch Java programmer implies mastery of these areas, too. After completing this book, you will have the knowledge to pursue any and all other aspects of Java. The Evolution of Java Only a few languages have fundamentally reshaped the very essence of programming. In this elite group, one stands out because its impact was both rapid and widespread. This language is, of course, Java. It is not an overstatement to say that the original release of Java 1.0 in 1995 by Sun Microsystems, Inc., caused a revolution in programming. This revolution radically transformed the Web into a highly interactive environment. In the process, Java set a new standard in computer language design. 00-FM.indd 17 12/11/21 9:20 PM
📄 Page
19
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter xviii Java: A Beginner’s Guide Over the years, Java has continued to grow, evolve, and otherwise redefine itself. Unlike many other languages, which are slow to incorporate new features, Java has often been at the forefront of computer language development. One reason for this is the culture of innovation and change that came to surround Java. As a result, Java has gone through several upgrades— some relatively small, others more significant. The first major update to Java was version 1.1. The features added by Java 1.1 were more substantial than the increase in the minor revision number would have you think. For example, Java 1.1 added many new library elements, redefined the way events are handled, and reconfigured many features of the original 1.0 library. The next major release of Java was Java 2, where the 2 indicates “second generation.” The creation of Java 2 was a watershed event, marking the beginning of Java’s “modern age.” The first release of Java 2 carried the version number 1.2. It may seem odd that the first release of Java 2 used the 1.2 version number. The reason is that it originally referred to the internal version number of the Java libraries but then was generalized to refer to the entire release itself. With Java 2, Sun repackaged the Java product as J2SE (Java 2 Platform Standard Edition), and the version numbers began to be applied to that product. The next upgrade of Java was J2SE 1.3. This version of Java was the first major upgrade to the original Java 2 release. For the most part, it added to existing functionality and “tightened up” the development environment. The release of J2SE 1.4 further enhanced Java. This release contained several important new features, including chained exceptions, channel-based I/O, and the assert keyword. The release of J2SE 5 created nothing short of a second Java revolution. Unlike most of the previous Java upgrades, which offered important but incremental improvements, J2SE 5 fundamentally expanded the scope, power, and range of the language. To give you an idea of the magnitude of the changes caused by J2SE 5, here is a list of its major new features: ● Generics ● Autoboxing/unboxing ● Enumerations ● The enhanced “for-each” style for loop ● Variable-length arguments (varargs) ● Static import ● Annotations This is not a list of minor tweaks or incremental upgrades. Each item in the list represents a significant addition to the Java language. Some, such as generics, the enhanced for loop, and varargs, introduced new syntax elements. Others, such as autoboxing and auto-unboxing, altered the semantics of the language. Annotations added an entirely new dimension to programming. The importance of these new features is reflected in the use of the version number “5.” The next version number for Java would normally have been 1.5. However, the new features were so significant that a shift from 1.4 to 1.5 just didn’t seem to express the magnitude of the change. Instead, Sun elected to increase the version number to 5 as a way of emphasizing that 00-FM.indd 18 12/11/21 9:20 PM
📄 Page
20
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter Introduction xix a major event was taking place. Thus, it was named J2SE 5, and the Java Development Kit (JDK) was called JDK 5. In order to maintain consistency, however, Sun decided to use 1.5 as its internal version number, which is also referred to as the developer version number. The “5” in J2SE 5 is called the product version number. The next release of Java was called Java SE 6, and Sun once again decided to change the name of the Java platform. First, notice that the “2” has been dropped. Thus, the platform now had the name Java SE, and the official product name was Java Platform, Standard Edition 6, with the development kit being called JDK 6. As with J2SE 5, the 6 in Java SE 6 is the product version number. The internal, developer version number is 1.6. Java SE 6 built on the base of J2SE 5, adding incremental improvements. Java SE 6 added no major features to the Java language proper, but it did enhance the API libraries, added several new packages, and offered improvements to the run time. It also went through several updates during its long (in Java terms) life cycle, with several upgrades added along the way. In general, Java SE 6 served to further solidify the advances made by J2SE 5. The next release of Java was called Java SE 7, with the development kit being called JDK 7. It has an internal version number of 1.7. Java SE 7 was the first major release of Java after Sun Microsystems was acquired by Oracle. Java SE 7 added several new features, including significant additions to the language and the API libraries. Some of the most important features added by Java SE 7 were those developed as part of Project Coin. The purpose of Project Coin was to identify a number of small changes to the Java language that would be incorporated into JDK 7, including ● A String can control a switch statement. ● Binary integer literals. ● Underscores in numeric literals. ● An expanded try statement, called try-with-resources, that supports automatic resource management. ● Type inference (via the diamond operator) when constructing a generic instance. ● Enhanced exception handling in which two or more exceptions can be caught by a single catch (multicatch) and better type checking for exceptions that are rethrown. As you can see, even though the Project Coin features were considered to be small changes to the language, their benefits were much larger than the qualifier “small” would suggest. In particular, the try-with-resources statement profoundly affects the way that a substantial amount of code is written. The next release of Java was Java SE 8, with the development kit being called JDK 8. It has an internal version number of 1.8. JDK 8 represented a very significant upgrade to the Java language because of the inclusion of a far-reaching new language feature: the lambda expression. The impact of lambda expressions was, and continues to be, quite profound, changing both the way that programming solutions are conceptualized and how Java code is written. In the process, lambda expressions can simplify and reduce the amount of source code needed to create certain constructs. The addition of lambda expressions also caused a new operator (the –>) and a new syntax element to be added to the language. In addition to 00-FM.indd 19 12/11/21 9:20 PM