Home Page Icon
Home Page
Table of Contents for
Contents
Close
Contents
by Herbert Schildt
Java The Complete Reference, 9th Edition
Cover
About the Author
About the Technical Editor
Title Page
Copyright Page
Contents at a Glance
Contents
Preface
A Book for All Programmers
What’s Inside
Don’t Forget: Code on the Web
Special Thanks
For Further Study
Part I: The Java Language
Chapter 1: The History and Evolution of Java
Java’s Lineage
The Birth of Modern Programming: C
C++: The Next Step
The Stage Is Set for Java
The Creation of Java
The C# Connection
How Java Changed the Internet
Java Applets
Security
Portability
Java’s Magic: The Bytecode
Servlets: Java on the Server Side
The Java Buzzwords
Simple
Object-Oriented
Robust
Multithreaded
Architecture-Neutral
Interpreted and High Performance
Distributed
Dynamic
The Evolution of Java
Java SE 8
A Culture of Innovation
Chapter 2: An Overview of Java
Object-Oriented Programming
Two Paradigms
Abstraction
The Three OOP Principles
A First Simple Program
Entering the Program
Compiling the Program
A Closer Look at the First Sample Program
A Second Short Program
Two Control Statements
The if Statement
The for Loop
Using Blocks of Code
Lexical Issues
Whitespace
Identifiers
Literals
Comments
Separators
The Java Keywords
The Java Class Libraries
Chapter 3: Data Types, Variables, and Arrays
Java Is a Strongly Typed Language
The Primitive Types
Integers
byte
short
int
long
Floating-Point Types
float
double
Characters
Booleans
A Closer Look at Literals
Integer Literals
Floating-Point Literals
Boolean Literals
Character Literals
String Literals
Variables
Declaring a Variable
Dynamic Initialization
The Scope and Lifetime of Variables
Type Conversion and Casting
Java’s Automatic Conversions
Casting Incompatible Types
Automatic Type Promotion in Expressions
The Type Promotion Rules
Arrays
One-Dimensional Arrays
Multidimensional Arrays
Alternative Array Declaration Syntax
A Few Words About Strings
A Note to C/C++ Programmers About Pointers
Chapter 4: Operators
Arithmetic Operators
The Basic Arithmetic Operators
The Modulus Operator
Arithmetic Compound Assignment Operators
Increment and Decrement
The Bitwise Operators
The Bitwise Logical Operators
The Left Shift
The Right Shift
The Unsigned Right Shift
Bitwise Operator Compound Assignments
Relational Operators
Boolean Logical Operators
Short-Circuit Logical Operators
The Assignment Operator
The ? Operator
Operator Precedence
Using Parentheses
Chapter 5: Control Statements
Java’s Selection Statements
if
switch
Iteration Statements
while
do-while
for
The For-Each Version of the for Loop
Nested Loops
Jump Statements
Using break
Using continue
Chapter 6: Introducing Classes
Class Fundamentals
The General Form of a Class
A Simple Class
Declaring Objects
A Closer Look at new
Assigning Object Reference Variables
Introducing Methods
Adding a Method to the Box Class
Returning a Value
Adding a Method That Takes Parameters
Constructors
Parameterized Constructors
The this Keyword
Instance Variable Hiding
Garbage Collection
The finalize( ) Method
A Stack Class
Chapter 7: A Closer Look at Methods and Classes
Overloading Methods
Overloading Constructors
Using Objects as Parameters
A Closer Look at Argument Passing
Returning Objects
Recursion
Introducing Access Control
Understanding static
Introducing final
Arrays Revisited
Introducing Nested and Inner Classes
Exploring the String Class
Using Command-Line Arguments
Varargs: Variable-Length Arguments
Overloading Vararg Methods
Varargs and Ambiguity
Chapter 8: Inheritance
Inheritance Basics
Member Access and Inheritance
A More Practical Example
A Superclass Variable Can Reference a Subclass Object
Using super
Using super to Call Superclass Constructors
A Second Use for super
Creating a Multilevel Hierarchy
When Constructors Are Executed
Method Overriding
Dynamic Method Dispatch
Why Overridden Methods?
Applying Method Overriding
Using Abstract Classes
Using final with Inheritance
Using final to Prevent Overriding
Using final to Prevent Inheritance
The Object Class
Chapter 9: Packages and Interfaces
Packages
Defining a Package
Finding Packages and CLASSPATH
A Short Package Example
Access Protection
An Access Example
Importing Packages
Interfaces
Defining an Inter face
Implementing Interfaces
Nested Interfaces
Applying Interfaces
Variables in Interfaces
Interfaces Can Be Extended
Default Interface Methods
Default Method Fundamentals
A More Practical Example
Multiple Inheritance Issues
Use static Methods in an Interface
Final Thoughts on Packages and Interfaces
Chapter 10: Exception Handling
Exception-Handling Fundamentals
Exception Types
Uncaught Exceptions
Using try and catch
Displaying a Description of an Exception
Multiple catch Clauses
Nested try Statements
throw
throws
finally
Java’s Built-in Exceptions
Creating Your Own Exception Subclasses
Chained Exceptions
Three Recently Added Exception Features
Using Exceptions
Chapter 11: Multithreaded Programming
The Java Thread Model
Thread Priorities
Synchronization
Messaging
The Thread Class and the Runnable Interface
The Main Thread
Creating a Thread
Implementing Runnable
Extending Thread
Choosing an Approach
Creating Multiple Threads
Using isAlive( ) and join( )
Thread Priorities
Synchronization
Using Synchronized Methods
The synchronized Statement
Interthread Communication
Deadlock
Suspending, Resuming, and Stopping Threads
Obtaining A Thread’s State
Using Multithreading
Chapter 12: Enumerations, Autoboxing, and Annotations (Metadata)
Enumerations
Enumeration Fundamentals
The values( ) and valueOf( ) Methods
Java Enumerations Are Class Types
Enumerations Inherit Enum
Another Enumeration Example
Type Wrappers
Character
Boolean
The Numeric Type Wrappers
Autoboxing
Autoboxing and Methods
Autoboxing/Unboxing Occurs in Expressions
Autoboxing/Unboxing Boolean and Character Values
Autoboxing/Unboxing Helps Prevent Errors
A Word of Warning
Annotations (Metadata)
Annotation Basics
Specifying a Retention Policy
Obtaining Annotations at Run Time by Use of Reflection
The AnnotatedElement Interface
Using Default Values
Marker Annotations
Single-Member Annotations
The Built-In Annotations
Type Annotations
Repeating Annotations
Some Restrictions
Chapter 13: I/O, Applets, and Other Topics
I/O Basics
Streams
Byte Streams and Character Streams
The Predefined Streams
Reading Console Input
Reading Characters
Reading Strings
Writing Console Output
The PrintWriter Class
Reading and Writing Files
Automatically Closing a File
Applet Fundamentals
The transient and volatile Modifiers
Using instanceof
strictfp
Native Methods
Problems with Native Methods
Using assert
Assertion Enabling and Disabling Options
Static Import
Invoking Overloaded Constructors Through this( )
Compact API Profiles
Chapter 14: Generics
What Are Generics?
A Simple Generics Example
Generics Work Only with Reference Types
Generic Types Differ Based on Their Type Arguments
How Generics Improve Type Safety
A Generic Class with Two Type Parameters
The General Form of a Generic Class
Bounded Types
Using Wildcard Arguments
Bounded Wildcards
Creating a Generic Method
Generic Constructors
Generic Interfaces
Raw Types and Legacy Code
Generic Class Hierarchies
Using a Generic Superclass
A Generic Subclass
Run-Time Type Comparisons Within a Generic Hierarchy
Casting
Overriding Methods in a Generic Class
Type Inference with Generics
Erasure
Bridge Methods
Ambiguity Errors
Some Generic Restrictions
Type Parameters Can’t Be Instantiated
Restrictions on Static Members
Generic Array Restrictions
Generic Exception Restriction
Chapter 15: Lambda Expressions
Introducing Lambda Expressions
Lambda Expression Fundamentals
Functional Interfaces
Some Lambda Expression Examples
Block Lambda Expressions
Generic Functional Interfaces
Passing Lambda Expressions as Arguments
Lambda Expressions and Exceptions
Lambda Expressions and Variable Capture
Method References
Method References to static Methods
Method References to Instance Methods
Method References with Generics
Constructor References
Predefined Functional Interfaces
Part II: The Java Library
Chapter 16: String Handling
The String Constructors
String Length
Special String Operations
String Literals
String Concatenation
String Concatenation with Other Data Types
String Conversion and toString( )
Character Extraction
charAt( )
getChars( )
getBytes( )
toCharArray( )
String Comparison
equals( ) and equalsIgnoreCase( )
regionMatches( )
startsWith( ) and endsWith( )
equals( ) Versus ==
compareTo( )
Searching Strings
Modifying a String
substring( )
concat( )
replace( )
trim( )
Data Conversion Using valueOf( )
Changing the Case of Characters Within a String
Joining Strings
Additional String Methods
StringBuffer
StringBuffer Constructors
length( ) and capacity( )
ensureCapacity( )
setLength( )
charAt( ) and setCharAt( )
getChars( )
append( )
insert( )
reverse( )
delete( ) and deleteCharAt( )
replace( )
substring( )
Additional StringBuffer Methods
StringBuilder
Chapter 17: Exploring java.lang
Primitive Type Wrappers
Number
Double and Float
Understanding isInfinite( ) and isNaN( )
Byte, Short, Integer, and Long
Character
Additions to Character for Unicode Code Point Support
Boolean
Void
Process
Runtime
Memory Management
Executing Other Programs
ProcessBuilder
System
Using currentTimeMillis( ) to Time Program Execution.
Using arraycopy( )
Environment Properties
Object
Using clone( ) and the Cloneable Interface
Class
ClassLoader
Math
Trigonometric Functions
Exponential Functions
Rounding Functions
Miscellaneous Math Methods
StrictMath
Compiler
Thread, ThreadGroup, and Runnable
The Runnable Interface
Thread
ThreadGroup
ThreadLocal and InheritableThreadLocal
Package
RuntimePermission
Throwable
SecurityManager
StackTraceElement
Enum
ClassValue
The CharSequence Interface
The Comparable Interface
The Appendable Interface
The Iterable Interface
The Readable Interface
The AutoCloseable Interface
The Thread.UncaughtExceptionHandler Interface
The java.lang Subpackages
java.lang.annotation
java.lang.instrument
java.lang.invoke
java.lang.management
java.lang.ref
java.lang.reflect
Chapter 18: java.util Part 1: The Collections Framework
Collections Overview
JDK 5 Changed the Collections Framework
Generics Fundamentally Changed the Collections Framework
Autoboxing Facilitates the Use of Primitive Types
The For-Each Style for Loop
The Collection Interfaces
The Collection Interface
The List Interface
The Set Interface
The SortedSet Interface
The NavigableSet Interface
The Queue Interface
The Deque Interface
The Collection Classes
The ArrayList Class
The LinkedList Class
The HashSet Class
The LinkedHashSet Class
The TreeSet Class
The PriorityQueue Class
The ArrayDeque Class
The EnumSet Class
Accessing a Collection via an Iterator
Using an Iterator
The For-Each Alternative to Iterators
Spliterators
Storing User-Defined Classes in Collections
The RandomAccess Interface
Working with Maps
The Map Interfaces
The Map Classes
Comparators
Using a Comparator
The Collection Algorithms
Arrays
The Legacy Classes and Interfaces
The Enumeration Interface
Vector
Stack
Dictionary
Hashtable
Properties
Using store( ) and load( )
Parting Thoughts on Collections
Chapter 19: java.util Part 2: More Utility Classes
StringTokenizer
BitSet
Optional, OptionalDouble, OptionalInt, and OptionalLong
Date
Calendar
GregorianCalendar
TimeZone
SimpleTimeZone
Locale
Random
Observable
The Observer Interface
An Observer Example
Timer and TimerTask
Currency
Formatter
The Formatter Constructors
The Formatter Methods
Formatting Basics
Formatting Strings and Characters
Formatting Numbers
Formatting Time and Date
The %n and %% Specifiers
Specifying a Minimum Field Width
Specifying Precision
Using the Format Flags
Justifying Output
The Space, +, 0, and ( Flags
The Comma Flag
The # Flag
The Uppercase Option
Using an Argument Index
Closing a Formatter
The Java printf( ) Connection
Scanner
The Scanner Constructors
Scanning Basics
Some Scanner Examples
Setting Delimiters
Other Scanner Features
The ResourceBundle, ListResourceBundle, and PropertyResourceBundle Classes
Miscellaneous Utility Classes and Interfaces
The java.util Subpackages
java.util.concurrent, java.util.concurrent.atomic, and java.util.concurrent.locks
java.util.function
java.util.jar
java.util.logging
java.util.prefs
java.util.regex
java.util.spi
java.util.stream
java.util.zip
Chapter 20: Input/Output: Exploring java.io
The I/O Classes and Interfaces
File
Directories
Using FilenameFilter
The listFiles( ) Alternative
Creating Directories
The AutoCloseable, Closeable, and Flushable Interfaces
I/O Exceptions
Two Ways to Close a Stream
The Stream Classes
The Byte Streams
InputStream
OutputStream
FileInputStream
FileOutputStream
ByteArrayInputStream
ByteArrayOutputStream
Filtered Byte Streams
Buffered Byte Streams
SequenceInputStream
PrintStream
DataOutputStream and DataInputStream
RandomAccessFile
The Character Streams
Reader
Writer
FileReader
FileWriter
CharArrayReader
CharArrayWriter
BufferedReader
BufferedWriter
PushbackReader
PrintWriter
The Console Class
Serialization
Serializable
Externalizable
ObjectOutput
ObjectOutputStream
ObjectInput
ObjectInputStream
A Serialization Example
Stream Benefits
Chapter 21: Exploring NIO
The NIO Classes
NIO Fundamentals
Buffers
Channels
Charsets and Selectors
Enhancements Added to NIO by JDK 7
The Path Interface
The Files Class
The Paths Class
The File Attribute Interfaces
The FileSystem, FileSystems, and FileStore Classes
Using the NIO System
Use NIO for Channel-Based I/O
Use NIO for Stream-Based I/O
Use NIO for Path and File System Operations
Pre-JDK 7 Channel-Based Examples
Read a File, Pre-JDK 7
Write to a File, Pre-JDK 7
Chapter 22: Networking
Networking Basics
The Networking Classes and Interfaces
InetAddress
Factory Methods
Instance Methods
Inet4Address and Inet6Address
TCP/IP Client Sockets
URL
URLConnection
HttpURLConnection
The URI Class
Cookies
TCP/IP Server Sockets
Datagrams
DatagramSocket
DatagramPacket
A Datagram Example
Chapter 23: The Applet Class
Two Types of Applets
Applet Basics
The Applet Class
Applet Architecture
An Applet Skeleton
Applet Initialization and Termination
Overriding update( )
Simple Applet Display Methods
Requesting Repainting
A Simple Banner Applet
Using the Status Window
The HTML APPLET Tag
Passing Parameters to Applets
Improving the Banner Applet
getDocumentBase( ) and getCodeBase( )
AppletContext and showDocument( )
The AudioClip Interface
The AppletStub Interface
Outputting to the Console
Chapter 24: Event Handling
Two Event Handling Mechanisms
The Delegation Event Model
Events
Event Sources
Event Listeners
Event Classes
The ActionEvent Class
The AdjustmentEvent Class
The ComponentEvent Class
The ContainerEvent Class
The FocusEvent Class
The InputEvent Class
The ItemEvent Class
The KeyEvent Class
The MouseEvent Class
The MouseWheelEvent Class
The TextEvent Class
The WindowEvent Class
Sources of Events
Event Listener Interfaces
The ActionListener Interface
The AdjustmentListener Interface
The ComponentListener Interface
The ContainerListener Interface
The FocusListener Interface
The ItemListener Interface
The KeyListener Interface
The MouseListener Interface
The MouseMotionListener Interface
The MouseWheelListener Interface
The TextListener Interface
The WindowFocusListener Interface
The WindowListener Interface
Using the Delegation Event Model
Handling Mouse Events
Handling Keyboard Events
Adapter Classes
Inner Classes
Anonymous Inner Classes
Chapter 25: Introducing the AWT: Working with Windows, Graphics, and Text
AWT Classes
Window Fundamentals
Component
Container
Panel
Window
Frame
Canvas
Working with Frame Windows
Setting the Window’s Dimensions
Hiding and Showing a Window
Setting a Window’s Title
Closing a Frame Window
Creating a Frame Window in an AWT-Based Applet
Handling Events in a Frame Window
Creating a Windowed Program
Displaying Information Within a Window
Introducing Graphics
Drawing Lines
Drawing Rectangles
Drawing Ellipses and Circles
Drawing Arcs
Drawing Polygons
Demonstrating the Drawing Methods
Sizing Graphics
Working with Color
Color Methods
Setting the Current Graphics Color
A Color Demonstration Applet
Setting the Paint Mode
Working with Fonts
Determining the Available Fonts
Creating and Selecting a Font
Obtaining Font Information
Managing Text Output Using FontMetrics
Displaying Multiple Lines of Text
Centering Text
Multiline Text Alignment
Chapter 26: Using AWT Controls, Layout Managers, and Menus
AWT Control Fundamentals
Adding and Removing Controls
Responding to Controls
The HeadlessException
Labels
Using Buttons
Handling Buttons
Applying Check Boxes
Handling Check Boxes
CheckboxGroup
Choice Controls
Handling Choice Lists
Using Lists
Handling Lists
Managing Scroll Bars
Handling Scroll Bars
Using a TextField
Handling a TextField
Using a TextArea
Understanding Layout Managers
FlowLayout
BorderLayout
Using Insets
GridLayout
CardLayout
GridBagLayout
Menu Bars and Menus
Dialog Boxes
FileDialog
A Word About Overriding paint( )
Chapter 27: Images
File Formats
Image Fundamentals: Creating, Loading, and Displaying
Creating an Image Object
Loading an Image
Displaying an Image
ImageObserver
Double Buffering
MediaTracker
ImageProducer
MemoryImageSource
ImageConsumer
PixelGrabber
ImageFilter
CropImageFilter
RGBImageFilter
Additional Imaging Classes
Chapter 28: The Concurrency Utilities
The Concurrent API Packages
java.util.concurrent
java.util.concurrent.atomic
java.util.concurrent.locks
Using Synchronization Objects
Semaphore
CountDownLatch
CyclicBarrier
Exchanger
Phaser
Using an Executor
A Simple Executor Example
Using Callable and Future
The TimeUnit Enumeration
The Concurrent Collections
Locks
Atomic Operations
Parallel Programming via the Fork/Join Framework
The Main Fork/Join Classes
The Divide-and-Conquer Strategy
A Simple First Fork/Join Example
Understanding the Impact of the Level of Parallelism
An Example that Uses RecursiveTask<V>
Executing a Task Asynchronously
Cancelling a Task
Determining a Task’s Completion Status
Restarting a Task
Things to Explore
Some Fork/Join Tips
The Concurrency Utilities Versus Java’s Traditional Approach
Chapter 29: The Stream API
Stream Basics
Stream Interfaces
How to Obtain a Stream
A Simple Stream Example
Reduction Operations
Using Parallel Streams
Mapping
Collecting
Iterators and Streams
Use an Iterator with a Stream
Use Spliterator
More to Explore in the Stream API
Chapter 30: Regular Expressions and Other Packages
The Core Java API Packages
Regular Expression Processing
Pattern
Matcher
Regular Expression Syntax
Demonstrating Pattern Matching
Two Pattern-Matching Options
Exploring Regular Expressions
Reflection
Remote Method Invocation (RMI)
A Simple Client/Server Application Using RMI
Formatting Date and Time with java.text
DateFormat Class
SimpleDateFormat Class
The Time and Date API Added by JDK 8
Time and Date Fundamentals
Formatting Date and Time
Parsing Date and Time Strings
Other Things to Explore in java.time
Part III: Introducing GUI Programming with Swing
Chapter 31: Introducing Swing
The Origins of Swing
Swing Is Built on the AWT
Two Key Swing Features
Swing Components Are Lightweight
Swing Supports a Pluggable Look and Feel
The MVC Connection
Components and Containers
Components
Containers
The Top-Level Container Panes
The Swing Packages
A Simple Swing Application
Event Handling
Create a Swing Applet
Painting in Swing
Painting Fundamentals
Compute the Paintable Area
A Paint Example
Chapter 32: Exploring Swing
JLabel and ImageIcon
JTextField
The Swing Buttons
JButton
JToggleButton
Check Boxes
Radio Buttons
JTabbedPane
JScrollPane
JList
JComboBox
Trees
JTable
Chapter 33: Introducing Swing Menus
Menu Basics
An Overview of JMenuBar, JMenu, and JMenuItem
JMenuBar
JMenu
JMenuItem
Create a Main Menu
Add Mnemonics and Accelerators to Menu Items
Add Images and Tooltips to Menu Items
Use JRadioButtonMenuItem and JCheckBoxMenuItem
Create a Popup Menu
Create a Toolbar
Use Actions
Put the Entire MenuDemo Program Together
Continuing Your Exploration of Swing
Part IV: Introducing GUI Programming with JavaFX
Chapter 34: Introducing JavaFX GUI Programming
JavaFX Basic Concepts
The JavaFX Packages
The Stage and Scene Classes
Nodes and Scene Graphs
Layouts
The Application Class and the Lifecycle Methods
Launching a JavaFX Application
A JavaFX Application Skeleton
Compiling and Running a JavaFX Program
The Application Thread
A Simple JavaFX Control: Label
Using Buttons and Events
Event Basics
Introducing the Button Control
Demonstrating Event Handling and the Button
Drawing Directly on a Canvas
Chapter 35: Exploring JavaFX Controls
Using Image and ImageView
Adding an Image to a Label
Using an Image with a Button
ToggleButton
RadioButton
Handling Change Events in a Toggle Group
An Alternative Way to Handle Radio Buttons
CheckBox
ListView
ListView Scrollbars
Enabling Multiple Selections
ComboBox
TextField
ScrollPane
TreeView
Introducing Effects and Transforms
Effects
Transforms
Demonstrating Effects and Transforms
Adding Tooltips
Disabling a Control
Chapter 36: Introducing JavaFX Menus
Menu Basics
An Overview of MenuBar, Menu, and MenuItem
MenuBar
Menu
MenuItem
Create a Main Menu
Add Mnemonics and Accelerators to Menu Items
Add Images to Menu Items
Use RadioMenuItem and CheckMenuItem
Create a Context Menu
Create a Toolbar
Put the Entire MenuDemo Program Together
Continuing Your Exploration of JavaFX
Part V: Applying Java
Chapter 37: Java Beans
What Is a Java Bean?
Advantages of Java Beans
Introspection
Design Patterns for Properties
Design Patterns for Events
Methods and Design Patterns
Using the BeanInfo Interface
Bound and Constrained Properties
Persistence
Customizers
The Java Beans API
Introspector
PropertyDescriptor
EventSetDescriptor
MethodDescriptor
A Bean Example
Chapter 38: Introducing Servlets
Background
The Life Cycle of a Servlet
Servlet Development Options
Using Tomcat
A Simple Servlet
Create and Compile the Servlet Source Code
Start Tomcat
Start a Web Browser and Request the Servlet
The Servlet API
The javax.servlet Package
The Servlet Interface
The ServletConfg Interface
The ServletContext Interface
The ServletRequest Interface
The ServletResponse Interface
The GenericServlet Class
The ServletInputStream Class
The ServletOutputStream Class
The Servlet Exception Classes
Reading Servlet Parameters
The javax.servlet.http Package
The HttpServletRequest Interface
The HttpServletResponse Interface
The HttpSession Interface
The Cookie Class
The HttpServlet Class
Handling HTTP Requests and Responses
Handling HTTP GET Requests
Handling HTTP POST Requests
Using Cookies
Session Tracking
Appendix: Using Java’s Documentation Comments
The javadoc Tags
@author
{@code}
@deprecated
{@docRoot}
@exception
{@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
Search in book...
Toggle Font Controls
Playlists
Add To
Create new playlist
Name your new playlist
Playlist description (optional)
Cancel
Create playlist
Sign In
Email address
Password
Forgot Password?
Create account
Login
or
Continue with Facebook
Continue with Google
Sign Up
Full Name
Email address
Confirm Email Address
Password
Login
Create account
or
Continue with Facebook
Continue with Google
Prev
Previous Chapter
Contents at a Glance
Next
Next Chapter
Preface
Contents
Preface
Part I
The Java Language
Chapter 1 The History and Evolution of Java
Java’s Lineage
The Birth of Modern Programming: C
C++: The Next Step
The Stage Is Set for Java
The Creation of Java
The C# Connection
How Java Changed the Internet
Java Applets
Security
Portability
Java’s Magic: The Bytecode
Servlets: Java on the Server Side
The Java Buzzwords
Simple
Object-Oriented
Robust
Multithreaded
Architecture-Neutral
Interpreted and High Performance
Distributed
Dynamic
The Evolution of Java
Java SE 8
A Culture of Innovation
Chapter 2 An Overview of Java
Object-Oriented Programming
Two Paradigms
Abstraction
The Three OOP Principles
A First Simple Program
Entering the Program
Compiling the Program
A Closer Look at the First Sample Program
A Second Short Program
Two Control Statements
The if Statement
The for Loop
Using Blocks of Code
Lexical Issues
Whitespace
Identifiers
Literals
Comments
Separators
The Java Keywords
The Java Class Libraries
Chapter 3 Data Types, Variables, and Arrays
Java Is a Strongly Typed Language
The Primitive Types
Integers
byte
short
int
long
Floating-Point Types
float
double
Characters
Booleans
A Closer Look at Literals
Integer Literals
Floating-Point Literals
Boolean Literals
Character Literals
String Literals
Variables
Declaring a Variable
Dynamic Initialization
The Scope and Lifetime of Variables
Type Conversion and Casting
Java’s Automatic Conversions
Casting Incompatible Types
Automatic Type Promotion in Expressions
The Type Promotion Rules
Arrays
One-Dimensional Arrays
Multidimensional Arrays
Alternative Array Declaration Syntax
A Few Words About Strings
A Note to C/C++ Programmers About Pointers
Chapter 4 Operators
Arithmetic Operators
The Basic Arithmetic Operators
The Modulus Operator
Arithmetic Compound Assignment Operators
Increment and Decrement
The Bitwise Operators
The Bitwise Logical Operators
The Left Shift
The Right Shift
The Unsigned Right Shift
Bitwise Operator Compound Assignments
Relational Operators
Boolean Logical Operators
Short-Circuit Logical Operators
The Assignment Operator
The ? Operator
Operator Precedence
Using Parentheses
Chapter 5 Control Statements
Java’s Selection Statements
if
switch
Iteration Statements
while
do-while
for
The For-Each Version of the for Loop
Nested Loops
Jump Statements
Using break
Using continue
Chapter 6 Introducing Classes
Class Fundamentals
The General Form of a Class
A Simple Class
Declaring Objects
A Closer Look at new
Assigning Object Reference Variables
Introducing Methods
Adding a Method to the Box Class
Returning a Value
Adding a Method That Takes Parameters
Constructors
Parameterized Constructors
The this Keyword
Instance Variable Hiding
Garbage Collection
The finalize( ) Method
A Stack Class
Chapter 7 A Closer Look at Methods and Classes
Overloading Methods
Overloading Constructors
Using Objects as Parameters
A Closer Look at Argument Passing
Returning Objects
Recursion
Introducing Access Control
Understanding static
Introducing final
Arrays Revisited
Introducing Nested and Inner Classes
Exploring the String Class
Using Command-Line Arguments
Varargs: Variable-Length Arguments
Overloading Vararg Methods
Varargs and Ambiguity
Chapter 8 Inheritance
Inheritance Basics
Member Access and Inheritance
A More Practical Example
A Superclass Variable Can Reference a Subclass Object
Using super
Using super to Call Superclass Constructors
A Second Use for super
Creating a Multilevel Hierarchy
When Constructors Are Executed
Method Overriding
Dynamic Method Dispatch
Why Overridden Methods?
Applying Method Overriding
Using Abstract Classes
Using final with Inheritance
Using final to Prevent Overriding
Using final to Prevent Inheritance
The Object Class
Chapter 9 Packages and Interfaces
Packages
Defining a Package
Finding Packages and CLASSPATH
A Short Package Example
Access Protection
An Access Example
Importing Packages
Interfaces
Defining an Inter face
Implementing Interfaces
Nested Interfaces
Applying Interfaces
Variables in Interfaces
Interfaces Can Be Extended
Default Interface Methods
Default Method Fundamentals
A More Practical Example
Multiple Inheritance Issues
Use static Methods in an Interface
Final Thoughts on Packages and Interfaces
Chapter 10 Exception Handling
Exception-Handling Fundamentals
Exception Types
Uncaught Exceptions
Using try and catch
Displaying a Description of an Exception
Multiple catch Clauses
Nested try Statements
throw
throws
finally
Java’s Built-in Exceptions
Creating Your Own Exception Subclasses
Chained Exceptions
Three Recently Added Exception Features
Using Exceptions
Chapter 11 Multithreaded Programming
The Java Thread Model
Thread Priorities
Synchronization
Messaging
The Thread Class and the Runnable Interface
The Main Thread
Creating a Thread
Implementing Runnable
Extending Thread
Choosing an Approach
Creating Multiple Threads
Using isAlive( ) and join( )
Thread Priorities
Synchronization
Using Synchronized Methods
The synchronized Statement
Interthread Communication
Deadlock
Suspending, Resuming, and Stopping Threads
Obtaining A Thread’s State
Using Multithreading
Chapter 12 Enumerations, Autoboxing, and Annotations (Metadata)
Enumerations
Enumeration Fundamentals
The values( ) and valueOf( ) Methods
Java Enumerations Are Class Types
Enumerations Inherit Enum
Another Enumeration Example
Type Wrappers
Character
Boolean
The Numeric Type Wrappers
Autoboxing
Autoboxing and Methods
Autoboxing/Unboxing Occurs in Expressions
Autoboxing/Unboxing Boolean and Character Values
Autoboxing/Unboxing Helps Prevent Errors
A Word of Warning
Annotations (Metadata)
Annotation Basics
Specifying a Retention Policy
Obtaining Annotations at Run Time by Use of Reflection
The AnnotatedElement Interface
Using Default Values
Marker Annotations
Single-Member Annotations
The Built-In Annotations
Type Annotations
Repeating Annotations
Some Restrictions
Chapter 13 I/O, Applets, and Other Topics
I/O Basics
Streams
Byte Streams and Character Streams
The Predefined Streams
Reading Console Input
Reading Characters
Reading Strings
Writing Console Output
The PrintWriter Class
Reading and Writing Files
Automatically Closing a File
Applet Fundamentals
The transient and volatile Modifiers
Using instanceof
strictfp
Native Methods
Problems with Native Methods
Using assert
Assertion Enabling and Disabling Options
Static Import
Invoking Overloaded Constructors Through this( )
Compact API Profiles
Chapter 14 Generics
What Are Generics?
A Simple Generics Example
Generics Work Only with Reference Types
Generic Types Differ Based on Their Type Arguments
How Generics Improve Type Safety
A Generic Class with Two Type Parameters
The General Form of a Generic Class
Bounded Types
Using Wildcard Arguments
Bounded Wildcards
Creating a Generic Method
Generic Constructors
Generic Interfaces
Raw Types and Legacy Code
Generic Class Hierarchies
Using a Generic Superclass
A Generic Subclass
Run-Time Type Comparisons Within a Generic Hierarchy
Casting
Overriding Methods in a Generic Class
Type Inference with Generics
Erasure
Bridge Methods
Ambiguity Errors
Some Generic Restrictions
Type Parameters Can’t Be Instantiated
Restrictions on Static Members
Generic Array Restrictions
Generic Exception Restriction
Chapter 15 Lambda Expressions
Introducing Lambda Expressions
Lambda Expression Fundamentals
Functional Interfaces
Some Lambda Expression Examples
Block Lambda Expressions
Generic Functional Interfaces
Passing Lambda Expressions as Arguments
Lambda Expressions and Exceptions
Lambda Expressions and Variable Capture
Method References
Method References to static Methods
Method References to Instance Methods
Method References with Generics
Constructor References
Predefined Functional Interfaces
Part II
The Java Library
Chapter 16 String Handling
The String Constructors
String Length
Special String Operations
String Literals
String Concatenation
String Concatenation with Other Data Types
String Conversion and toString( )
Character Extraction
charAt( )
getChars( )
getBytes( )
toCharArray( )
String Comparison
equals( ) and equalsIgnoreCase( )
regionMatches( )
startsWith( ) and endsWith( )
equals( ) Versus ==
compareTo( )
Searching Strings
Modifying a String
substring( )
concat( )
replace( )
trim( )
Data Conversion Using valueOf( )
Changing the Case of Characters Within a String
Joining Strings
Additional String Methods
StringBuffer
StringBuffer Constructors
length( ) and capacity( )
ensureCapacity( )
setLength( )
charAt( ) and setCharAt( )
getChars( )
append( )
insert( )
reverse( )
delete( ) and deleteCharAt( )
replace( )
substring( )
Additional StringBuffer Methods
StringBuilder
Chapter 17 Exploring java.lang
Primitive Type Wrappers
Number
Double and Float
Understanding isInfinite( ) and isNaN( )
Byte, Short, Integer, and Long
Character
Additions to Character for Unicode Code Point Support
Boolean
Void
Process
Runtime
Memory Management
Executing Other Programs
ProcessBuilder
System
Using currentTimeMillis( ) to Time Program Execution.
Using arraycopy( )
Environment Properties
Object
Using clone( ) and the Cloneable Interface
Class
ClassLoader
Math
Trigonometric Functions
Exponential Functions
Rounding Functions
Miscellaneous Math Methods
StrictMath
Compiler
Thread, ThreadGroup, and Runnable
The Runnable Interface
Thread
ThreadGroup
ThreadLocal and InheritableThreadLocal
Package
RuntimePermission
Throwable
SecurityManager
StackTraceElement
Enum
ClassValue
The CharSequence Interface
The Comparable Interface
The Appendable Interface
The Iterable Interface
The Readable Interface
The AutoCloseable Interface
The Thread.UncaughtExceptionHandler Interface
The java.lang Subpackages
java.lang.annotation
java.lang.instrument
java.lang.invoke
java.lang.management
java.lang.ref
java.lang.reflect
Chapter 18 java.util Part 1: The Collections Framework
Collections Overview
JDK 5 Changed the Collections Framework
Generics Fundamentally Changed the Collections Framework
Autoboxing Facilitates the Use of Primitive Types
The For-Each Style for Loop
The Collection Interfaces
The Collection Interface
The List Interface
The Set Interface
The SortedSet Interface
The NavigableSet Interface
The Queue Interface
The Deque Interface
The Collection Classes
The ArrayList Class
The LinkedList Class
The HashSet Class
The LinkedHashSet Class
The TreeSet Class
The PriorityQueue Class
The ArrayDeque Class
The EnumSet Class
Accessing a Collection via an Iterator
Using an Iterator
The For-Each Alternative to Iterators
Spliterators
Storing User-Defined Classes in Collections
The RandomAccess Interface
Working with Maps
The Map Interfaces
The Map Classes
Comparators
Using a Comparator
The Collection Algorithms
Arrays
The Legacy Classes and Interfaces
The Enumeration Interface
Vector
Stack
Dictionary
Hashtable
Properties
Using store( ) and load( )
Parting Thoughts on Collections
Chapter 19 java.util Part 2: More Utility Classes
StringTokenizer
BitSet
Optional, OptionalDouble, OptionalInt, and OptionalLong
Date
Calendar
GregorianCalendar
TimeZone
SimpleTimeZone
Locale
Random
Observable
The Observer Interface
An Observer Example
Timer and TimerTask
Currency
Formatter
The Formatter Constructors
The Formatter Methods
Formatting Basics
Formatting Strings and Characters
Formatting Numbers
Formatting Time and Date
The %n and %% Specifiers
Specifying a Minimum Field Width
Specifying Precision
Using the Format Flags
Justifying Output
The Space, +, 0, and ( Flags
The Comma Flag
The # Flag
The Uppercase Option
Using an Argument Index
Closing a Formatter
The Java printf( ) Connection
Scanner
The Scanner Constructors
Scanning Basics
Some Scanner Examples
Setting Delimiters
Other Scanner Features
The ResourceBundle, ListResourceBundle, and PropertyResourceBundle Classes
Miscellaneous Utility Classes and Interfaces
The java.util Subpackages
java.util.concurrent, java.util.concurrent.atomic, and java.util.concurrent.locks
java.util.function
java.util.jar
java.util.logging
java.util.prefs
java.util.regex
java.util.spi
java.util.stream
java.util.zip
Chapter 20 Input/Output: Exploring java.io
The I/O Classes and Interfaces
File
Directories
Using FilenameFilter
The listFiles( ) Alternative
Creating Directories
The AutoCloseable, Closeable, and Flushable Interfaces
I/O Exceptions
Two Ways to Close a Stream
The Stream Classes
The Byte Streams
InputStream
OutputStream
FileInputStream
FileOutputStream
ByteArrayInputStream
ByteArrayOutputStream
Filtered Byte Streams
Buffered Byte Streams
SequenceInputStream
PrintStream
DataOutputStream and DataInputStream
RandomAccessFile
The Character Streams
Reader
Writer
FileReader
FileWriter
CharArrayReader
CharArrayWriter
BufferedReader
BufferedWriter
PushbackReader
PrintWriter
The Console Class
Serialization
Serializable
Externalizable
ObjectOutput
ObjectOutputStream
ObjectInput
ObjectInputStream
A Serialization Example
Stream Benefits
Chapter 21 Exploring NIO
The NIO Classes
NIO Fundamentals
Buffers
Channels
Charsets and Selectors
Enhancements Added to NIO by JDK 7
The Path Interface
The Files Class
The Paths Class
The File Attribute Interfaces
The FileSystem, FileSystems, and FileStore Classes
Using the NIO System
Use NIO for Channel-Based I/O
Use NIO for Stream-Based I/O
Use NIO for Path and File System Operations
Pre-JDK 7 Channel-Based Examples
Read a File, Pre-JDK 7
Write to a File, Pre-JDK 7
Chapter 22 Networking
Networking Basics
The Networking Classes and Interfaces
InetAddress
Factory Methods
Instance Methods
Inet4Address and Inet6Address
TCP/IP Client Sockets
URL
URLConnection
HttpURLConnection
The URI Class
Cookies
TCP/IP Server Sockets
Datagrams
DatagramSocket
DatagramPacket
A Datagram Example
Chapter 23 The Applet Class
Two Types of Applets
Applet Basics
The Applet Class
Applet Architecture
An Applet Skeleton
Applet Initialization and Termination
Overriding update( )
Simple Applet Display Methods
Requesting Repainting
A Simple Banner Applet
Using the Status Window
The HTML APPLET Tag
Passing Parameters to Applets
Improving the Banner Applet
getDocumentBase( ) and getCodeBase( )
AppletContext and showDocument( )
The AudioClip Interface
The AppletStub Interface
Outputting to the Console
Chapter 24 Event Handling
Two Event Handling Mechanisms
The Delegation Event Model
Events
Event Sources
Event Listeners
Event Classes
The ActionEvent Class
The AdjustmentEvent Class
The ComponentEvent Class
The ContainerEvent Class
The FocusEvent Class
The InputEvent Class
The ItemEvent Class
The KeyEvent Class
The MouseEvent Class
The MouseWheelEvent Class
The TextEvent Class
The WindowEvent Class
Sources of Events
Event Listener Interfaces
The ActionListener Interface
The AdjustmentListener Interface
The ComponentListener Interface
The ContainerListener Interface
The FocusListener Interface
The ItemListener Interface
The KeyListener Interface
The MouseListener Interface
The MouseMotionListener Interface
The MouseWheelListener Interface
The TextListener Interface
The WindowFocusListener Interface
The WindowListener Interface
Using the Delegation Event Model
Handling Mouse Events
Handling Keyboard Events
Adapter Classes
Inner Classes
Anonymous Inner Classes
Chapter 25 Introducing the AWT: Working with Windows, Graphics, and Text
AWT Classes
Window Fundamentals
Component
Container
Panel
Window
Frame
Canvas
Working with Frame Windows
Setting the Window’s Dimensions
Hiding and Showing a Window
Setting a Window’s Title
Closing a Frame Window
Creating a Frame Window in an AWT-Based Applet
Handling Events in a Frame Window
Creating a Windowed Program
Displaying Information Within a Window
Introducing Graphics
Drawing Lines
Drawing Rectangles
Drawing Ellipses and Circles
Drawing Arcs
Drawing Polygons
Demonstrating the Drawing Methods
Sizing Graphics
Working with Color
Color Methods
Setting the Current Graphics Color
A Color Demonstration Applet
Setting the Paint Mode
Working with Fonts
Determining the Available Fonts
Creating and Selecting a Font
Obtaining Font Information
Managing Text Output Using FontMetrics
Displaying Multiple Lines of Text
Centering Text
Multiline Text Alignment
Chapter 26 Using AWT Controls, Layout Managers, and Menus
AWT Control Fundamentals
Adding and Removing Controls
Responding to Controls
The HeadlessException
Labels
Using Buttons
Handling Buttons
Applying Check Boxes
Handling Check Boxes
CheckboxGroup
Choice Controls
Handling Choice Lists
Using Lists
Handling Lists
Managing Scroll Bars
Handling Scroll Bars
Using a TextField
Handling a TextField
Using a TextArea
Understanding Layout Managers
FlowLayout
BorderLayout
Using Insets
GridLayout
CardLayout
GridBagLayout
Menu Bars and Menus
Dialog Boxes
FileDialog
A Word About Overriding paint( )
Chapter 27 Images
File Formats
Image Fundamentals: Creating, Loading, and Displaying
Creating an Image Object
Loading an Image
Displaying an Image
ImageObserver
Double Buffering
MediaTracker
ImageProducer
MemoryImageSource
ImageConsumer
PixelGrabber
ImageFilter
CropImageFilter
RGBImageFilter
Additional Imaging Classes
Chapter 28 The Concurrency Utilities
The Concurrent API Packages
java.util.concurrent
java.util.concurrent.atomic
java.util.concurrent.locks
Using Synchronization Objects
Semaphore
CountDownLatch
CyclicBarrier
Exchanger
Phaser
Using an Executor
A Simple Executor Example
Using Callable and Future
The TimeUnit Enumeration
The Concurrent Collections
Locks
Atomic Operations
Parallel Programming via the Fork/Join Framework
The Main Fork/Join Classes
The Divide-and-Conquer Strategy
A Simple First Fork/Join Example
Understanding the Impact of the Level of Parallelism
An Example that Uses RecursiveTask<V>
Executing a Task Asynchronously
Cancelling a Task
Determining a Task’s Completion Status
Restarting a Task
Things to Explore
Some Fork/Join Tips
The Concurrency Utilities Versus Java’s Traditional Approach
Chapter 29 The Stream API
Stream Basics
Stream Interfaces
How to Obtain a Stream
A Simple Stream Example
Reduction Operations
Using Parallel Streams
Mapping
Collecting
Iterators and Streams
Use an Iterator with a Stream
Use Spliterator
More to Explore in the Stream API
Chapter 30 Regular Expressions and Other Packages
The Core Java API Packages
Regular Expression Processing
Pattern
Matcher
Regular Expression Syntax
Demonstrating Pattern Matching
Two Pattern-Matching Options
Exploring Regular Expressions
Reflection
Remote Method Invocation (RMI)
A Simple Client/Server Application Using RMI
Formatting Date and Time with java.text
DateFormat Class
SimpleDateFormat Class
The Time and Date API Added by JDK 8
Time and Date Fundamentals
Formatting Date and Time
Parsing Date and Time Strings
Other Things to Explore in java.time
Part III
Introducing GUI Programming with Swing
Chapter 31 Introducing Swing
The Origins of Swing
Swing Is Built on the AWT
Two Key Swing Features
Swing Components Are Lightweight
Swing Supports a Pluggable Look and Feel
The MVC Connection
Components and Containers
Components
Containers
The Top-Level Container Panes
The Swing Packages
A Simple Swing Application
Event Handling
Create a Swing Applet
Painting in Swing
Painting Fundamentals
Compute the Paintable Area
A Paint Example
Chapter 32 Exploring Swing
JLabel and ImageIcon
JTextField
The Swing Buttons
JButton
JToggleButton
Check Boxes
Radio Buttons
JTabbedPane
JScrollPane
JList
JComboBox
Trees
JTable
Chapter 33 Introducing Swing Menus
Menu Basics
An Overview of JMenuBar, JMenu, and JMenuItem
JMenuBar
JMenu
JMenuItem
Create a Main Menu
Add Mnemonics and Accelerators to Menu Items
Add Images and Tooltips to Menu Items
Use JRadioButtonMenuItem and JCheckBoxMenuItem
Create a Popup Menu
Create a Toolbar
Use Actions
Put the Entire MenuDemo Program Together
Continuing Your Exploration of Swing
Part IV
Introducing GUI Programming with JavaFX
Chapter 34 Introducing JavaFX GUI Programming
JavaFX Basic Concepts
The JavaFX Packages
The Stage and Scene Classes
Nodes and Scene Graphs
Layouts
The Application Class and the Lifecycle Methods
Launching a JavaFX Application
A JavaFX Application Skeleton
Compiling and Running a JavaFX Program
The Application Thread
A Simple JavaFX Control: Label
Using Buttons and Events
Event Basics
Introducing the Button Control
Demonstrating Event Handling and the Button
Drawing Directly on a Canvas
Chapter 35 Exploring JavaFX Controls
Using Image and ImageView
Adding an Image to a Label
Using an Image with a Button
ToggleButton
RadioButton
Handling Change Events in a Toggle Group
An Alternative Way to Handle Radio Buttons
CheckBox
ListView
ListView Scrollbars
Enabling Multiple Selections
ComboBox
TextField
ScrollPane
TreeView
Introducing Effects and Transforms
Effects
Transforms
Demonstrating Effects and Transforms
Adding Tooltips
Disabling a Control
Chapter 36 Introducing JavaFX Menus
Menu Basics
An Overview of MenuBar, Menu, and MenuItem
MenuBar
Menu
MenuItem
Create a Main Menu
Add Mnemonics and Accelerators to Menu Items
Add Images to Menu Items
Use RadioMenuItem and CheckMenuItem
Create a Context Menu
Create a Toolbar
Put the Entire MenuDemo Program Together
Continuing Your Exploration of JavaFX
Part V
Applying Java
Chapter 37 Java Beans
What Is a Java Bean?
Advantages of Java Beans
Introspection
Design Patterns for Properties
Design Patterns for Events
Methods and Design Patterns
Using the BeanInfo Interface
Bound and Constrained Properties
Persistence
Customizers
The Java Beans API
Introspector
PropertyDescriptor
EventSetDescriptor
MethodDescriptor
A Bean Example
Chapter 38 Introducing Servlets
Background
The Life Cycle of a Servlet
Servlet Development Options
Using Tomcat
A Simple Servlet
Create and Compile the Servlet Source Code
Start Tomcat
Start a Web Browser and Request the Servlet
The Servlet API
The javax.servlet Package
The Servlet Interface
The ServletConfg Interface
The ServletContext Interface
The ServletRequest Interface
The ServletResponse Interface
The GenericServlet Class
The ServletInputStream Class
The ServletOutputStream Class
The Servlet Exception Classes
Reading Servlet Parameters
The javax.servlet.http Package
The HttpServletRequest Interface
The HttpServletResponse Interface
The HttpSession Interface
The Cookie Class
The HttpServlet Class
Handling HTTP Requests and Responses
Handling HTTP GET Requests
Handling HTTP POST Requests
Using Cookies
Session Tracking
Appendix Using Java’s Documentation Comments
The javadoc Tags
@author
{@code}
@deprecated
{@docRoot}
@exception
{@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
Index
Add Highlight
No Comment
..................Content has been hidden....................
You can't read the all page of ebook, please click
here
login for view all page.
Day Mode
Cloud Mode
Night Mode
Reset