Oracle press java a beginners guide 6th

569 778 0
Oracle press java a beginners guide 6th

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Java™ A Beginner’s Guide Sixth Edition About the Author Best-selling author Herbert Schildt has written extensively about programming for nearly 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, 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, including compilers, interpreters, and robotic control languages He also has an active interest in the standardization of languages Schildt holds both graduate and undergraduate degrees from the University of Illinois He can be reached at his consulting office at (217) 586-4683 His website is www.HerbSchildt.com About the Technical Reviewer 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 Additionally, he is the author of JavaWebSocket Programming and an upcoming book on Java EE Dr Coward holds a bachelor’s, master’s, and doctorate in mathematics from the University of Oxford Java™ A Beginner’s Guide Sixth Edition Herbert Schildt New York Chicago San Francisco Athens London Madrid Mexico City Milan New Delhi Singapore Sydney Toronto Copyright © 2014 by McGraw-Hill Education (Publisher) All rights reserved Printed in the United States of America Except as permitted under the 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 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-0-07-180926-9 MHID: 0-07-180926-0 e-book conversion by Cenveo® Publisher Services Version 1.0 The material in this e-book also appears in the print version of this title: ISBN: 978-0-07-180925-2, MHID: 0-07-180925-2 McGraw-Hill Education e-books 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 McGraw-Hill Education from sources believed to be reliable However, because of the possibility of human or mechanical error by our sources, McGraw-Hill Education, or others, McGraw-Hill Education 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 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 (“McGraw-Hill”) 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’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 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 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 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 has no responsibility for the content of any information accessed through the work Under no circumstances shall McGraw-Hill 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 at a Glance Java Fundamentals Introducing Data Types and Operators Program Control Statements Introducing Classes, Objects, and Methods More Data Types and Operators A Closer Look at Methods and Classes Inheritance Packages and Interfaces Exception Handling 10 Using I/O 11 Multithreaded Programming 12 Enumerations, Autoboxing, Static Import, and Annotations 13 Generics 14 Lambda Expressions and Method References 15 Applets, Events, and Miscellaneous Topics 16 Introducing Swing 17 Introducing JavaFX A Answers to Self Tests B Using Java’s Documentation Comments Index Contents INTRODUCTION Java Fundamentals The Origins of Java How Java Relates to C and C++ How Java Relates to C# Java’s Contribution to the Internet Java Applets Security Portability Java’s Magic: The Bytecode 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 finalize( ) Method Try This 4-2: Demonstrate Garbage Collection and Finalization 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 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 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 Self Test 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 Self Test 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 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 Self Test 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 Final Thoughts on Packages and Interfaces Chapter Self Test 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 general form of generic and interfaces See also Interface methods lambda expressions to pass executable code to, using native overloading overriding See Overriding, method and parameters See also Parameters parsing passing objects to recursive reference See Method references returning from a returning objects from returning a value from scope defined by signature static super to access hidden superclass, using synchronized and the throws clause and type parameters varargs See Varargs variable-arity MIN_PRIORITY Model-Delegate architecture, Swing Model-View-Controller (MVC) architecture Modulus operator (%) Monitor Mouse and mouse motion events, handling mouseClicked( ) mouseDragged( ) mouseEntered( ) MouseEvent class mouseExited( ) MouseListener interface MouseMotionListener interface mouseMoved( ) mousePressed( ) mouseReleased( ) Multicore systems and the Fork/Join Framework MULTIPLE_INTERVAL_SELECTION MultipleSelectionModel class Multitasking operating system implementation of process-based versus thread-based Multithreaded programming and deadlock and multicore versus single-core systems and synchronization See Synchronization and threads See Thread(s) effective use of MVC (Model-View-Controller) architecture N Name hiding Namespace default (global) packages and static import and Narrowing conversion native modifier Naughton, Patrick Negative numbers, representation of nextX methods, Scanner’s new and abstract classes and type inference NIO (New I/O) system Node class Node(s), JavaFX effects and transforms to alter the look of, using root text NORM_PRIORITY NOT operator bitwise unary (~) Boolean logical unary (!) notify( ) notifyAll( ) null Number class NumberFormatException O Oak Object creating an to a method, passing an monitor returning an Object class and erasure and functional interfaces, public methods of the Object initialization with another object with a constructor Object reference variables and assignment declaring and dynamic method dispatch to a method, effect of passing to superclass reference variables, assigning subclass OBJECT tag, HTML Object-oriented programming (OOP) observableArrayList( ) ObservableList ObservableValue Octal literals One’s complement (bitwise unary NOT) operator Operator(s) ? ternary arithmetic assignment See Assignment operator(s) bitwise diamond (< >) logical parentheses and precedence, table of relational OR operator (|) bitwise Boolean logical OR operator, short-circuit or conditional-or (||) Ordinal value of enumeration constant ordinal( ) out See also System.out standard output stream OutputStream class methods, table of OutputStreamWriter class Overloading constructors methods Overriding, method and dynamic method dispatch final to prevent, using and polymorphism P package statement Package(s) and access control default (global) defining a and directories importing paint( ) Panel class Panes, container PARAM Parameters applets and final lambda and overloaded constructors and overloaded methods type See Type parameter(s) variable-length Parent class parseDouble( ) parseInt( ) Pascal PasswordField JavaFX control PATH environmental variable Peers Pipeline for actions on stream API stream data Pluggable look and feel Pointers Polymorphism and dynamic method dispatch, run-time and interfaces and overloaded methods and overridden methods Portability problem Pos enumeration pow( ) Predicate predefined functional interface print( ) printf( ) println( ) printStackTrace( ) PrintStream class PrintWriter class private access modifier and inheritance and packages Programming art of concurrent multithreaded See Multithreaded programming object-oriented parallel structured protected access modifier in C++ versus Java and packages public access modifier and interfaces and packages Push buttons, JavaFX Push buttons, Swing action command string of Q Queue(s) example program generic, creating a interface, creating a Quicksort algorithm R RandomAccessFile class Raw types read( ) Reader class methods defined by, table of readInt( ) readLine( ) readPassword( ) Recursion Reflection class program demonstrating Relational operators remove( ) removeActionListener( ) removeKeyListener( ) removeTypeListener( ) repaint( ) demonstration program replace( ) resume( ) return statement and block lambdas Root pane Rotate class program demonstrating run( ) overriding using a flag variable with Runnable interface implementing the Run-time exception system, Java type information RuntimeException class S SAM (Single Abstract Method) type Scale class program demonstrating Scanner class Scene class Scene graph Scientific notation Scopes Scroll bars Scroll panes Security problem seek( ) selectedItemProperty( ) Selection statements SelectionMode SelectionModel class Selectors (NIO) Separable model architecture, Swing Servlets setActionCommand( ) setAlignment( ) setAllowIndeterminate( ) setAngle( ) setBottomOpacity( ) setCharAt( ) setDefaultCloseOperation( ) setEffect( ) setFraction( ) setHeight( ) setIterations( ) setLayout( ) setName( ) setOnAction( ) setPivotX( ) setPivotY( ) setPrefColumnCount( ) setPreferredSize( ) setPrefHeight( ) setPrefSize( ) setPrefWidth( ) setPriority( ) setPromptText( ) setRotate( ) setScaleX( ) setScaleY( ) setScene( ) setSelectionMode( ) setSize( ) setText( ) setTitle( ) setTopOffset( ) setTopOpacity( ) setTranslateX( ) setTranslateY( ) setVisible( ) setWidth( ) setX( ) setY( ) Shear class Sheridan, Mike Shift operators, bitwise Short class short data type shortValue( ) show( ) showAll( ) showStatus( ) Signature of a method SINGLE_INTERVAL_SELECTION SINGLE_SELECTION sleep( ) Source delegation event model file Spurious wakeup sqrt( ) Stacks and polymorphism Stage class start( ) Statements null Statements, control iteration jump selection static and generics Static import stop( ) defined by the Applet class defined by the Application class deprecated Thread method Stream interface Stream, stream API Stream(s), I/O definition of the term predefined Streams, byte classes, table of using Streams, character classes, table of using strictfp String class methods, some String(s) arrays of concatenating constructing definition of the term immutability of length, obtaining literals as objects reading representations of numbers into binary format, converting searching switch, used to control a StringBuffer class StringBuilder class Subclass, definition of substring( ) Sun Microsystems super and bounded wildcard arguments default interface method implementation, used to refer to a and superclass members super( ) and superclass constructors and this( ) Superclass, definition of suspend( ) Swing applet example application, example of a simple and the AWT components, table of class names for containers and components, relationship between file comparison utility and JavaFX and MVC architecture programs, event-driven nature of Swing: A Beginner’s Guide SwingUtilities class switch statement using enumeration values in a using a string to control a Synchronization and deadlock race condition and via a synchronized block via a synchronized method synchronized keyword used with a block used with a method Syntax errors System class System.console( ) System.err standard error stream System.in standard input stream System.in.read( ) System.out standard output stream and static import T Templates, C++ Text class Text field, JavaFX Text field, Swing action command string and action listeners TextArea JavaFX control TextField class TextInputControl class this this( ) Thread class constructors extending the Thread(s) application child communication among creating and deadlock definition of the term event-dispatching launcher main possible states of priorities race condition and and spurious wakeup suspending, resuming, and stopping synchronization See Synchronization terminates, determining when a throw Throwable class and chained exceptions and generic classes methods defined by, table of commonly used throws toString( ) toLowerCase( ) toUpperCase( ) Transform class Transforms program demonstrating transient modifier Translate class true True and false in Java try block(s) and finally nested try-with-resources Two’s complement Type argument(s) and bounded types and generic functional interfaces type inference and and type safety See also Wildcard arguments Type inference and constructor references the diamond operator (< >) and and lambda expressions and a method reference to a generic method Type parameter(s) and bounded types and erasure instance of a, cannot create an and primitive types and static members used with a class used with a method Type safety and generics and raw types and wildcard arguments Type(s) bounded casting checking class as a data conversion, automatic inference See Type inference information, run-time numeric, default value of promotion in expressions raw reference, default value of simple or elemental Type(s), primitive and binary I/O table of and type parameters wrappers Types, parameterized versus C++ templates U UI delegate UnaryOperator predefined functional interface Unboxing See also Autoboxing/unboxing Unchecked warnings and raw types Underscores with integer and floating-point literals, using Unicode update( ) V valueChanged( ) valueOf( ) values( ) Varargs and ambiguity methods, overloading parameter, declaring a Variable(s) capture character declaration definition of the term dynamic initialization of effectively final enumeration final initializing instance See Instance variables interface interface reference name hiding and object reference See Object reference variables scope and lifetime of static transient volatile Virtual functions (C++) void methods volatile modifier W wait( ) Warth, Chris Web browser executing applet in using status window of while loop Widening conversion Wildcard arguments bounded Window, using the applet viewer or browser status WindowConstants interface World Wide Web Wrappers, primitive type write( ) Writer class methods defined by, table of writeDouble( ) X XOR (exclusive OR) operator (^) bitwise Boolean logical

Ngày đăng: 12/05/2017, 10:41

Từ khóa liên quan

Mục lục

  • INTRODUCTION

  • 1   Java Fundamentals

  • The Origins of Java

  • How Java Relates to C and C++

  • How Java Relates to C#

  • Java’s Contribution to the Internet

  • Java Applets

  • Security

  • Portability

  • Java’s Magic: The Bytecode

  • 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

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan