Download Exception

Document related concepts
no text concepts found
Transcript
Java
Programming
Fundamentals
Copyright © 2002 ProsoftTraining. All rights reserved.
Lesson 1:
Java Runtime
Environment
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Identify the differences between stand-alone
applications and applets
• Describe the role of the Java Virtual Machine
• Create a simple Java program
• Use Java comments
• Compile and execute a Java program
• Describe the differences between *.java and
*.class files
The Java
Virtual Machine
•
•
•
•
•
Stand-alone applications
Applets
Classes
Methods
Bytecode
Java Comments
• Single-line comment
• Multiline comment
• Javadoc comment
Summary
 Identify the differences between stand-alone
applications and applets
 Describe the role of the Java Virtual Machine
 Create a simple Java program
 Use Java comments
 Compile and execute a Java program
 Describe the differences between *.java and
*.class files
Lesson 2:
Data Types,
Variables and Operators
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
•
•
•
•
Use primitive data types
Declare a variable
Distinguish between local and class variables
Distinguish between implicit and explicit
casting
• Use the operators for primitive types
Data
Types
• Primitives
– Integers
– Floating-point numbers
– Character
– Boolean
Declaring Variables
and Variable Scope
• Types
– Local
– Instance
– Class
• Default variable values
• Variable declaration and initialization
• Casting
– Implicit
– Explicit
Casting
Rules Chart
byte
short
int
char
long
float
double
Operators
• Arithmetic operators
• Relational operators
• Logical operators
– Short-circuit
• Bitwise operators
Automatic
Casting
• Java automatically casts
– bytes or shorts  ints
– floats  doubles
Summary




Use primitive data types
Declare a variable
Distinguish between local and class variables
Distinguish between implicit and explicit
casting
 Use the operators for primitive types
Lesson 3:
Control
Statements
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Explain the block structure of Java
• Use Java conditional statements
• Use Java iterative statements
Code
Blocks
• Used to group the contents of a class or a
method
• Used to designate all conditional and iterative
statements
• Used for exception handling
Conditional
Statements
• if statement
• switch/case statement
– break statement
Iterative
Statements (Loops)
•
•
•
•
while loop (entry condition loop)
do while loop (exit condition loop)
for loop
Nested loops (break and continue)
Summary
 Explain the block structure of Java
 Use Java conditional statements
 Use Java iterative statements
Lesson 4:
Methods
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
•
•
•
•
•
Create and use static methods
Return a value from a method
Explain pass by value
Describe overloading methods
Identify the method signature
Java
Methods
• The executable part of a class
– Member
Return
Statement
• Data types
• Void
Calling
a Method
• Parameters
• Literals
Pass by Value
• A copy of the value of the variable is available
to the method; changes to the copy do not
affect the original value
Overloading
• Method signature
– Name
– Parameter list
• Does not include return type
Summary





Create and use static methods
Return a value from a method
Explain pass by value
Describe overloading methods
Identify the method signature
Lesson 5:
Arrays
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
•
•
•
•
•
•
•
Declare and initialize an array
Allocate space for a new array
Describe array indexing
Use the length property
Discuss why arrays are passed by reference
Discuss Java’s garbage collection mechanism
Retrieve command line parameters
What Is
an Array?
• Collection of same type
• Non-primitive data type
Initializing
an Array
• Allocation
• Reference
• Index
Objects
• Properties
• Methods
Using
an Array
• length property
Passing an Array
to a Method
MyIntArray
1
3
5
0
1
2
tmpIntArray
Garbage
Collection
• Variable name reuse
• Memory leak
Command Line
Parameters
• Always String type data
Summary







Declare and initialize an array
Allocate space for a new array
Describe array indexing
Use the length property
Discuss why arrays are passed by reference
Discuss Java’s garbage collection mechanism
Retrieve command line parameters
Lesson 6:
Classes
and Objects
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Identify the parts of an object
• Create and use instance members
• Distinguish between instance and class
members
• Define abstraction
• Create object references
Object-Oriented Programming
• Refers to the creation of a number of
objects that communicate with one another
What Is
an Object?
• Instantiation
• The new keyword
Instance and
Class Members
• Class members
– The exception in Java
• Instance members
– The rule in Java
• Accessing instance members
– Dot notation
• Accessing class members
Abstraction
• What does the object do versus how does it
do it?
• Functionality versus implementation
Object
References
tmpEmp variable
rachael
tmpEmp
name: "Rachael"
dept: "Accounting"
salary: 52000
Summary
 Identify the parts of an object
 Create and use instance members
 Distinguish between instance and class
members
 Define abstraction
 Create object references
Lesson 7:
Inheritance
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Create a new class using inheritance
• Create an overridden method
What Is
Inheritance?
• Code reuse
• Using inheritance
– extends keyword
– subclass
– superclass
– Multiple inheritance
Overriding
Methods
• Same signature as the superclass
• super.method()
Summary
 Create a new class using inheritance
 Create an overridden method
Lesson 8:
Constructors
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Use the default constructor
• Create a constructor to initialize instance
variables
• Call other constructors from the same class
and the parent class
• Create a no-arguments constructor
• Discuss String characteristics and define the
common methods of String
What Is a
Constructor?
• new keyword
• Similarities to methods
– Initialization of object
– Pass parameters
• Differences from methods
– Same name as class
– No return type
• Callback
Using
Constructors
• Default constructor
– No arguments
– Must be explicitly created if there are any
other constructors
• Overloading constructors
– Unique parameter types
The
Keyword this
• this() as a constructor
• Avoiding namespace conflicts
• The super keyword
Constructors
and Callbacks
• Constructors are a major facilitator in
establishing interobject communication
Strings and
StringBuffer
•
•
•
•
String constructors
String characteristics
Methods of String
StringBuffer
Summary
 Use the default constructor
 Create a constructor to initialize instance
variables
 Call other constructors from both the same
class and the parent class
 Create a no-arguments constructor
 Discuss String characteristics and define the
common methods of String
Lesson 9:
Interfaces and Abstract Classes
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
•
•
•
•
Define and use interfaces
Define polymorphism
Use abstract classes
Create an abstract method
What Is an
Interface?
• Contents of an interface
– Abstract methods
– Final variables
• Interface functions
– Decoupling objects
– Providing data type
Polymorphism
• Using one method name to invoke many
different methods
What Is an
Abstract Class?
• Cannot be instantiated
• Can be used for a type
Summary




Define and use interfaces
Define polymorphism
Use abstract classes
Create an abstract method
Lesson 10:
Packages and Access Modifiers
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
•
•
•
•
Compile and run a class with packages
Identify the packages in the Java 2 API
Identify the various access levels in Java
Describe how access modifiers can be used to
set the access level of a variable, method or
class
• Describe the object-oriented programming
principle of encapsulation
• Identify accessor and mutator methods
Packages and
Access Modifiers
• Packages
– import statement
• Access modifiers
– public
– protected
– package
– private
Java 2 Application
Programming Interface
• Organized into packages such as
– java.lang
– java.awt
– java.io
– java.util
– java.net
Encapsulation
• Accessor
– Method that reads a variable
• Mutator
– Wrapping variables and methods together
Object
Encapsulation
Data 1
Data 2
Data 3
Data 4
Summary




Compile and run a class with packages
Identify the packages in the Java 2 API
Identify the various access levels in Java
Describe how access modifiers can be used to
set the access level of a variable, method or
class
 Describe the object-oriented programming
principle of encapsulation
 Identify accessor and mutator methods
Lesson 11:
Swing Components
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Distinguish between the AWT and Swing
• Identify the general organization of the Swing
class structure
• Define and use Swing widgets and containers
What Is
the AWT?
• Heavyweight components
– Peer components
• AWT 1.0
– Container propagation
– Single-method event-handling
• AWT 1.1
– New event model
What
Is Swing?
• Lightweight components
– No peer components
– All Java
• Customizable
• Model View Controller (MVC) programming
paradigm
• Included in Java 2 (JDK 1.2)
Basic Swing
Components
•
•
•
•
•
•
JComponent
JLabel
JButton
JTextField
JTextArea
JScrollBar
•
•
•
•
•
•
ImageIcon
JScrollPane
JPanel
JFrame
JFileChooser
JApplet
Graphical Widgets
• The graphical components with which users
interact
– JButton
– JLabel
– JScrollBar
Swing
Containers
• Two types
– Top level (includes JFrame, Window)
– Lower level (includes JPanel,
JScrollPane)
Summary
 Distinguish between the AWT and Swing
 Identify the general organization of the Swing
class structure
 Define and use Swing widgets and containers
Lesson 12:
Layout Managers
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Define a layout manager
• Set a layout manager for a Container
• Effectively use FlowLayout, GridLayout,
BorderLayout and BoxLayout
• Nest containers and layout managers to form
more complex GUI layouts
• Separate a complex design into its component
containers and layout managers
What Is a
Layout Manager?
•
•
•
•
•
FlowLayout
GridLayout
BorderLayout
BoxLayout
CardLayout
•
•
•
•
•
GridBagLayout
GridLayout
OverlayLayout
ScrollPaneLayout
ViewportLayout
FlowLayout
• Centers components on each line in a flowing
manner
GridLayout
• Adds components in a gridlike format
BorderLayout
NORTH
W
E
S
T
CENTER
SOUTH
E
A
S
T
BoxLayout
• Allows either a horizontal or a vertical layout
of components
Combining
Layouts
Button 1
Button 2
Button 3
Button 4
Summary
 Define a layout manager
 Set a layout manager for a Container
 Effectively use FlowLayout, GridLayout,
BorderLayout and BoxLayout
 Nest containers and layout managers to form
more complex GUI layouts
 Separate a complex design into its component
containers and layout managers
Lesson 13:
Graphics in Java
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Identify the AWT class structure for graphics
• Gain access to a container’s graphic context
by overriding the
paint(Graphics g) method
• Use methods of the Graphics class via the
graphics context
• Effectively use the Color and Font classes
Graphics Class
• The graphics context is used to access the
functionality of the Graphics class (an
abstract class)
Graphics
Class Methods
•
•
•
•
•
•
•
draw3DRect()
drawArc()
drawLine()
drawOval()
drawPolygon()
drawPolyline()
drawRect()
•
•
•
•
•
•
•
drawRoundRect()
fill3DRect()
fillArc()
fillOval()
fillPolygon()
fillRect()
fillRoundRect()
Other
Classes
• Color
setColor()
• Font
setFont()
– FontMetrics
Summary
 Identify the AWT class structure for graphics
 Gain access to a container’s graphic context
by overriding the
paint(Graphics g) method
 Use methods of the Graphics class via the
graphics context
 Effectively use the Color and Font classes
Lesson 14:
The Event
Delegation Model
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Describe the event delegation model
• Create listener classes that can respond to
events
• Register listener classes with their
Component sources
• Capture events and deal with them in
meaningful ways
What Is
an Event?
• What caused the event?
• What was the exact nature of the event?
• Is additional information available about
the event?
JDK 1.0
Event Handling
•
•
•
•
•
Tightly coupled with the AWT
Inefficient
General
Unruly
Code and event handling could not be
separated
SDK 1.2
Event Handling
•
•
•
•
•
Generating the event object
Sending the event object to the listener
Preparing the listener to receive the event
Example: Creating a closeable JFrame
JFrame convenience methods for event
handling
• Example: Event handling and callbacks
Summary
 Describe the event delegation model
 Create listener classes that can respond to
events
 Register listener classes with their
Component sources
 Capture events and deal with them in
meaningful ways
Lesson 15:
Inner Classes
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Define an inner class
• Recognize the advantages of inner classes
over package-level classes in relation to event
handling
• Design and implement inner classes for event
handling
What Is an
Inner Class?
• A class defined within other classes
• Introduced with the SDK 1.2
Inner Classes
for Event Handling
• Member inner classes
• Anonymous inner classes
Summary
 Define an inner class
 Recognize the advantages of inner classes
over package-level classes in relation to event
handling
 Design and implement inner classes for event
handling
Lesson 16:
Java Applets
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Compare and contrast Java applets and
applications
• Implement the life cycle of an applet through
its inherited methods
• Embed an applet into an HTML document
• Pass parameters from an HTML document to
its contained applet
• Identify applet security restrictions
• Convert an applet into an application
JApplet
Class Hierarchy
Object
Component
Container
Panel
Applet
JApplet
Applets and
Web Browsers
• Applets do not have a main() method
• Applets have a life cycle
• Applets are started from HTML pages, and
receive information from HTML pages
• Because they are program code, applets
should not be trusted
Converting an
Application into an Applet
• Use init() method to perform
instantiation
• Instantiating the applet is unnecessary
• Applets must be derived from JApplet
• Applet size should be set within the HTML
document (the Web browser makes it
visible)
• Applets must be declared public
Converting an Applet
into an Application
• By adding an instance of the JApplet to the
JFrame and calling its init() and start()
methods, the conversion from JApplet to
stand-alone JFrame readily takes place
Summary
 Compare and contrast Java applets and
applications
 Implement the life cycle of an applet through
its inherited methods
 Embed an applet into an HTML document
 Pass parameters from an HTML document to
its contained applet
 Identify applet security restrictions
 Convert an applet into an application
Lesson 17:
Exceptions
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Differentiate between errors and
exceptions
• Differentiate between runtime exceptions
and explicit exceptions
• Propagate an exception using the throws
statement
• Handle an exception using the try/catch
statement
• Create and use a user-defined exception
What Is
an Exception?
• Exceptions
– Runtime exceptions (unchecked)
– Other exceptions (checked)
Exception
Class Hierarchy
Object
Throwable
Exception
RuntimeException



Error
Explicit Exceptions






Handling
Exceptions
• Ignore the Exception
• Handle the Exception with a try/catch
statement
• Throw the Exception to the calling method
• Handle the Exception and rethrow it to the
calling method
Creating
User-Defined Exceptions
• Creating the exception
• Throwing the exception
• Exception handling tips
Exception
Handling Tips
• Use simple tests instead of try/catch
• Choose user-defined exceptions wisely
• Use one try/catch block for multiple
exceptions
• Do something meaningful with caught
exceptions
Summary
 Differentiate between errors and exceptions
 Differentiate between runtime exceptions and
explicit exceptions
 Propagate an exception using the throws
statement
 Handle an exception using the try/catch
statement
 Create and use a user-defined exception
Lesson 18:
Creating Threads
and Thread Methods
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Define threads
• Create and instantiate threads using two
different techniques
• Control single-thread flow
• Define the four thread states and their
relationships to thread methods
What
Are Threads?
• Multitasking
• Multiprocessing
• Multithreading
How Operating Systems
Handle Multitasking
• Pre-emptive multitasking
• Cooperative multitasking
Types of
Threads in Java
• Daemon thread
• User thread
– Main thread
– Other user threads
The Main Thread
main thread
user thread
user thread
user thread
user thread
Creating Threads
• Subclassing the Thread class
• Implementing the Runnable interface
• Which technique?
Summary
 Define threads
 Create and instantiate threads using two
different techniques
 Control single-thread flow
 Define the four thread states and their
relationships to thread methods
Lesson 19:
Thread
Synchronization
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Define synchronization in relation to object
monitors
• Control thread racing using thread
synchronization
• Convert non-atomic to atomic processes to
avoid thread racing
• Use sophisticated methods for controlling
threads
• Stop, suspend and resume threads
• Explain thread deadlock
What Is Thread Synchronization?
• Controlling threads in a predictable manner
Thread
Racing
• Two threads trying to access the same data
Synchronized and
the Object Monitor
• synchronized keyword
• Threads waiting in a queue to obtain an
objects monitor
• All synchronized methods of an object use a
single monitor
Thread
Race Condition
• Competing for resources
• Synchronizing the methods
• Atomic processes
Sophisticated
Thread Synchronization
• Consumer/producer scenario
Stopping, Suspending
and Resuming Threads
• Stopping a thread
• Suspending a thread
• Resuming a thread
Summary
 Define synchronization in relation to object
monitors
 Control thread racing using thread
synchronization
 Convert non-atomic to atomic processes to
avoid thread racing
 Use sophisticated methods for controlling
threads
 Stop, suspend and resume threads
 Explain thread deadlock
Lesson 20:
Streams and Serialization
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Define a stream
• Differentiate between byte streams and
character streams
• Recognize the abstraction of byte streams
through the InputStream and OutputStream
classes
• Recognize the abstraction of character
streams through the Reader and Writer
classes
• Create and use file objects
Objectives
(cont’d)
• Use System.in and System.out to perform
stream operations
• Nest streams using wrapper classes to
enhance basic stream behavior
• Perform file I/O
• Define object serialization
• Use serialization to save an object to a file
• Explain the transient keyword
What Is
a Stream?
• A path of information from a source to a
destination
InputStream, OutputStream,
Reader and Writer
• JDK 1.0 (bytes)
– InputStream
– OutputStream
• JDK 1.1 (characters)
– Reader
– Writer
Files
• Instantiating a file object
• Working with a file object
– Methods of File
– Directories
– FileDialog/FileChooser
Stream
Classes of java.io.*
• System.in and System.out
• Reading bytes from System.in
• Converting a byte stream into a character
stream
• Wrapper streams
• File I/O
Serialization
• The process of object serialization
– Marking an object for serialization
– Writing the object to file
– Reading the serialized object from a file
• Transient variables and security
Summary
 Define a stream
 Differentiate between byte streams and
character streams
 Recognize the abstraction of byte streams
through the InputStream and OutputStream
classes
 Recognize the abstraction of character
streams through the Reader and Writer
classes
 Create and use file objects
Summary
(cont’d)
 Use System.in and System.out to perform
stream operations
 Nest streams using wrapper classes to
enhance basic stream behavior
 Perform file I/O
 Define object serialization
 Use serialization to save an object to a file
 Explain the transient keyword
Lesson 21:
Networking in Java
Copyright © 2002 ProsoftTraining. All rights reserved.
Objectives
• Define networking, IP addresses, the Domain
Name System, and ports
• Discuss the socket model and socket-tosocket communication
• Explain the client/server model
• Write a single-threaded client/server echo
system
• Write a multithreaded client/server echo
system
What Is
Networking?
• Computers communicating across distances
• Java networking
– TCP/IP
– UDP
Connecting Computers
Across the Internet
• IP addresses
– Dotted quad
– 32 bits
– IPv6
• DNS
• Sockets
• Well-known ports
Well-Known Ports
and Their Protocols
Port
Protocol
21
FTP
23
Telnet
25
E-mail
79
Finger
80
HTTP
119
NNTP/Usenet
Networking
Classes of java.net.*
• Common networking classes
– InetAddress
– Socket
– ServerSocket
The Java
Client/Server Model
• Server
– Delivers information
– ServerSocket object
– accept method returns a socket
• Client
– Requests information from the server
– Connects to server with socket
Building the
EchoServer
• The client
– Step 1: getConnection
– Step 2: sendMessage
– Step 3: receiveMessage
• The server
– Step 1: getConnection
– Step 2: receiveMessage
– Step 3: sendMessage
Multithreading
Your Client/Server Model
•
•
•
•
Modifications to the server
The Connection class
The Client class
Running the threaded client/server example
Summary
 Define networking, IP addresses, the
Domain Name System, and ports
 Discuss the socket model and socket-tosocket communication
 Explain the client/server model
 Write a single-threaded client/server echo
system
 Write a multithreaded client/server echo
system
Java
Programming Fundamentals








Java Runtime Environment
Data Types, Variables and Operators
Control Statements
Methods
Arrays
Classes and Objects
Inheritance
Constructors
Java
Programming Fundamentals







Interfaces and Abstract Classes
Packages and Access Modifiers
Swing Components
Layout Managers
Graphics in Java
The Event Delegation Model
Inner Classes
Java
Programming Fundamentals






Java Applets
Exceptions
Creating Threads and Thread Methods
Thread Synchronization
Streams and Serialization
Networking in Java