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 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 Programming, and Swing: A Beginner’s Guide He has also written extensively about C, C++, and C# Although interested in all facets of computing, his primary focus is computer languages Schildt holds both graduate and undergraduate 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 He founded JavaFX technology and, most recently, designed the largest addition to the Java EE 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: The Big Picture Dr Coward holds a bachelor’s, master’s, and doctorate in mathematics from the University of Oxford Copyright © 2018 by McGraw-Hill Education (Publisher) 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 system, without the prior written permission of the publisher ISBN: 978-1-25-958932-4 MHID: 1-25-958932-3 The material in this eBook also appears in the print version of this title: ISBN: 978-1-25-958931-7, MHID: 1-25-958931-5 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 Oracle and Java are registered trademarks of Oracle Corporation and/or its affiliates All other trademarks are the property of their respective owners, and McGraw-Hill Education makes no claim of ownership by the mention of products that contain these marks Screen displays of copyrighted Oracle software programs have been reproduced herein with the permission of Oracle Corporation and/or its affiliates Information has been obtained by Publisher from sources believed to be reliable However, because of the possibility of human or mechanical error by our sources, Publisher, or others, Publisher does not guarantee to the accuracy, adequacy, or completeness of any information included in this work 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 information 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, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE McGraw-Hill Education and its licensors 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 accessed 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 Contents INTRODUCTION Java Fundamentals The Origins of Java Java’s Lineage: C and C++ How Java Impacted the Internet Java Simplified Web-Based Programming Java Applets Security Portability Java’s Magic: The Bytecode Moving Beyond Applets The Java Buzzwords Object-Oriented Programming Encapsulation Polymorphism Inheritance Obtaining the Java Development Kit A First Simple Program Entering the Program Compiling the Program The First Sample Program Line by Line Handling Syntax Errors A Second Simple Program Another Data Type Try This 1-1: Converting Gallons to Liters Two Control Statements The if Statement The for Loop Create Blocks of Code Semicolons and Positioning Indentation Practices Try This 1-2: Improving the Gallons-to-Liters Converter The Java Keywords Identifiers in Java The Java Class Libraries Chapter Self Test Introducing Data Types and Operators Why Data Types Are Important Java’s Primitive Types Integers Floating-Point Types Characters The Boolean Type Try This 2-1: How Far Away Is the Lightning? Literals Hexadecimal, Octal, and Binary Literals Character Escape Sequences String Literals A Closer Look at Variables Initializing a Variable Dynamic Initialization The Scope and Lifetime of Variables Operators Arithmetic Operators Increment and Decrement Relational and Logical Operators Short-Circuit Logical Operators The Assignment Operator Shorthand Assignments Type Conversion in Assignments Casting Incompatible Types Operator Precedence Try This 2-2: Display a Truth Table for the Logical Operators Expressions Type Conversion in Expressions Spacing and Parentheses Chapter Self Test Program Control Statements Input Characters from the Keyboard The if Statement Nested ifs The if-else-if Ladder The switch Statement Nested switch Statements Try This 3-1: Start Building a Java Help System The for Loop Some Variations on the for Loop Missing Pieces The Infinite Loop Loops with No Body Declaring Loop Control Variables Inside the for Loop The Enhanced for Loop The while Loop The do-while Loop Try This 3-2: Improve the Java Help System Use break to Exit a Loop Use break as a Form of goto Use continue Try This 3-3: Finish the Java Help System Nested Loops Chapter Self Test Introducing Classes, Objects, and Methods Class Fundamentals The General Form of a Class Defining a Class How Objects Are Created Reference Variables and Assignment Methods Adding a Method to the Vehicle Class Returning from a Method Returning a Value Using Parameters Adding a Parameterized Method to Vehicle Try This 4-1: Creating a Help Class Constructors Parameterized Constructors Adding a Constructor to the Vehicle Class The new Operator Revisited Garbage Collection The this Keyword Chapter Self Test More Data Types and Operators Arrays One-Dimensional Arrays Try This 5-1: Sorting an Array Multidimensional Arrays Two-Dimensional Arrays Irregular Arrays Arrays of Three or More Dimensions Initializing Multidimensional Arrays Alternative Array Declaration Syntax Assigning Array References used with a generic interface, 467-468 used with a method, 450, 463-465 Type safety and generics, 447, 450, 452 and raw types, 473-475 and wildcard arguments, 457 Type(s), 18, 19, 21, 34-35 bounded, 454-457, 468 casting, 56-58, 61 checking, 34, 44, 55, 246, 450, 474 class as a data, 108, 189 conversion, automatic, 55, 196-198 enumeration as a, 416 inference See Type inference information, run-time, 704-705 numeric, default value of, 127 promotion in expressions, 60-61, 173 raw, 473-475 reference, default value of, 127 simple or elemental, 35 Type(s), primitive, 33-40, 41, 130, 190-192, 430, 433, 436 and binary I/O, 348-351 table of, 35 and type parameters, 451 wrappers, 192, 363-365, 430-432, 436, 451 Types, parameterized, 266, 446-447 versus C++ templates, 447 U UI delegate, 550 UnaryOperator predefined functional interface, 513 Unboxing, 432 See also Autoboxing/unboxing Unchecked warnings and raw types, 475 Underscore with integer and floating-point literals, using an, 41 as a keyword, 29 Unicode, 37, 38, 39, 167, 333, 334, 360 uses keyword, 30, 519, 536 statement, 536, 543 V valueChanged( ), 571, 572, 574 valueOf( ), 419-420, 421, 431 values( ), 419-421 Varargs, 216-222 and ambiguity, 221-222 methods, overloading, 220-222 parameter, declaring a, 217-218, 219 Variable(s) capture, 501-502 character, 38 declaration, 18, 19, 24, 44, 45-47 definition of the term, 17 dynamic initialization of, 45 effectively final, 501-502 enumeration, 417 final, 264-265, 417, 419, 423 initializing, 44 instance See Instance variables interface, 279, 290-291, 293 interface reference, 283-284 and JShell, 693-694 member, 10 object reference See Object reference variables scope and lifetime of, 45-47 static, 206-208, 209, 265, 501, 693 transient, 704 volatile, 704 Virtual functions (C++), 254 void, 16 methods, 112, 115 volatile modifier, 704 W wait( ), 265, 402-407 Warth, Chris, Web browser executing applet in, and Java Web Start, 682, 685 while loop, 66, 83-84, 85, 96 Widening conversion, 55-56 Wildcard arguments, 457-463 bounded, 460-463 WindowConstants interface, 556 with keyword, 30, 519, 536 World Wide Web, Wrappers, primitive type, 192, 363-365, 430-432, 436, 451 write( ), 337, 338-339, 343, 353, 356 Writer class, 334, 335, 354, 355, 360 methods defined by, table of, 356 writeDouble( ), 348, 353 X XOR (exclusive OR) operator (^) bitwise, 166, 167, 169-170 Boolean logical, 50, 51 ... Defining a Package Finding Packages and CLASSPATH A Short Package Example Packages and Member Access A Package Access Example Understanding Protected Members Importing Packages Java’s Class Library Is... Comments C An Overview of Java Web Start What Is Java Web Start? Four Key Java Web Start Essentials Java Web Start Apps Require a JAR File Java Web Start Apps Are Signed Java Web Start Relies... Stage and Scene Classes Nodes and Scene Graphs Layouts The Application Class and the Life-cycle Methods Launching a JavaFX Application A JavaFX Application Skeleton Compiling and Running a JavaFX