Java A Beginners Guide, Seventh Edition (Herbert Schildt) (Z-Library)

Author: Herbert Schildt

技术

No Description

📄 File Format: PDF
💾 File Size: 37.4 MB
80
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
(This page has no text content)
📄 Page 2
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 8 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 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: The Big Picture. Dr. Coward holds a bachelor’s, master’s, and doctorate in mathematics from the University of Oxford.
📄 Page 3
(This page has no text content)
📄 Page 4
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.
📄 Page 5
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 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 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.
📄 Page 6
Contents INTRODUCTION 1 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
📄 Page 7
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 1 Self Test 2 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
📄 Page 8
Try This 2-2: Display a Truth Table for the Logical Operators Expressions Type Conversion in Expressions Spacing and Parentheses Chapter 2 Self Test 3 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 3 Self Test 4 Introducing Classes, Objects, and Methods Class Fundamentals The General Form of a Class Defining a Class How Objects Are Created Reference Variables and Assignment
📄 Page 9
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 4 Self Test 5 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 Using the length Member Try This 5-2: A Queue Class The For-Each Style for Loop Iterating Over Multidimensional Arrays Applying the Enhanced for Strings Constructing Strings Operating on Strings Arrays of Strings Strings Are Immutable Using a String to Control a switch Statement
📄 Page 10
Using Command-Line Arguments The Bitwise Operators The Bitwise AND, OR, XOR, and NOT Operators The Shift Operators Bitwise Shorthand Assignments Try This 5-3: A ShowBits Class The ? Operator Chapter 5 Self Test 6 A Closer Look at Methods and Classes Controlling Access to Class Members Java’s Access Modifiers Try This 6-1: Improving the Queue Class Pass Objects to Methods How Arguments Are Passed Returning Objects Method Overloading Overloading Constructors Try This 6-2: Overloading the Queue Constructor Recursion Understanding static Static Blocks Try This 6-3: The Quicksort Introducing Nested and Inner Classes Varargs: Variable-Length Arguments Varargs Basics Overloading Varargs Methods Varargs and Ambiguity Chapter 6 Self Test 7 Inheritance Inheritance Basics Member Access and Inheritance Constructors and Inheritance Using super to Call Superclass Constructors Using super to Access Superclass Members Try This 7-1: Extending the Vehicle Class
📄 Page 11
Creating a Multilevel Hierarchy When Are Constructors Executed? Superclass References and Subclass Objects Method Overriding Overridden Methods Support Polymorphism Why Overridden Methods? Applying Method Overriding to TwoDShape Using Abstract Classes Using final final Prevents Overriding final Prevents Inheritance Using final with Data Members The Object Class Chapter 7 Self Test 8 Packages and Interfaces Packages 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 Contained in Packages Interfaces Implementing Interfaces Using Interface References Try This 8-1: Creating a Queue Interface Variables in Interfaces Interfaces Can Be Extended Default Interface Methods Default Method Fundamentals A More Practical Example of a Default Method Multiple Inheritance Issues Use static Methods in an Interface Private Interface Methods
📄 Page 12
Final Thoughts on Packages and Interfaces Chapter 8 Self Test 9 Exception Handling The Exception Hierarchy Exception Handling Fundamentals Using try and catch A Simple Exception Example The Consequences of an Uncaught Exception Exceptions Enable You to Handle Errors Gracefully Using Multiple catch Statements Catching Subclass Exceptions Try Blocks Can Be Nested Throwing an Exception Rethrowing an Exception A Closer Look at Throwable Using finally Using throws Three Additional Exception Features Java’s Built-in Exceptions Creating Exception Subclasses Try This 9-1: Adding Exceptions to the Queue Class Chapter 9 Self Test 10 Using I/O Java’s I/O Is Built upon Streams Byte Streams and Character Streams The Byte Stream Classes The Character Stream Classes The Predefined Streams Using the Byte Streams Reading Console Input Writing Console Output Reading and Writing Files Using Byte Streams Inputting from a File Writing to a File Automatically Closing a File
📄 Page 13
Reading and Writing Binary Data Try This 10-1: A File Comparison Utility Random-Access Files Using Java’s Character-Based Streams Console Input Using Character Streams Console Output Using Character Streams File I/O Using Character Streams Using a FileWriter Using a FileReader Using Java’s Type Wrappers to Convert Numeric Strings Try This 10-2: Creating a Disk-Based Help System Chapter 10 Self Test 11 Multithreaded Programming Multithreading Fundamentals The Thread Class and Runnable Interface Creating a Thread One Improvement and Two Simple Variations Try This 11-1: Extending Thread Creating Multiple Threads Determining When a Thread Ends Thread Priorities Synchronization Using Synchronized Methods The synchronized Statement Thread Communication Using notify( ), wait( ), and notifyAll( ) An Example That Uses wait( ) and notify( ) Suspending, Resuming, and Stopping Threads Try This 11-2: Using the Main Thread Chapter 11 Self Test 12 Enumerations, Autoboxing, Static Import, and Annotations Enumerations Enumeration Fundamentals Java Enumerations Are Class Types The values( ) and valueOf( ) Methods Constructors, Methods, Instance Variables, and Enumerations
📄 Page 14
Two Important Restrictions Enumerations Inherit Enum Try This 12-1: A Computer-Controlled Traffic Light Autoboxing Type Wrappers Autoboxing Fundamentals Autoboxing and Methods Autoboxing/Unboxing Occurs in Expressions A Word of Warning Static Import Annotations (Metadata) Chapter 12 Self Test 13 Generics Generics Fundamentals A Simple Generics Example Generics Work Only with Reference Types Generic Types Differ Based on Their Type Arguments A Generic Class with Two Type Parameters The General Form of a Generic Class Bounded Types Using Wildcard Arguments Bounded Wildcards Generic Methods Generic Constructors Generic Interfaces Try This 13-1: Create a Generic Queue Raw Types and Legacy Code Type Inference with the Diamond Operator Erasure Ambiguity Errors Some Generic Restrictions Type Parameters Can’t Be Instantiated Restrictions on Static Members Generic Array Restrictions Generic Exception Restriction Continuing Your Study of Generics
📄 Page 15
Chapter 13 Self Test 14 Lambda Expressions and Method References Introducing Lambda Expressions Lambda Expression Fundamentals Functional Interfaces Lambda Expressions in Action Block Lambda Expressions Generic Functional Interfaces Try This 14-1: Pass a Lambda Expression as an Argument Lambda Expressions and Variable Capture Throw an Exception from Within a Lambda Expression Method References Method References to static Methods Method References to Instance Methods Constructor References Predefined Functional Interfaces Chapter 14 Self Test 15 Modules Module Basics A Simple Module Example Compile and Run the First Module Example A Closer Look at requires and exports java.base and the Platform Modules Legacy Code and the Unnamed Module Exporting to a Specific Module Using requires transitive Try This 15-1: Experiment with requires transitive Use Services Service and Service Provider Basics The Service-Based Keywords A Module-Based Service Example Additional Module Features Open Modules The opens Statement requires static
📄 Page 16
Continuing Your Study of Modules Chapter 15 Self Test 16 Introducing Swing The Origins and Design Philosophy of Swing Components and Containers Components Containers The Top-Level Container Panes Layout Managers A First Simple Swing Program The First Swing Example Line by Line Swing Event Handling Events Event Sources Event Listeners Event Classes and Listener Interfaces Use JButton Work with JTextField Create a JCheckBox Work with JList Try This 16-1: A Swing-Based File Comparison Utility Use Anonymous Inner Classes or Lambda Expressions to Handle Events Chapter 16 Self Test 17 Introducing JavaFX JavaFX Basic Concepts The JavaFX Packages The 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 Program The Application Thread A Simple JavaFX Control: Label
📄 Page 17
Using Buttons and Events Event Basics Introducing the Button Control Demonstrating Event Handling and the Button Three More JavaFX Controls CheckBox Try This 17-1: Use the CheckBox Indeterminate State ListView TextField Introducing Effects and Transforms Effects Transforms Demonstrating Effects and Transforms What Next? Chapter 17 Self Test A Answers to Self Tests Chapter 1: Java Fundamentals Chapter 2: Introducing Data Types and Operators Chapter 3: Program Control Statements Chapter 4: Introducing Classes, Objects, and Methods Chapter 5: More Data Types and Operators Chapter 6: A Closer Look at Methods and Classes Chapter 7: Inheritance Chapter 8: Packages and Interfaces Chapter 9: Exception Handling Chapter 10: Using I/O Chapter 11: Multithreaded Programming Chapter 12: Enumerations, Autoboxing, Static Import, and Annotations Chapter 13: Generics Chapter 14: Lambda Expressions and Method References Chapter 15: Modules Chapter 16: Introducing Swing Chapter 17: Introducing JavaFX B Using Java’s Documentation Comments The javadoc Tags
📄 Page 18
@author {@code} @deprecated {@docRoot} @exception {@index} {@inheritDoc} {@link} {@linkplain} {@literal} @param @return @see @serial @serialData @serialField @since @throws {@value} @version The General Form of a Documentation Comment What javadoc Outputs An Example That Uses Documentation 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 on JNLP Linking to the Java Web Start JNLP File Experimenting with Java Web Start Using the Local File System Create a JAR File for ButtonDemo Create a Keystore and Sign ButtonDemo.jar Create a JNLP file for ButtonDemo Create a Short HTML File Called StartBD.html Add ButtonDemo.jnlp to the Exception Site List in the Java Control Panel
📄 Page 19
Execute ButtonDemo via Your Browser Running a Java Web Start Application Using javaws Using Java Web Start with an Applet D Introducing JShell JShell Basics List, Edit, and Rerun Code Add a Method Create a Class Use an Interface Evaluate Expressions and Use Built-in Variables Importing Packages Exceptions Some More JShell Commands Exploring JShell Further E More Java Keywords The transient and volatile Modifiers instanceof strictfp assert Native Methods Another Form of this Index
📄 Page 20
T Introduction he 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, and modules. An introduction to the fundamentals of Swing and JavaFX 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. 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
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List