Professional Documents
Culture Documents
Guia de Actividades1 PDF
Guia de Actividades1 PDF
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
c o m
ฺ
ail eฺ
Java Programming g mLanguage,
id
Java SE 6 11 @ G u
2 e n t
9 2 0 ud
n t S t
( s ai this
A e - Volume 1
NActivityusGuide
L TR e to
O BE ens SL-275-SE6 G.2
E N le lic
M OR ferab
A RO -trans
GEN non
D61748GC11
Edition 1.1
June 2010
D67982
7i Business Solutions, SฺAฺ de CฺVฺ
Copyright © 2009, 2010, Oracle and/or its affiliates. All rights reserved.
Disclaimer
This document contains proprietary information, is provided under a license agreement containing restrictions on use and
disclosure, and is protected by copyright and other intellectual property laws. You may copy and print this document solely for
your own use in an Oracle training course. The document may not be modified or altered in any way. Except as expressly
permitted in your license agreement or allowed by law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express
authorization of Oracle.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
The information contained in this document is subject to change without notice. If you find any problems in the document,
please report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This
document is not warranted to be error-free.
This training manual may include references to materials, offerings, or products that were previously offered by Sun
Microsystems, Inc. Certain materials, offerings, services, or products may no longer be offered or provided.Oracle and its
affiliates cannot be held responsible for any such references should they appear in the text provided.
s a
U.S. GOVERNMENT RIGHTS
The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or disclose these training materials are
) h a
c o m
restricted by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.
ฺ
ail eฺ
Trademark Notice
g m id
@ G u
owners.
0 2 11 ent
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
t 9 2
S t ud
AMD, Opteron, the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced Micro
n
( sai this
Devices. Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used
under license and are trademarks or registered trademarks of SPARC International, Inc. UNIX is a registered trademark
AN use
licensed through X/Open Company, Ltd.
R
LT se to
E
B en
O
N le lic
E
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Table of Contents
About This Workbook .......................................................Preface-xvii
Lab Goals............................................................................. Preface-xvii
s a
Performing the Exercises ................................................. Preface-xviii
) h a
c o m
Conventions .......................................................................... Preface-xix
ail eฺฺ
Typographical Conventions ...................................... Preface-xix
g m
Additional Conventions.............................................. Preface-xx
id
@ G u
0 2 11 ent
Getting Started..................................................................................1-1
t 9 2 t u d
Objectives ........................................................................................... 1-1
Exercise 1: Exploring Java™
a in Program i s S Errors ................................ 1-2
s
( et h
Preparation................................................................................. 1-2
N s
RA toa Test
Task – Correcting
ExerciseL2:TCreating
uCompilation and Runtime Errors........... 1-2
Program (Level 1) ............................... 1-4
B E nse
Preparation................................................................................. 1-4
O
N le l
Task i c1
e– Copying the Account Class ..................................... 1-5
E
M OR ferab Task 2 – Creating the TestAccount Class............................. 1-5
Task 3 – Compiling the TestAccount Class ......................... 1-6
A RO -trans Task 4 – Running the TestAccount Program ...................... 1-6
E N n
G no Exercise 2: Creating a Test Program (Level 2) ............................... 1-7
Preparation................................................................................. 1-7
Task 1 – Copying the Account Class ..................................... 1-8
Task 2 – Creating the TestAccount Class............................. 1-8
Task 3 – Compiling the TestAccount Class ......................... 1-9
Task 4 – Running the TestAccount Program ...................... 1-9
Exercise 2: Creating a Test Program (Level 3) ............................. 1-10
Preparation............................................................................... 1-10
Task 1 – Copying the Account Class ................................... 1-11
Task 2 – Creating the TestAccount Class........................... 1-11
Task 3 – Compiling the TestAccount Class ....................... 1-12
Task 4 – Running the TestAccount Program .................... 1-12
Exercise Summary............................................................................ 1-13
v
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
EN non
Task 3 – Compiling the TestAccount Class ....................... 2-13
G Task 4 – Running the TestAccount Program .................... 2-13
Exercise 3: Exploring Encapsulation, Version 2 (Level 2) .......... 2-14
Preparation............................................................................... 2-14
Task 1 – Modifying the Account Class ................................ 2-14
Task 2 – Modifying the TestAccount Class ....................... 2-15
Task 3 – Compiling the TestAccount Class ....................... 2-15
Task 4 – Running the TestAccount Program .................... 2-15
Exercise 3: Exploring Encapsulation, Version 2 (Level 3) .......... 2-16
Preparation............................................................................... 2-16
Task 1 – Modifying the Account Class ................................ 2-16
Task 2 – Modifying the TestAccount Class ....................... 2-17
Task 3 – Compiling the TestAccount Class ....................... 2-17
Task 4 – Running the TestAccount Program .................... 2-17
Exercise 4: Creating Java Packages................................................ 2-18
Preparation............................................................................... 2-19
0 2 11 ent
Exercise 2: Creating Customer Accounts (Level 2) ....................... 3-8
n t 2
S t ud
Preparation................................................................................. 3-8
9
sai this
Task 1 – Creating the Customer Class ................................... 3-9
(
Task 2 – Copying the TestBanking Class............................. 3-9
R AN use
Task 3 – Compiling the TestBanking Class ......................... 3-9
E LT se to
Task 4 – Running the TestBanking Program .................... 3-10
O B enExercise 2: Creating Customer Accounts (Level 3) ..................... 3-11
E N le lic Preparation............................................................................... 3-11
RO -trans
Task 2 – Copying the TestBanking Class........................... 3-13
A Task 3 – Compiling the TestBanking Class ....................... 3-13
GEN non Task 4 – Running the TestBanking Program .................... 3-13
Exercise Summary............................................................................ 3-14
Expressions and Flow Control........................................................4-1
Objectives ........................................................................................... 4-1
Exercise 1: Using Loops and Branching Statements ..................... 4-2
Preparation................................................................................. 4-3
Task 1 – Creating the FooBarBaz Class ................................. 4-3
Task 2 – Compiling the FooBarBaz Class ............................. 4-4
Task 3 – Running the FooBarBaz Program........................... 4-4
Hints............................................................................................ 4-4
Exercise 2: Using Conditional Statements in the Account Class
(Level 1) ............................................................................................ 4-5
Preparation................................................................................. 4-5
Task 1 – Modifying the Account Class .................................. 4-6
Task 2 – Deleting the Current TestBanking Class ................ 4-6
vii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Preparation................................................................................. 4-8
Task 1 – Modifying the Account Class .................................. 4-9
Task 2 – Deleting the Current TestBanking Class ................ 4-9
Task 3 – Copying the TestBanking Class............................. 4-9
Task 4 – Compiling the TestBanking Class ......................... 4-9
Task 5 – Running the TestBanking Program ...................... 4-9
Exercise 2: Using Conditional Statements in the Account Class
(Level 3) .......................................................................................... 4-10
Preparation............................................................................... 4-10
Task 1 – Modifying the Account Class ................................ 4-11
s a
Task 2 – Deleting the Current TestBanking Class .............. 4-11
) h a
Task 3 – Copying the TestBanking Class........................... 4-11
c o m
ail eฺ
Task 4 – Compiling the TestBanking Class ....................... 4-11 ฺ
g m
Task 5 – Running the TestBanking Program .................... 4-12
id
@ G u
Exercise 3: Using Nested Loops (Advanced) ............................... 4-13
2 11 ent
Preparation............................................................................... 4-13
0
n t 9 2 t ud
Task 1 – Writing the isSubString Method........................ 4-14
S
sai this
Task 2 – Compiling the TestIsSubString Class .............. 4-14
(
AN use
Task 3 – Running the TestIsSubString Program............ 4-14
R
LT se to
Hints......................................................................................... 4-15
B enE Exercise Summary............................................................................ 4-16
O
N le lic
Arrays................................................................................................ 5-1
R E b
M e ra 1 – Using Primitive Arrays (Level 2) ............................... 5-1
O fExercise
Objectives ...........................................................................................
ix
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
LT se to
Task 5 – Running the TestReport Program....................... 6-27
E Exercise 3: Creating a Batch Program (Advanced) ..................... 6-28
B en
O
N le lic Preparation............................................................................... 6-29
E Task 1 – Modifying the SavingsAccount Class................. 6-29
M OR ferab Task 2 – Creating the AccumulateSavingsBatch
EN non
Task 3 – Copying the TestBatch Class ............................... 6-30
G Task 4 – Compiling the TestBatch Class ........................... 6-30
Task 5 – Running the TestBatch Program......................... 6-30
Exercise Summary............................................................................ 6-32
Advanced Class Features ............................................................... 7-1
Objectives ........................................................................................... 7-1
Exercise 1: Applying Static Members to a Design (Level 1) ........ 7-2
Preparation................................................................................. 7-3
Task 1 – Modifying the Bank Class......................................... 7-3
Task 2 – Modifying the CustomerReport Class................... 7-3
Task 3 – Deleting the Current TestReport Class ................ 7-4
Task 4 – Copying the TestReport Class............................... 7-4
Task 5 – Compiling the TestReport Class ........................... 7-4
Task 6 – Running the TestReport Program......................... 7-4
Exercise 1: Applying Static Members to a Design (Level 2) ........ 7-5
LT se to
Task 1 – Creating the Pet Interface ....................................... 7-17
E
B en Task 2 – Creating the Animal Classes .................................. 7-17
O
N le lic Task 3 – Creating the TestAnimals Class........................... 7-19
E Task 4 – Compiling the TestAnimals Class ....................... 7-20
M OR ferab Task 5 – Running the TestAnimals Program .................... 7-20
EN non
(Level 3) .......................................................................................... 7-21
G Preparation............................................................................... 7-21
Task 1 – Creating the Pet Interface ....................................... 7-22
Task 2 – Creating the Animal Classes .................................. 7-22
Task 3 – Creating the TestAnimals Class........................... 7-25
Task 4 – Compiling the TestAnimals Class ....................... 7-26
Task 5 – Running the TestAnimals Program .................... 7-26
Exercise Summary............................................................................ 7-27
Exceptions and Assertions .............................................................8-1
Objectives ........................................................................................... 8-1
Exercise: Creating Your Own Exception (Level 1) ........................ 8-2
Task 1 – Creating the OverdraftException Class ............. 8-4
Task 2 – Modifying the Account Class .................................. 8-4
Task 3 – Modifying the CheckingAccount Class ................ 8-4
Task 4 – Deleting the Current TestBanking Class .............. 8-4
xi
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
s a i
Objectives ...........................................................................................
i s 9-1
N ( ustoeRepresent
Exercise 1: Using Collections t h Association
R A
(Level 1) ............................................................................................ 9-2
T t o
B
TaskE1L– Modifying
Preparation.................................................................................
n s e the Bank Class......................................... 9-3 9-3
O l i c e
R EN Task b l e 23 –– Modifying the Customer Class................................ 9-3
Preparation............................................................................... 11-4
Task 1 – Creating a data Directory ...................................... 11-4
Task 2 – Copying the Resource File...................................... 11-4
Task 3 – Creating the DataSource Class............................. 11-5
Task 4 – Deleting Unnecessary Classes ............................... 11-5
Task 5 – Copying the TestReport Class............................. 11-5
Task 6 – Compiling the TestReport Class ......................... 11-5
Task 7 – Running the BankPrj Project................................. 11-6
Exercise 1: Reading a Data File (Level 2) ...................................... 11-7
Preparation............................................................................... 11-7
Task 1 – Creating a data Directory ...................................... 11-8 s a
Task 2 – Copying the Resource File...................................... 11-8 ) h a
c o m
Task 3 – Creating the DataSource Class............................. 11-8
ฺ
ail eฺ
Task 4 – Deleting Unnecessary Classes ............................... 11-9
g m id
@ G u
Task 5 – Copying the TestReport Class............................. 11-9
0 2 11 ent
Task 6 – Compiling the TestReport Class ......................... 11-9
n t 2
S t ud
Task 7 – Running the BankPrj Project................................. 11-9
9
sai this
Exercise 1: Reading a Data File (Level 3) .................................... 11-11
(
Preparation............................................................................. 11-11
R AN use
Task 1 – Creating a data Directory .................................... 11-12
E LT se to
Task 2 – Copying the Resource File.................................... 11-12
O B en Task 3 – Creating the DataSource Class........................... 11-12
E N le lic Task 4 – Deleting Unnecessary Classes ............................. 11-15
RO -trans
Task 6 – Compiling the TestReport Class ....................... 11-15
A Task 7 – Running the BankPrj Project............................... 11-15
GEN non Exercise Summary.......................................................................... 11-17
Building Java GUIs Using the Swing API.....................................12-1
Objectives ......................................................................................... 12-1
Exercise 1: Creating the ChatClient GUI Part 1 (Level 1)........ 12-2
Preparation............................................................................... 12-3
Task 1 – Creating the ChatClient Class............................. 12-3
Task 2 – Compiling the ChatClient Class ......................... 12-4
Task 3 – Running the ChatClient Program....................... 12-4
Task 4 – Terminating the Running ChatClient Program 12-4
Exercise 1: Creating the ChatClient GUI Part 1 (Level 2)........ 12-5
Preparation............................................................................... 12-5
Task 1 – Creating the ChatClient Class............................. 12-6
Task 2 – Compiling the ChatClient Class ......................... 12-6
Task 3 – Running the ChatClient Program....................... 12-7
Task 4 – Terminating the Running ChatClient Program 12-7
xiii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
0 2 11 ent
Preparation............................................................................... 13-2
n t 2
S t ud
Task 1 – Modifying the ChatClient Class ......................... 13-3
9
sai this
Task 2 – Compiling the ChatClient Class ......................... 13-3
(
Task 3 – Running the ChatClient Program....................... 13-3
AN use
Hints.......................................................................................... 13-3
R
LT se to
Exercise 1: Creating the ChatClient GUI Part 2 (Level 2)........ 13-4
E
O B en Preparation............................................................................... 13-4
E N le licTask 1 – Modifying the ChatClient Class ......................... 13-4
RO -trans
Task 3 – Running the ChatClient Program....................... 13-5
A Exercise 1: Creating the ChatClient GUI Part 2 (Level 3)........ 13-6
G EN non Preparation............................................................................... 13-6
Task 1 – Modifying the ChatClient Class ......................... 13-6
Task 2 – Compiling the ChatClient Class ......................... 13-8
Task 3 – Running the ChatClient Program....................... 13-8
Exercise 2: Creating the Bank ATM GUI Part 2
(Advanced)..................................................................................... 13-9
Preparation............................................................................. 13-10
Task 1 – Modifying the ATMClient Class.......................... 13-10
Task 2 – Compiling the ATMClient Class ......................... 13-10
Task 3 – Running the BankPrj Project............................... 13-10
Exercise Summary.......................................................................... 13-12
GUI-Based Applications ................................................................ 14-1
Objectives ......................................................................................... 14-1
Exercise: Creating the ChatClient GUI, Part 3 (Level 1).......... 14-2
Preparation............................................................................... 14-3
0 2 11 ent
Task 2 – Creating the TestThreeThreads Class................ 15-3
n t 2
S t ud
Task 3 – Compiling the TestThreeThreads Class ............ 15-3
9
sai this
Task 4 – Running the TestThreeThreads Program ......... 15-4
(
Exercise: Using Multithreaded Programming (Level 2)............. 15-5
R AN use
Preparation............................................................................... 15-5
E LT se to
Task 1 – Creating the PrintMe Class ................................... 15-6
O B en Task 2 – Creating the TestThreeThreads Class................ 15-6
E N le lic Task 3 – Compiling the TestThreeThreads Class ............ 15-7
RO -trans
Exercise: Using Multithreaded Programming (Level 3)............. 15-8
A Preparation............................................................................... 15-8
GEN non Task 1 – Creating the PrintMe Class ................................... 15-8
Task 2 – Creating the TestThreeThreads Class................ 15-9
Task 3 – Compiling the TestThreeThreads Class .......... 15-10
Task 4 – Running the TestThreeThreads Program ....... 15-10
Exercise Summary.......................................................................... 15-11
Networking ......................................................................................16-1
Objectives ......................................................................................... 16-1
Exercise: Creating a Socket Client (Level 1) ................................. 16-2
Preparation............................................................................... 16-4
Task 1 – Modifying the ChatClient Class ......................... 16-4
Task 2 – Compiling the ChatClient Class ......................... 16-4
Task 3 – Running the ChatRoomPrj Project........................ 16-4
Exercise: Creating a Socket Client (Level 2) ................................. 16-6
Preparation............................................................................... 16-6
Task 1 – Modifying the ChatClient Class ......................... 16-6
xv
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
LabPreface
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Lab Goals
Upon completion of this workbook, you should be able to:
s a
Write a Java™ technology program using the fundamental language
● ) h a
o m
ilฺc statements
elements: primitive types, reference types, arithmetic operators,
a
m ideฺ
relational operators, conditional statements, and iterative
g u
@object-oriented
Write a Java technology program using good
●
1 1 t G
programming concepts and principles:
2 u d en inheritance,
02 encapsulation,
interfaces, polymorphism, object
i n t 9 S t
association, and multiplicity in
associations
( sa this
Write a robust Java
●
R AN u seprogram using exception handling,
technology
LT seandtoconcurrency control
generic collections,
E
O
Write
B Java
a richic e ntechnology program using the graphical user
●
Einterface l
N le(GUI) application programming interfaces (APIs),
R rab
O finput/output
O M s e (I/O) APIs, and networking APIs
A R -tran
N on This workbook presents the lab exercises for each module of the Student
GE n Guide.
Lab Preface-xvii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Performing the Exercises
Conventions
The following conventions are used in this course to represent various
training elements and alternative learning resources.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Typographical Conventions
Courier is used for the names of commands, files, directories,
programming code, and on-screen computer output; for example:
Use ls -al to list all files.
system% You have mail.
s a
Courier is also used to indicate programming constructs, such as class
) h a
names, methods, and keywords; for example:
c o m
il ฺ
The getServletInfo method is used to get authorainformation.
The java.awt.Dialog class contains Dialog g m i d eฺ
1 1 @ t Gu
constructor.
02numbersd n
ethat
Courier bold is used for characters9and
t 2 t u you type; for
n S
example:
( sai this
To list the files inA
R
this
u se type:
N directory,
# ls
E LT se to
O B en
Courier
E N le islicalso used for each line of programming code that is
bold
R rabin a textual description; for example:
Oreferenced
O M
n s f1e import java.io.*;
N AR n-tra 2 import javax.servlet.*;
GE no 3 import javax.servlet.http.*;
Notice the javax.servlet interface is imported to allow access to its life cycle
methods (Line 2).
Palatino italics is used for book titles, new words or terms, or words that
you want to emphasize; for example:
Read Chapter 6 in the User’s Guide.
These are called class options.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Additional Conventions
Java programming language examples use the following additional
conventions:
● Method names are not followed with parentheses unless a formal or
actual parameter list is shown; for example:
“The doIt method...” refers to any method called doIt.
s a
“The doIt() method...” refers to a method called doIt that takes ) h a
o m
ilฺc ฺ
no arguments.
Line breaks occur only where there are separationsm a e
●
@ g (commas),
u idcode
1 1
conjunctions (operators), or white space in the code.
t G
Broken is
indented four spaces under the starting
9 2 02code.uden
●
a i
If a command used in the Solaris™
i s St System (Solaris OS) is
nt Operating
s in the
different from a command(used th Microsoft Windows platform,
both commands are A N
shown; for e
usexample:
T R
L Solaris t o
If working in
B Ethe
e n se OS
$ cd
E NO lic
$SERVER_ROOT/bin
l e
M ORIf working
e r a b in Microsoft Windows
R sf cd %SERVER_ROOT%\bin
O ranC:\>
E NA on-t
G n
Lab 1
Getting Started
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to:
● Diagnose simple compilation and runtime errors s a
Create a test program for an existing class ) h a
●
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 1-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Exploring Java™ Program Errors
Preparation
No preparation is needed for this exercise.
s a
Tool Reference – Tool references used in this exercise: ) h a
c o m
● Java Development: Java Classes: Opening Java Classes ฺ
ail eฺ
g m
Java Development: Java Classes: Modifying Java Classes: id
Compiling
●
@ G u
Java Classes
0 2 11 ent
●
n t 9 2
Java Development: Java Classes: Modifying
S t ud Classes: Executing
Java
Java Programs
( sai this
R u se
AinNthe TestProject
For this exercise, youT
L work
e t o project in the
BE ens
exercises/01_intro/exercise1
O
directory.
E N le lic
M OR ferab – The demonstration
Demonstration for this exercise can be found in the
ns
1 demos/01_intro/exercise1 directory.
2 RO r a
A t
G EN3 non-
Task – Correcting Compilation and Runtime Errors
In this task, you are presented with four Java programs that contain
errors. The errors can be either compilation or runtime errors. Your job is
to diagnose and fix those errors so the programs will execute.
Figure 1-1 shows the definition of the Account class using a Unified
Modeling Language (UML) Class diagram.
Account
«constructors»
+Account(initBalance:double)
s a
«methods»
+getBalance():double ) h a
c o m
+deposit(amt:double):void
+withdraw(amt:double):void ฺ
ail eฺ
g m id
@ G u
Figure 1-1 Banking Account Class
0 2 11 ent
t 9 2 t u d
n S
( sai sections:
This exercise contains the following
t h is
“Task 1 – Copying
●
R AN se Class”
the Account
u
“Task 2 E
● LT sethetoTestAccount Class”
– Creating
O B3 – Compiling
e n the TestAccount Class”
“Task l i c
EN
●
R EN Copying
Classes:
b l e Java Classes
M O2. fCopy
e ra the pre-provided Account.java source file from the
A RO -trans resources/01_intro/exercise2 directory to the source
GEN non package of the BankPrj project.
2. Edit the source file for the TestAccount class to add a main
method. The main method of the TestAccount class creates an
Account object with an initial balance of 100. It deposits 50 to and
then withdraws 147 from the Account object. Finally, it must print
out the balance of the Account object to the standard output stream.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
hints.
s a
h a
Preparation m )
ฺ c o
a il
No preparation is needed for this exercise. g m i d eฺ
1 1 @ t Gu
2 2 den
in0this exercise:
Tool Reference – Tool references used
i n t 9 S tu
a thisProjects: Creating Projects
Java Development: Java(sApplication
●
●
R
Java Development:AN u se Copying Existing Resources
Java Classes:
E LT seJavatoClasses: Creating Java Classes
●
O B en
Java Development:
E Java
●
l e lic
N Development: Java Classes: Modifying Java Classes: Compiling
R
O fera Java b
Classes
M
A RO -trans Java
● Development: Java Classes: Modifying Java Classes: Executing
t 9 2 t u d
n S
( sai thdirectory
2. Copy the pre-provided Account.java
issource file from the
to the source
ANproject. se
resources/01_intro/exercise2
R
package of the BankPrj u
E LT se to
O B en
N le lthe
Task 2 – Creating
E ic TestAccount Class
M OR ferab
A nstask, you complete the following steps to create a new
RO -Intrathis
G EN non TestAccount Java class.
Tool Reference – Java Development: Java Classes: Creating Java Classes
1. Create a Java class with the following characteristics:
Class Name: TestAccount
Project: BankPrj
Location: Source Packages
Package: default package
2. Add the main method.
3. Declare a variable in the main method. The variable has a type of
Account and a name of acct. Initialize the variable by creating an
instance of the Account class with an initial balance of 100.
s a
h a
Preparation m )
ฺ c o
a il
No preparation is needed for this exercise. g m i d eฺ
1 1 @ t Gu
Tool Reference – Tool references used in 2 02exercise:
this u d en
i n t 9 S t
a i s
(s e thProjects: Creating Projects
Java Development: Java Application
●
N us Copying Existing Resources
A Classes:
Java Development:RJava
●
T t o
B EL nJava
Java Development:
● seClasses: Creating Java Classes
e
O lic Java Classes: Modifying Java Classes: Compiling
NDevelopment:
E
Java
●
RJava Classes
b le
O
M sfer a
O
R -tranJava● Development: Java Classes: Modifying Java Classes: Executing
A
G EN non Java Programs
t 9 2 t u d
n S
( sai this directory
2. Copy the pre-provided Account.java source file from the
to the source
package of the R A N
resources/01_intro/exercise2
u s e
project.
L T BankPrjt o
B E nse
Task 2 E–N
O licethe TestAccount Class
Creating
O R rable
O M sfe
A R -traInnthis task, you complete the following steps to create a new
GEN non TestAccount Java class.
Tool Reference – Java Development: Java Classes: Creating Java Classes
1. Create a Java class with the following characteristics:
Class Name: TestAccount
Project: BankPrj
Location: Source Packages
Package: default package
2. Add the main method to the TestAccount class:
public class TestAccount {
public static void main(String[] args) {
// code here
}
}
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 2
Object-Oriented Programming
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to:
● Use the Java API documentation to research a class s a
Explore information hiding and encapsulation ) h a
●
c o m
Use packages to organize your classes
● ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 2-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Using the Java API Documentation
Preparation
You must have a web browser window open.
s a
) h a
Task – Using the Java API Documentation m
ฺ c o
m ail eฺ
g
Complete the following steps to use the Java API documentation:
@ u id
n t G
116 APIeSpecification
1. Open the Java™ Platform, Standard Edition
2 0 2 d
Web
page in the browser.
i n t9 Stu
( sa this
R se Platform SE 6 can be found at
AN foruJava
LT se to
Note – The API documentation
E
http://java.sun.com/javase/6/docs/api.
B en
O lic package in the package list in the upper-left
N the java.text
E
2. Select l e
M ORcorner
e r a b
panel of the API frameset.
R sf the NumberFormat class in the class list in the lower-left panel.
O 3.ranSelect
A t
G EN non- 4. Read about the class in the top part of the documentation window
on the right panel of the frameset. Review the format and parse
methods.
this version, you create an Account class with public data members. You
will then create a test program that demonstrates the danger of using the
public data directly.
Figure 2-1 shows the UML class diagram of the Account class that you
will create in this exercise. This class will have one public data member
(or instance variable), called balance, that maintains the monetary value
of the customer’s bank account.
Account
s a
+balance : double ) h a
c o m
«constructors» ฺ
ail eฺ
+Account(initBalance:double)
g m id
@ G u
Figure 2-1 UML Class Diagram of Account
0 2 11WitheNo
n t Hiding
n t 9 2
S t ud
i applies
sathat is to the Account class: The
(
There is only one business rule t h
A
balance of the bank account
R u sego below zero. In this exercise, you will
Nmust never
LT se class
discover that the Account
E to cannot ensure this business rule.
O B en
N lecontains
This exercise
E lic the following sections:
M OR f“Task
e
● rab1 – Deleting the Account Class”
A RO -trans “Task 2 – Creating the Account Class”
●
Preparation
No preparation is needed for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
After creating the Account class, add an instance variable balance and
a constructor according to the UML diagram in Figure 2-1. Initialize the
balance instance variable with the parameter of the constructor.
R u
●
E LT se to
Java Development: Java
●
O B enJava Classes: Modifying Java Classes: Compiling
Java Development:
E
JavaNClassesle lic
M ORJavafeDevelopment:
● rab Java Classes: Modifying Java Classes: Executing
O s
R -tranJava Programs
A
G EN non For this exercise, you work in the BankPrj project in the projects
directory.
code snippets.
E ●Java
l e lic
N Development: Java Classes: Modifying Java Classes: Compiling
R
O fera Java b
Classes
M
A RO -trans Java
● Development: Java Classes: Modifying Java Classes: Executing
For this exercise, you work in the BankPrj project in the projects
directory.
A RO -trans
N on
GE Taskn 3 – Creating the TestAccount2 Class
In this task, you complete the following steps to create a Java class named
TestAccount2:
1. Create the TestAccount2 class with the following characteristics:
Class Name: TestAccount2
Project: BankPrj
Location: Source Packages
Package: default package
O RE rable
O M 5s–feRunning the TestAccount2 Program
Task
A R -tran
GEN non In this task, you run the TestAccount2 program.
methods to manipulate the balance. You then use the test program that
you created in Lab 1 to test that the business rule (balance must not fall
below zero) is satisfied.
Figure 2-2 shows the UML class diagram of the Account class that you
create. This design for the Account class hides the instance variable,
balance, and supplies public methods to manipulate the account balance.
The deposit method adds money to the account. The withdraw method
removes money from the account. The getBalance method returns the
current value of the balance instance variable.
s a
) h a
Account
c o m
-balance : double
ฺ
ail eฺ
g m id
@ G u
11 ent
«constructors»
+Account(initBalance:double)
0 2
«methods»
n t 9 2
S t ud
+getBalance():double
( s ai this
+deposit(amt:double):void N
R A u se
LT se to
+withdraw(amt:double):void
E
B Class nDiagram of Account With Information Hiding
Figure 2-2 UML
O l i c e
R EN ble
M O ferathere is still one business rule that must be maintained: The
Remember,
A t r nsof the bank account must never go below zero. This business rule
RO -balance
a
G EN non should be enforced in the withdraw method.
This exercise contains the following sections:
● “Task 1 – Modifying the Account Class”
● “Task 2 – Modifying the TestAccount Class”
● “Task 3 – Compiling the TestAccount Class”
● “Task 4 – Running the TestAccount Program”
Preparation
There is no preparation for this exercise.
For this exercise, you work in the BankPrj project in the projects
directory.
O M sfe
A R -tran
GEN noTask
n 3 – Compiling the TestAccount Class
In this task, you compile the TestAccount class and the Account class.
The 150 withdraw command did not take effect, because it would have
made the balance drop below zero. However, the Account object did not
tell program that the withdraw command failed, it ignored the command.
You will fix this problem in future exercises.
Preparation s a
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
Tool Reference – Tool references used in this2
0 11 ent
exercise:
t 9 2
Java Development: Java Classes:nModifying S t ud Classes: Compiling
Java
sai this
●
Java Classes (
ANClasses:
Java Development:RJava u seModifying Java Classes: Executing
LT se to
●
Java Programs E
B en
O
N leyou licwork in the BankPrj project in the projects
E
For this exercise,
M OR ferab
directory.
A RO -trans
G EN non Demonstration – The demonstration for this exercise can be found in the
1 demos/02_OOP/exercise3 directory.
2
3
3. Add the withdraw method that takes an amount (of type double)
and subtracts that amount from the balance. Save the new balance in
the instance variable.
This operation might set the balance to a value below zero if the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
amount to withdraw is larger than the current balance. You must use
a conditional statement to verify that the amount is not greater than
the balance before doing the subtraction. The conditional statement
looks like the following:
if ( <boolean_test> ) {
<statement_when_true>*
} else {
<statement_when_false>*
}
4. Add the getBalance method to return the balance instance s a
variable. ) h a
c o m
ฺ
ail eฺ
Task 2 – Modifying the TestAccount Class g m id
@ G u
0 2 11 ent
9
In this task, you complete the following
t d the TestAccount
2 steps totumodify
n S
class:
( sai this
1. Change the amount
R seto the deposit method to 47.0.
ANin theucall
T eintothe call to the withdraw method to 150.0.
Lamount
2. Change the E
B ens
O
N le lic
E
M OR
Task
f r a b
3 – eCompiling the TestAccount Class
A RO -trans
GEN non In this task, you compile the TestAccount class and the Account class.
Task 4 – Running the TestAccount Program
In this task, you run the TestAccount program. The output should be
similar to the following:
Final account balance is 147.0
code snippets.
s a
h a
Preparation m )
ฺ c o
a il
There is no preparation for this exercise. g m i d eฺ
1 1 @ t Gu
Tool Reference – Tool references used 2in u en
02this exercise:
d
i n t 9 S t
Java Development: Java
● a
(sClasses: i s
thModifying Java Classes: Compiling
Java Classes A N us e
T R t o
L seJava Classes: Modifying Java Classes: Executing
●
B E
Java Development:
n
O
Java Programs
l i c e
R EN ble
M e raexercise, you work in the BankPrj project in the projects
OFor fthis
A ns
RO -tradirectory.
G EN non Demonstration – The demonstration for this exercise can be found in the
1 demos/02_OOP/exercise3 directory.
2
3
2. Add the deposit method that takes an amount (of type double) and
adds that amount to the balance. Save the new balance in the
balance instance variable.
public void deposit(double amt) {
balance = balance + amt;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
}
3. Add the withdraw method that takes an amount (of type double)
and subtracts that amount from the balance. Save the new balance in
the balance instance variable.
public void withdraw(double amt) {
if ( amt <= balance ) {
balance = balance - amt;
}
} a
4. Add the getBalance method to return the balance instance ) h
as
variable. c o m
ฺ
ail eฺ
public double getBalance() {
g m id
return balance; @ G u
}
0 2 11 ent
n t 9 2
S t ud
( s ai this
Task 2 – Modifying theNTestAccount s e Class
A u
L TR e to
In this task,B E complete
you n s the following steps to modify the TestAccount
class: N O lic e
E l e
M O1.R fChange
e rab the amount in the call to the deposit method to 47.0.
A RO -trans
acct.deposit(47.0);
GEN non 2. Change the amount in the call to the withdraw method to 150.0.
acct.withdraw(150.0);
Figure 2-3 shows a UML diagram of the packages that you will create in
this exercise. The Account class is placed in the com.mybank.domain
package and the TestAccount class is placed in the com.mybank.test
package.
com.mybank
test domain s a
) h a
c o m
TestAccount
ฺ
ail eฺ
Account
-balance : double m
@ g u id
+main(args:String[])
11 ent
«constructors» G
0 2
n t 2
S t ud
+Account(initBalance:double)
9
( sai +getBalance():double
t h is
«methods»
R AN use+deposit(amt:double):void
E LT se to +withdraw(amt:double):void
O B en
E N le lic
M OR 2-3
Figure
e r a b Package Structure of the Banking Project
The
R O ransf
A t
G EN non-This exercise contains the following sections:
● “Task 1 – Creating the Java Packages”
● “Task 2 – Moving and Modifying the Account Class”
● “Task 3 – Moving the TestAccount Class”
● “Task 4 – Compiling the TestAccount Class”
● “Task 5 – Running the TestAccount Program”
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
package com.mybank.domain;
n t 9 2
S t ud
sai this
import com.mybank.domain.Account;
(
R AN use
Task 4 – Compiling LTthesTestAccount
e to Class
E
B en
In this E
O lic the TestAccount class and the Account class.
N youlecompile
task,
M OR ferab
O rans
RTask
A t5 – Running the TestAccount Program
G EN non-
In this task, you run the TestAccount program. The code has not
changed, so the output should be similar to the following:
Final account balance is 147.0
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 3
Objectives
Upon completion of this lab, you should be able to:
● Explore reference variable assignment s a
Use a reference variable to encode an object association ) h a
●
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 3-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Investigating Reference Assignment
Figure 3-1 shows a class diagram for the MyPoint class that is provided in
the exercise directory. Notice that the instance variables, x and y, are both
public so you can access these data members in your test program
directly. Also, the toString method is used when you print the object
using the System.out.println method.
MyPoint
+x : int
s a
+y : int
) h a
+toString() : String
c o m
il ฺ
Figure 3-1 UML Class Diagram for the MyPointgClass ma ideฺ
1 1 @ t Gu
02explores
d n references.
eobject
9 2
Your task is to create a test program that
u
a i nt is St
(s e sections:
This exercise contains the following
N th
T
“Task 1 – CreatingR t o us
A the TestMyPoint Class”
●
L e
E ns the TestMyPoint Class”
“TaskB
N
●
O l i ce
2 – Compiling
O RE “Task
●
a b 3le– Running the TestMyPoint Program”
O M sfer
A - t an
R Preparation
r
G EN non
No preparation is needed for this exercise.
G EN non variables.
Figure 3-2 shows the UML class diagram of the Customer class and its
relationship to the Account class. This relationship can be read as: A
customer has one account.
com.mybank.domain
has-a 1
Customer Account
-firstName : String s a
-lastName : String
-balance : double
) h a
-account : Account
c o m
«constructors»
ฺ
ail eฺ
+Account(initBalance:double)
«constructors»
«methods»
g m id
+Customer(f:String, l:String)
@ G u
11 ent
+getBalance():double
«methods»
0 2
+deposit(amt:double):void
+getFirstName():String
n t 9 2 t ud
+withdraw(amt:double):void
S
sai this
+getLastName():String
+getAccount():Account (
+setAccount(acct:Account):void
R AN use
E LT se to
O
Figure 3-2 BUML eClass
n Diagram for the Customer Class
l i c
R EN ble
M e ra contains the following sections:
OThis fexercise
A RO -trans “Task 1 – Creating the Customer Class”
EN non
●
Preparation
No preparation is needed for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Preparation s a
) h a
c o m
No preparation is needed for this exercise. ฺ
ail eฺ
g m id
@ G u
Tool Reference – Tool references used in this2
0 11 ent
exercise:
t 9 2 Java
Java Development: Java Classes:nCreating S t udClasses
sai Copying
●
(
Java Development: Java Classes: t h is Existing Resources
ANClasses: seModifying Java Classes: Compiling
●
R u
●
E LT se to
Java Development: Java
B en
Java Classes
O
E
Java
●
l e lic Java Classes: Modifying Java Classes: Executing
NDevelopment:
M ORJavafePrograms
rab
A RO -For
t r ns exercise, you work in the BankPrj project in the projects
athis
G EN non directory.
Demonstration – The demonstration for this exercise can be found in the
1 demos/03_types/exercise2 directory.
2
3
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
s a
h a
Preparation m )
ฺ c o
a il
No preparation is needed for this exercise. g m i d eฺ
1 1 @ t Gu
2 2 den
in0this exercise:
Tool Reference – Tool references used
i n t 9 S tu
a tCreating
Java Development: Java(sClasses:
● h is Java Classes
●
R AN
Java Development: u se Copying Existing Resources
Java Classes:
E LT seJavatoClasses: Modifying Java Classes: Compiling
●
O B en
Java Development:
E N le lic
Java Classes
M OR fJava
●
e r b
aDevelopment: Java Classes: Modifying Java Classes: Executing
s a
Task 4 – Running the TestBanking Program h a
m )
ฺ c o
ail should
In this task, you run the TestBanking program. The output
m eฺ be
similar to the following: g
@ t Gu i d
1 1
Creating the customer Jane Smith.02
2 u d en
Creating her account with a 500.00
i 9
nt is St
balance.
Withdraw 150.00 a
(s e th
Deposit 22.50
A N us
Withdraw 47.62 TR o
EL nJane] t
B
Customer [Smith,
e se has a balance of 324.88
E NO le lic
M OR ferab
A RO -trans
GEN non
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications
●
R AN use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR_____________________________________________________________
e r a b
R O ransf
A t
G EN non-
Lab 4
Objectives
Upon completion of this lab, you should be able to:
● Use a simple for loop s a
Using conditional statements in business logic ) h a
●
c o m
ฺ
ail operation
(Optional) Use nested loops to implement a string search
eฺ
●
g m i d
1 1 @ t Gu
9 2 02 uden
a i nt is St
N (s e th
T R A
t o us
B EL nse
N O lice
O RE rable
O M sfe
A R -tran
GEN non
Lab 4-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Using Loops and Branching Statements
Create a program that loops from 1–50 and prints each value on a
separate line. Also print foo for every multiple of three, bar for every
multiple of five, and baz for every multiple of seven. For example:
Preparation
There is no preparation required for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Hints
s a
These hints might help you to solve this exercise: ) h a
c o m
ฺ
a l print
Use the System.out.print method to print a string or ivalue
eฺ
●
without printing a new line character. You can use g m
multiplei d
methods to print a single line of text. You can1 @ G uprintln
use a single
method, with no arguments, to print a0new
1 en t
2 linedcharacter.
9 2 u
●
a i
The % operator calculates an integer
i s St
nt remainder.
N (s e th
T R A
t o us
B EL nse
N O lice
O RE rable
O M sfe
A R -tran
G EN non
Figure 4-1 shows the UML class diagram of the Banking Project. The
Account class now includes a design change to the deposit and
withdraw methods; these methods must now return a boolean value to
indicate the success (true) or failure (false) of the operation.
com.mybank.domain
s a
has-a 1
) h a
Customer
c o mAccount
-firstName : String -balance : double ฺ
ail eฺ
-lastName : String
g m id
«constructors»
@ G u
11 ent
-account : Account
+Account(initBalance:double)
0 2
«constructors»
n t 9 2
«methods»
S t ud
sai +deposit(amt:double):boolean
+Customer(f:String, l:String)
«methods» ( t is
+getBalance():double
h
A N use+withdraw(amt:double):boolean
+getFirstName():String
+getLastName():String R
LT se to
+getAccount():Account E
B en
O
N le lic
+setAccount(acct:Account):void
E
R rab
M OFigurefe4-1 UML Class Diagram of Banking Project
O n s
N AR n-tra
GE no This exercise contains the following sections:
● “Task 1 – Modifying the Account Class”
● “Task 2 – Deleting the Current TestBanking Class”
● “Task 3 – Copying the TestBanking Class”
● “Task 4 – Compiling the TestBanking Class”
● “Task 5 – Running the TestBanking Program”
Preparation
There is no preparation required for this exercise.
For this exercise, you work in the BankPrj project in the projects
directory.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
For this exercise, you work in the BankPrj project in the projects
directory.
For this exercise, you work in the BankPrj project in the projects
directory.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
Note – There are several advanced exercises in this course. These exercises
are optional and should only be attempted if you completed all of the s a
previous exercises for this module. ) h a
c o m
ฺ
ail eฺ
g m id
Preparation @ G u
0 2 11 ent
n
There is no preparation requiredifor S tud
2 exercise.
t9this
( sa this
N usused
Areferences e in this exercise:
Tool Reference – ToolR
LT se to
E
B en Java Application Projects: Opening Projects
Java Development:
●
O lic
N Development:
E Java
R Java
●
b l e Java Classes: Modifying Java Classes: Compiling
O
M sfer aClasses
O
R -tran Java Development: Java Classes: Modifying Java Classes: Executing
A ●
Hints
These hints might help you to solve this exercise.
● Use the charAt(int index) method in the String class to retrieve
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
a specific character from a string; the index starts with zero. For
example. "cat".charAt(0) is ‘c’, "cat".charAt(1) is ‘a’, and
"cat".charAt(2) is ‘t’.
● The length method returns the number of characters in the string;
for example, "cat".length() is 3.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications
●
R AN use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR_____________________________________________________________
e r a b
R O ransf
A t
G EN non-
Lab 5
Arrays
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to:
● Declare, create, and manipulate one-dimensional primitive arrays s a
Use an array to represent a one-to-many object relationship ) h a
●
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 5-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1 – Using Primitive Arrays (Level 2)
Preparation
s a
) h a
There is no preparation for this exercise.
c o m
ฺ
ail eฺ
Tool Reference – Tool references used in this exercise:gm id
@ G u
Java Development: Java Application Projects:
●
0 2 11Opening
e n t Projects
t 9 2 Java
Java Development: Java Classes:nCreating S t udClasses
sai Modifying
●
(
Java Development: Java Classes: t h is Java Classes: Compiling
AN use
●
Java Classes R
LT Java to
E s e
O B licen
Java Development:
● Classes: Modifying Java Classes: Executing
JavaN Programs
O RE rable
O e
MFor thissfexercise, you work in the ArrayProject project in the
tra n
AR n-exercises/05_arrays/exercise1 directory.
E N
G no Demonstration – The demonstration for this exercise can be found in the
1 demos/05_arrays/exercise1 directory.
2
3
Hint
The printArray support method might help you to solve this exercise, as
follows:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a in is S
System.out.println(Arrays.toString(array1));
N ( e th
T R A
t o us
B EL nse
N O lice
O RE rable
O M sfe
A R -tran
G EN non
Preparation
s a
) h a
There is no preparation for this exercise.
c o m
ฺ
ail eฺ
g
Tool Reference – Tool references used in this exercise: m id
@ G u
● Java Development: Java Application 2
0 11 eOpening
Projects: n t Projects
t 9 d Classes
2CreatingtuJava
●
n
Java Development: Java Classes:
ai his S
Java Development: Java(s
Classes:tModifying Java Classes: Compiling
●
A N s e
T e to u
Java Classes R
L
●
O BE ens Java Classes: Modifying Java Classes: Executing
Java Development:
E N le lic
Java Programs
R rab
OFor
O M
n s fe exercise, you work in the exercises/05_arrays/exercise1
this
N AR n-tradirectory.
GE no Demonstration – The demonstration for this exercise can be found in the
1 demos/05_arrays/exercise1 directory.
2
3
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Figure 5-1 shows the UML class diagram of the Banking Project. Your
assignment is to create the Bank class. A bank object keeps track of an
association between itself and its customers. You implement this
one-to-many association with an array of customer objects. You will also
need to keep an integer instance variable that keeps track of how many
customers currently exist in the bank.
s a
com.mybank.domain
) h a
c o m
Bank
ฺ
ail eฺ
g m id
@ G u
11 ent
-customers : Customer[]
-numberOfCustomers : int
0 2
n t 9 2
S t ud
sai this
«constructors»
+Bank()
(
«methods»
+addCustomer(f:String, l:String) TR
AN use
E L se to
+getNumOfCustomers():int
O B en
N le lic
+getCustomer(index:int):Customer
E
M OR ferab
R O rans serves
A t
EN non-
has-a 1
Customer Account
0..*
G
Figure 5-1 UML Class Diagram of Banking Project
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
B
O lice
Java Development:
●
N
O REJava
●
a b le
Development: Java Classes: Copying Existing Resources
For this exercise, you work in the BankPrj project in the projects
directory.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
B
Java Development:e se Files: Deleting Files
●
O lic
NDevelopment:
E
R rable
Java
● Java Classes: Copying Existing Resources
O
M Java feDevelopment: Java Classes: Modifying Java Classes: Compiling
O n●
s
N AR n-tra Java Classes
G E no Java Development: Java Classes: Modifying Java Classes: Executing
●
Java Programs
For this exercise, you work in the BankPrj project in the projects
directory.
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 6
Class Design
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to:
● Create subclasses with inheritance and overriding of methods s a
Create a heterogeneous collection and use polymorphism ) h a
●
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 6-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Creating Bank Account Subclasses (Level 1)
SavingsAccount CheckingAccount
-interestRate : double -overdraftAmount : double
«constructors» «constructors»
+SavingsAccount(initBalance:double, +CheckingAccount(initBalance:double,
interestRate:double) overdraft:double)
+CheckingAccount(initBalance:double)
«methods»
+withdraw(amt:double):boolean
Preparation
s a
There is no preparation for this exercise. ) h a
c o m
ฺ
ail eฺ
g m
Tool Reference – Tool references used in this exercise: id
@ G u
●
0 2 11JavaeClasses
Java Development: Java Classes: Creating n t
n
2
Java Development: Other Files:t9Deleting
S t ud
Files
ai his Existing Resources
●
R u
●
E LT se to
Java Development: Java Classes:
B en
Java Classes
O
E●Java
l e lic
N Development: Java Classes: Modifying Java Classes: Executing
R
O fera Java b
Programs
M
A nsthis exercise, you work in the BankPrj project in the projects
RO -traFor
GEN non directory.
Demonstration – The demonstration for this exercise can be found in the
1 demos/06_class1/exercise1 directory.
2
3
This class must satisfy the UML diagram in Figure 6-1 on page L6-2 and
the business rules defined in the introduction to ‘‘Exercise 1: Creating
Bank Account Subclasses (Level 1)’’ on page L6-2.
Retrieving the customer Owen Bryant with his checking account with no
overdraft protection.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Retrieving the customer Tim Soley with his checking account that has
overdraft protection.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Withdraw 400.00: true
Customer [Soley, Tim] has a balance of 0.0
s a
) h a
Retrieving the customer Maria Soley with her joint checking account with
c o m
husband Tim. ฺ
ail eฺ
Deposit 150.00: true
g m id
@ G u
11 ent
Withdraw 750.00: false
Customer [Soley, Maria] has a balance of 150.0
0 2
n t 9 2
S t ud
i
sachecking isaccount behave
Jane’s savings account and Owen’s
( t h
fundamentally as a basic bank
R ANworth seoverdraft
account.
u But Tim and Maria’s joint
checking account hasT
L 500.00
e t o of protection. Tim’s
transactions dip E thatnprotection
Binto s and therefore his ending balance
is 0.00. His O
N account’sl ic e
overdraft protection level is 424.88. Finally, Maria
E
R 150.00
deposits e
blshe
into this joint account; raising the balance from 0.00
toO
Mthe balance
150.00.
f e r a
Then tries to withdraw 750.00, which fails because neither
O
R -tran s nor the overdraft protection can cover that requested amount.
A
G EN non
GE no Java Classes
● Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs
For this exercise, you work in the BankPrj project in the projects
directory.
s a h i s
super constructor. Save(the overdraftAmount
t
to the
parameter to the
A N s e
TR e to u
instance variable.
L
4. Add aB E public
second
n s constructor that takes only one argument:
N O l
initBalance. ic eCall the first constructor with the initBalance
E e
bl and use the default value 0.0 for the overdraftAmount
R parameter
O
M sfe r a
parameter.
O
R -tra5.n Override the withdraw method to use the overdraftAmount
A
GEN non variable. Here is the pseudo-code for the withdraw method:
if balance < amount
then
overdraftNeeded = amount - balance
if overdraftAmount < overdraftNeeded
then transaction fails
else
balance = 0
decrement overdraftAmount by overdraftNeeded
else
decrement balance by amount
Retrieving the customer Owen Bryant with his checking account with no
overdraft protection.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Retrieving the customer Tim Soley with his checking account that has
overdraft protection.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Withdraw 400.00: true
Customer [Soley, Tim] has a balance of 0.0
s a
) h a
c o m
Retrieving the customer Maria Soley with her joint checking account with
husband Tim. ฺ
ail eฺ
Deposit 150.00: true
g m id
@ G u
11 ent
Withdraw 750.00: false
0 2
Customer [Soley, Maria] has a balance of 150.0
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
M
O rans ● Java Classes: Copying Existing Resources
A R t
G EN non- Java ● Development: Java Classes: Modifying Java Classes: Compiling
Java Classes
● Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs
For this exercise, you work in the BankPrj project in the projects
directory.
super(initBalance);
this.interestRate = interestRate;
}
this(initBalance, 0.0);
}
5. Override the withdraw method to use the overdraftAmount
variable.
public boolean withdraw(double amount) {
boolean result = true;
if ( balance < amount ) {
double overdraftNeeded = amount - balance;
if ( overdraftAmount < overdraftNeeded ) {
s a
result = false;
) h a
} else {
c o m
balance = 0.0; ฺ
ail eฺ
overdraftAmount -= overdraftNeeded; g m id
@ G u
}
} else { 0 2 11 ent
balance -= amount;
n t 9 2
S t ud
}
( sai this
return result;
R AN use
}
E LT se to
O B en
Task R 4E–N Deleting
l e lic the Current TestBanking Class
M O ferab
s
RO -traInnthis
N A n
task, you delete the current TestBanking class in the
GE no com.mybank.test source package of the BankPrj project.
Retrieving the customer Tim Soley with his checking account that has
overdraft protection.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Withdraw 400.00: true
Customer [Soley, Tim] has a balance of 0.0
Retrieving the customer Maria Soley with her joint checking account with
husband Tim.
Deposit 150.00: true
Withdraw 750.00: false
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Figure 6-2 shows the UML class diagram of the relationships between
bank, customers, and accounts. What has changed is that a Customer
object may now have more than one account and these accounts may be
of different types, subclasses of the Account class.
com.mybank.domain s a
) h a
serves
c o m
Bank 0..* Customer
has-a
ฺ
0..*
ail eฺ
Account
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
SavingsAccount CheckingAccount
A N use
Figure 6-2 Customer R
LT With to or More Different Accounts
One
E
B en s e
N O licthe Customer class to support a heterogeneous
E
Your job is to modify
l e
M OR feofraAccount
collection b objects.
RO -This s
anexercise
A t r contains the following sections:
G EN non ● “Task 1 – Modifying the Customer Class”
● “Task 2 – Copying and Completing the CustomerReport Class”
● “Task 3 – Copying the TestReport Class”
● “Task 4 – Compiling the TestReport Class”
● “Task 5 – Running the TestReport Program”
Preparation
There is no preparation required for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
c o m
ฺ
ail eฺ
Preparation g m id
@ G u
0 2 11 ent
There is no preparation required for
n t 9
this S t ud
2 exercise.
( sai this
Tool Reference – ToolA N usused
references e in this exercise:
R
LT seJavatoPackages: Creating Java Packages
● E
B en
Java Development:
O lic
N Development:
R E ●Java
b l e Java Classes: Copying Existing Resources
M O fJava
●
e raDevelopment: Java Classes: Modifying Java Classes: Compiling
A RO -trans Java Classes
GEN non ●Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs
For this exercise, you work in the BankPrj project in the projects
directory.
handle the association with multiple accounts, just as you did in the
Exercise 2 of Lab 5. It must include the public methods:
addAccount(Account), getAccount(int), and getNumOfAccounts().
c o m
ฺ
ail eฺ
Preparation g m id
@ G u
0 2 11 ent
There is no preparation required n t
for 9this S t ud
2 exercise.
( sai this
N usused
Tool Reference – ToolAreferences e in this exercise:
R
LT seJava to Packages: Creating Java Packages
E
B en
Java Development:
●
N O lic
R E Java Development:
●
b l e Java Classes: Copying Existing Resources
For this exercise, you work in the BankPrj project in the projects
directory.
handle the association with multiple accounts, just as you did in the
Exercise 2 of Lab 5. It must include the public methods:
addAccount(Account), getAccount(int), and getNumOfAccounts().
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Figure 6-3 shows the dependencies between the class used by the
TestBatch program.
s a
TestBatch
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
AccumulateSavingsBatch
0 2 11 CustomerReport
e n t
-bank : Bank
t 9 2 -banktu: dBank
a i n i s S
«methods» s h
( e t +generateReport():void
«methods»
+doBatch():void
A N us
L T R
+setBank(bank:Bank):void
t o +setBank(bank:Bank):void
B E nse
N O lice
O RE rablSavingsAccount
e
O M sfe
A R -tran-interestRate : double
G EN non «constructors»
+SavingsAccount(initBalance:double,
interestRate:double)
«methods»
+accumulateInterest():void
Preparation
There is no preparation required for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
R O rans ================
A t
G EN non-Customer: Simms, Jane
Savings Account: current balance is 500.0
Checking Account: current balance is 200.0
CUSTOMERS REPORT
================
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications
●
R AN use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR_____________________________________________________________
e r a b
R O ransf
A t
G EN non-
Lab 7
Objectives
Upon completion of this lab, you should be able to:
● Apply static class members to resolve a design decision. s a
) h a
Create abstract classes and interfaces, and explore the polymorphic
●
o m
properties of these types of components
a ilฺc ฺ
@ gm uide
2 1 1 nt G
t 9 20 tude
s a in is S
N ( e th
T R A
t o us
B EL nse
N O lice
O RE rable
O M sfe
A R -tran
GEN non
Lab 7-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Applying Static Members to a Design (Level 1)
the concept of a bank, which contains the set of customers for the bank.
The project team has decided that this is a risky design because it would
be possible to instantiate multiple Bank objects each with the potential to
contain different sets of customers.
The design team has decided to make the Bank class a utility class. A
utility class is one that is not instantiated and all of its members are static.
Figure 7-1 shows the new design for the Bank class. Your job is to program
these changes to the Bank class and to all of the classes that use the Bank
class.
s a
) h a
c o m
com.mybank.domain ฺ
ail eฺ
g m id
@ G u
Bank
0 2 11 ent
-customers : Customer[]
t 9 2 t u d
n S
-numberOfCustomers : int
( sai this
«constructors»
R AN use
-Bank()
E LT se to
«methods»
O B en
E N le lic
+addCustomer(f:String, l:String)
OR ferab
+getNumOfCustomers():int
M
+getCustomer(index:int):Customer
A RO -trans
G EN non serves
has-a 1
Customer Account
0..*
Preparation
There is no preparation required for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
GE no the BankPrj project. All the members (both instance variables and
methods) should be changed to static, as shown in Figure 7-1 on
page L7-2. Also, move the original variable initialization code from the
constructor to either a static block or on the static variable declarations.
the concept of a bank, which contains the set of customers for the bank.
The project team has decided that this is a risky design because it would
be possible to instantiate multiple Bank objects each with the potential to
contain different sets of customers.
The design team has decided to make the Bank class a utility class. A
utility class is one that is not instantiated and all of its members are static.
Figure 7-1 on page L7-2 shows the new design for the Bank class. Your job
is to program these changes to the Bank class and to all of the classes that
use the Bank class.
s a
) h a
This exercise contains the following sections:
c o m
“Task 1 – Modifying the Bank Class”
ฺ
ail eฺ
●
m
@
“Task 2 – Modifying the CustomerReport1Class”
●
g
G uid
0 2 1 ent
●
t 9 2
“Task 3 – Deleting the Current TestReport
t u d
Class”
n S
sai thClass”
“Task 4 – Copying the TestReport
●
( is
“Task 5 – Compiling
●
R se Class”
ANthe TestReport
u
LT sthe
“Task 6 –ERunning
● e o
tTestReport Program”
B e n
E NO le lic
OR ferab
Preparation
M
A RO -trans
GEN non There is no preparation required for this exercise.
Tool Reference – Tool references used in this exercise:
● Java Development: Java Application Projects: Opening Projects
● Java Development: Other Files: Deleting Files
● Java Development: Java Classes: Copying Existing Resources
● Java Development: Java Classes: Modifying Java Classes: Compiling
Java Classes
● Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs
For this exercise, you work in the BankPrj project in the projects
directory.
the concept of a bank, which contains the set of customers for the bank.
The project team has decided that this is a risky design because it would
be possible to instantiate multiple Bank objects each with the potential to
contain different sets of customers.
The design team has decided to make the Bank class a utility class. A
utility class is one that is not instantiated and all of its members are static.
Figure 7-1 on page L7-2 shows the new design for the Bank class. Your job
is to program these changes to the Bank class and to all of the classes that
use the Bank class.
s a
) h a
This exercise contains the following sections:
c o m
“Task 1 – Modifying the Bank Class”
ฺ
ail eฺ
●
g m id
@ G u
“Task 2 – Modifying the CustomerReport
●
0 2 11 ent
Class”
●
t 9 2
“Task 3 – Deleting the Current TestReport
t u d
Class”
n S
sai thClass”
“Task 4 – Copying the TestReport
●
( is
“Task 5 – Compiling
●
R se Class”
ANthe TestReport
u
“Task 6 E
● LT sethetoTestReport Program”
– Running
O B en
E N le lic
OR ferab
Preparation
M
A RO -trans
G EN non There is no preparation required for this exercise.
Tool Reference – Tool references used in this exercise:
● Java Development: Java Application Projects: Opening Projects
● Java Development: Other Files: Deleting Files
● Java Development: Java Classes: Copying Existing Resources
● Java Development: Java Classes: Modifying Java Classes: Compiling
Java Classes
● Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs
For this exercise, you work in the BankPrj project in the projects
directory.
either B
EL block
4. Move the original
a static e n
variable initialization code from the constructor to
seor on the static variable declarations.
static { E NO le lic
M
customersO=Rnewe r a b
Customer[10];
O ransf = 0;
numberOfCustomers
R
}A t
GEN non- 5. Change the constructor to be private and remove the body of the
constructor.
private Bank() {
// this constructor should never be called
}
6. Change all methods to static.
public static void addCustomer(String f, String l) {
int i = numberOfCustomers++;
customers[i] = new Customer(f, l);
}
public static int getNumOfCustomers() {
return numberOfCustomers;
}
public static Customer getCustomer(int customer_index) {
return customers[customer_index];
}
Advanced Class Features Lab 7-9
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Applying Static Members to a Design (Level 3)
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Animal
{abstract} «interface»
Pet
#legs : int
«constructors» +getName():String
s a
#Animal(legs:int) +setName(n:String):void
) h a
«methods»
+play()
c o m
+walk():void ฺ
ail eฺ
+eat():void
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
Spider Cat ( sai this Fish
e : String
AN us-name
-name : String R
LT se to «constructors»
«constructors» E
B en
«constructors»
+Spider()
N O
+Cat(n:String)
l ic +Fish()
«methods» E
R rabl
+Cat() e «methods»
+eat():void O f e
M s«methods» +getName():String
O
R -tran +getName():String +setName(n:String):void
A
N on +play():void
G E n
+setName(n:String):void
+play():void +walk():void
+eat():void +eat():void
Preparation
There is no preparation required for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
The Pet interface must satisfy the UML diagram in Figure 7-1 on
page L7-2.
The Animal class must satisfy the UML diagram in Figure 7-1 on
page L7-2. The action methods (walk and eat) print a statement to
standard output that reflects the animal. For example, the walk method
s a
for the Animal class might say something similar to This animal walks
) h a
o
on 4 legs, where 4 is the value of the legs instance variable.
c m
l ฺ
aiPackages
g m
2. Create the Spider, Cat, and Fish classes in the Source
i d eฺ of
the InterfaceProject project to satisfy the UML
1 1 @ t Gu
diagram in
Figure 7-1 on page L7-2.
9 2 02 uden
a i nt is St
Task 3 – Creating the TestAnimals
N (s e th Class
T R A
t o us
B EL nsteps:
Complete the following se
NOtask,leyou e
liccreate the TestAnimals class with the following
1. InEthis
M ORcharacteristics:
e r a b
R sf Name: TestAnimals
O ranClass
A t
G EN non- Project: InterfaceProject
Location: Source Packages
Package: default package
2. Add the main method to create and manipulate instances of the
classes you created previously.
Start with:
Fish d = new Fish();
Cat c = new Cat("Fluffy");
Animal a = new Fish();
Animal e = new Spider();
Pet p = new Cat();
Experiment by:
● Calling the methods in each object
● Casting objects
Using polymorphism
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
O BE ens
N l–eTool
Tool Reference
E lic references used in this exercise
M ORJavafeDevelopment:
● rab Java Application Projects: Opening Projects
O s
R -tranJava Development: Java Classes: Creating Java Classes
A ●
exercises/07_class2/exercise2 directory.
2. Create the Pet interface with the following characteristics:
Class Name: Pet
Project: InterfaceProject
Location: Source Packages
Package: default package
s a
The Pet interface must satisfy the UML diagram in Figure 7-1 on
page L7-2. ) h a
c o m
ฺ
ail eฺ
Task 2 – Creating the Animal Classes@g m id
G u
0 2 11 ent
Complete the following steps:
n t 9 2
S t ud
(
1. Create the abstract Animal saiclass.this
R AN classu sewith the following characteristics:
a.
LT se to
Create the
E
Animal
O B Name:
Class e n Animal
l i c
R EN Project:
b le InterfaceProject
O a
M sfer Location: Source Packages
O
R -tran
A
EN non
Package: default package
G b. Declare a protected integer instance variable called legs, which
records the number of legs for this animal.
c. Define a protected constructor that initializes the legs instance
variable.
d. Declare an abstract method eat.
e. Declare a concrete method walk that prints out something
about how the animals walks (include the number of legs).
Extends: Animal
Location: Source Packages
Package: default package
b. Define a no-arg constructor that calls the superclass
constructor to specify that all spiders have eight legs.
c. Implement the eat method.
3. Create the Cat class.
s a
a. Create the Cat class with the following characteristics: ) h a
c o m
Class Name: Cat ฺ
ail eฺ
g m id
Project: InterfaceProject
@ G u
Extends: Animal
0 2 11 ent
n t 9 2
S t ud
Implements: Pet
( s ai this
Location: SourceNPackages
R A u se
Package: L
E
default to
T e package
B e s
ninclude a String instance variable to store the
O
b. This class must
l i c
R ENnameb l e the pet.
of
M ra a constructor that takes one String parameter that
O c. feDefine
A RO -trans specifies the cat’s name. This constructor must also call the
G EN non superclass constructor to specify that all cats have four legs.
d. Define another constructor that takes no parameters. Have this
constructor call the previous constructor (using the this
keyword) and pass an empty string as the argument.
e. Implement the Pet interface methods.
f. Implement the eat method.
4. Create the Fish class.
a. Create the Fish class with the following characteristics:
Class Name: Fish
Project: InterfaceProject
Extends: Animal
Implements: Pet
Location: Source Packages
Package: default package
b. This class must include a String instance variable to store the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
g m id
@ G u
Preparation
0 2 11 ent
n t 9 2
S t ud
( saifor this
There is no preparation required
t h isexercise.
R AN use
Tool Reference L
E –T to used in this exercise:
Tool references
e
s
B en Java Application Projects: Opening Projects
● O
N le lic
Java Development:
E
M OR fJava
●
e
b
raDevelopment: Java Classes: Creating Java Classes
A RO -trans Java
● Development: Java Classes: Modifying Java Classes: Compiling
exercises/07_class2/exercise2 directory.
2. Create the Pet interface with the following characteristics:
Class Name: Pet
Project: InterfaceProject
Location: Source Packages
Package: default package
s a
The Pet interface must satisfy the UML diagram in Figure 7-1 on
page L7-2. ) h a
c o m
public interface Pet { ฺ
ail eฺ
public String getName(); g m id
@ G u
public void setName(String n);
0 2 11 ent
ud
public void play();
t 9 2 t
} n S
( sai this
A N use
Task 2 – Creating L R
the
T Animal to Classes
E
B en s e
O lic steps:
Nthe following
E
Complete
R rab l e
M1.O Create
f e the Animal class.
O s
R -trana. Create the Animal class with the following characteristics:
A
N on
GE n Class Name: Animal
Project: InterfaceProject
Location: Source Packages
Package: default package
public abstract class Animal {
// more code here
}
b. Declare a protected integer instance variable called legs, which
records the number of legs for this animal.
protected int legs;
c. Define a protected constructor that initializes the legs instance
variable.
s a
// Demonstrate different implementations of an interface
f.play(); ) h a
c o m
c.play(); ฺ
ail eฺ
g m id
// Demonstract virtual method invocation @ G u
e.eat();
0 2 11 ent
e.walk();
n t 9 2
S t ud
( sai this
AN use
// Demonstrate calling super methods
a.walk(); R
LT se to
}
E
B en
}
O
N le lic
E
M OR ferab
Task
O 4ra–nCompiling
s the TestAnimals Class
R
E NA on-t
G n In this task, you compile the TestAnimals class.
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 8
Objectives
Upon completion of this lab, you should be able to create an application
exception and apply the declare-or-handle rule to the account classes.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 8-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise: Creating Your Own Exception (Level 1)
Figure 8-1 shows UML class diagram of this new design. In UML
parlance, the «send» dependency indicates that the method on the source
operation (the withdraw method) may throw an OverdraftException.
s a
) h a
com.mybank.domain
c o m
ฺ
ail eฺ
Account
«exception»g
m id
@
1 nt G u
#balance : double
2 1java.lang}
Exception
«constructors»
t 9 2 0
{from
t u de
a i s S
in«constructors»
#Account(initBalance:double)
s h
«methods»
A N ( use+Exception(msg:String)
t
+getBalance():double
+deposit(amt:double):void EL
TR e to «methods»
O B ens +getMessage():String
+withdraw(amt:double):void
l i c
R EN ble «send»
M O fera
R O a n s
CheckingAccount
«exception»
NA on-tr : double
OverdraftException
G E-overdraftAmount
n -deficit : double
«constructors»
«constructors»
+CheckingAccount(initBalance:double,
overdraft:double) +OverdraftException(msg:String,
deficit:double)
+CheckingAccount(initBalance:double)
«methods»
«methods»
«send» +getDeficit():double
+withdraw(amt:double):boid
Preparation
There is no preparation required for this exercise.
following characteristics:
Class Name: OverdraftException
Project: BankPrj
Extends: Exception
Location: Source Packages
Package: com.mybank.domain
This class must satisfy the UML diagram in Figure 8-1 on page L8-2.
s a
) h a
c o m
Task 2 – Modifying the Account Class ฺ
ail eฺ
g m id
@ G u
In this task, you modify the Account class source
0 2 11file einnthe
t
com.mybank.domain source package of the
n t 9 2 BankPrj
S t udL8-2.
project. This class
s a i
must satisfy the UML diagram in Figure 8-1
i on
s page In particular,
N ( usshould
the deposit and withdraw methods h
e t not return a boolean flag.
A
L TR e to
Task 3 – Modifying
O BE thee n sCheckingAccount Class
E N le lic
InO
R rayou b modify the CheckingAccount class source file in the
M e
this task,
sf
O com.mybank.domain
A R t r a n source package of the BankPrj project. This class
M
O rans ● Java Classes: Copying Existing Resources
A R t
G EN non- Java ● Development: Java Classes: Modifying Java Classes: Compiling
Java Classes
● Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs
For this exercise, you work in the BankPrj project in the projects
directory.
withdraw method so that it does not return a value (that is, void). Declare
that this method throws the OverdraftException. Modify the code to
throw an exception when the overdraftProtection amount is not
sufficient to cover the deficit; use the message Insufficient funds for
overdraft protection for this exception.
GE no Java Classes
● Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs
For this exercise, you work in the BankPrj project in the projects
directory.
Modify the withdraw method so that it does not return a value (that is,
void). Declare that this method throws the OverdraftException. Modify
the code to throw an exception if necessary. There are two cases that need
to be handled. First, there is a deficit with no overdraft protection; use the
message No overdraft protection for this exception. Second, the
overdraftProtection amount is not sufficient to cover the deficit; use
the message Insufficient funds for overdraft protection for this
exception.
protection",
overdraftNeeded);
} else {
balance = 0.0;
overdraftAmount -= overdraftNeeded;
}
} else {
balance = balance - amount;
}
s a
}
) h a
c o m
ฺ
ail eฺ
Task 4 – Deleting the Current TestBanking g mClass id
@ G u
0 2 11classenintthe
92BankPrjtudproject.
In this task, you delete the current TestBanking
com.mybank.test source packageiof n tthe S
( sa this
R AN use
Task 5 – Copying the to
LT TestBanking
e Class
E
B en s
In this E
O licthe TestBanking.java file from the
N youlecopy
task,
M OR ferab
resources/08_except directory to the com.mybank.test source
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 9
Objectives
Upon completion of this lab, you should be able to:
● Use a generic collection to manage a one-to-many association s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 9-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Using Collections to Represent Association (Level 1)
Figure 9-1 shows the domain model of the Bank project with the class s a
associations: a bank serves many customers, and a customer has many ) h a
c o m
accounts. Figure 9-1 also shows the detailed design for Bank and
ฺ
ail eฺ
Customer classes that use a generic List to maintain these links.
g m id
@ G u
0 2 11 ent
com.mybank.domain
n t 9 2
S t ud
serves ( s ai 0..*this
has-a
Bank 0..* Customer N
A u s e Account
L TR e to
O BE ens
E N le lic
M OR ferab SavingsAccount CheckingAccount
A RO -trans
N on
GE n Bank Customer
-customers : List<Customer> -accounts : List<Account>
-firstName : String
«constructors»
-lastName : String
-Bank()
«methods» «constructors»
+addCustomer(f:String, l:String) +Customer(f:String, l:String)
+getNumOfCustomers():int «methods»
+getCustomer(index:int):Customer +addAccount(acct:Account)
+getNumOfAccounts():int
+getAccount(index:int):Account
Figure 9-1 Domain Model of the Bank Project with Details on the Bank
and Customer Classes
Preparation
There is no preparation for this exercise.
0 2 11exercise:
e n t
Java Development: Java Classes:
n t 9 2
Modifying
●
S t udJava Classes: Compiling
Java Classes ( sai this
R
Java Development: AN u se Modifying Java Classes: Executing
Java Classes: ●
LT se to
Java Programs
E
O B en
ForE N exercise,
this l e licyou work in the BankPrj project in the projects
R rab
Odirectory.
O M
n s fe
N AR n-traDemonstration – The demonstration for this exercise can be found in the
GE no 1 demos/09_collections/exercise directory.
2
3
n t 9 2
S t udadd method.
3. Modify the addAccount method
( s ai this to use the
A N method
4. Modify the getAccount
u s e to use the get method.
TR e to
5. Modify theLgetNumOfAccounts method to use the size method.
E
B en s
O
N le lic
Task E
M OR3 –feCompiling
rab the TestReport Class
A RO -traInnsthis task, you compile the TestReport class.
N on
GE n
Task 4 – Running the TestReport Program
In this task, you run the TestReport program. The output should be
similar to the following:
CUSTOMERS REPORT
================
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
1. Add the two import statements to include the collections classes you
will use in the Bank class.
import java.util.List;
import java.util.ArrayList;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
CUSTOMERS REPORT
================
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N lic
_____________________________________________________________
l e
M OR fe_____________________________________________________________
rab
A RO -trans
G EN non
Lab 10
I/O Fundamentals
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 10-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 11
Objectives
Upon completion of this lab, you should be able to:
● Read a data file using the Scanner API s a
Use a generic collection to manage a one-to-many association) h a
●
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 11-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Reading a Data File (Level 1)
Figure 11-1 shows the UML diagram for the DataSource class that you
create for the TestReport program.
TestReport
DataSource
s a
{from com.mybank.data}
CustomerReport
) h a
-dataFile : File
c o m
a il ฺ
«constructors»
g m i d eฺ
@ t Gu
+DataSource(dataFilePath:String)
«exception»
1 1
en
«methods»
02 {fromujava.io}
IOException
«send»
+loadData():void
9 2 d
a i n t
i s St
«read»
N (s e th
T R A
t o us
B EL nse
N O lice
O RE ble
test.dat ra
O M sfe
A t r an 11-1 The DataSource Class Loads Customer Data From a Flat
R -Figure
G EN non File
Code 11-1 shows an example of the format of the customer data file. The
first line contains an integer, which determines the number of customers
in the data file. A customer record contains the first name, last name, and
the number of accounts, separated by tab characters. Each account record
contains a single-character code that determines the type of account and
also the data in that record.
Code 11-2 shows an example of the format of the customer data file. This
data file contains four customer records. The first is for Jane Simms; Jane
has two bank accounts. The first account is a savings account, with an
initial balance of 500.00 and an interest rate of 5 percent (0.05). The second
account is a checking account with an initial balance of 200.00 and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Jane Simms 2
S 500.00 0.05
C 200.00 400.00
s a
Owen Bryant 1
) h a
C 200.00 0.00
c o m
ฺ
ail eฺ
Tim Soley 2
g m id
S 1500.00 0.05 @ G u
C 200.00 0.00
0 2 11 ent
n t 9 2
S t ud
Maria Soley 1
150.00 0.05N (s
ai this
se
S
R A u
E LT the e to
This exercise contains
B e n s following sections:
E NO 1le– Creating
“Task
● lic a data Directory”
M OR f“Task
e
● rab2 – Copying the Resource File”
A RO -trans “Task 3 – Creating the DataSource Class”
●
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
9 2 02 uden
i nt iproject
For this exercise, you work in the BankPrj
a s St in the projects
directory.
N (s e th
T R A
t o us
Demonstration –E L demonstration
The
se directory.
for this exercise can be found in the
B e n
NO le lic
1 demos/11_fileio/exercise
2 E
3
M OR ferab
A RO -trans
G EN Task
non 1 – Creating a data Directory
The class must satisfy the UML diagram in Figure 11-1 on page L11-2. The
loadData method must use Bank utility methods (addCustomer and
getCustomer) to populate the customers recorded in the data file.
s a
Furthermore, the Customer class has the addAccount method to add the
accounts from the data file. ) h a
c o m
ฺ
ail eฺ
Task 4 – Deleting Unnecessary Classes g m id
@ G u
0 2 11 ent
n t
In this task, you delete the following 9 2 classes
Java S t udthat are no longer used:
( sai this
TestReport
TestAccount RA
N use
E LT se to
TestAccount2
O B en
TestBatch
E N le lic
TestBanking
M OR ferab
ROTask a n s
A t r 5 – Copying the TestReport Class
GEN non-
In this task, you copy the TestReport class from the
resources/11_fileio directory to the com.mybank.test source
package of the BankPrj project.
data/test.dat.
N
Customer: Simms, Jane O lice
Savings O RE racurrent
Account: ble balance is 500.0
Checking
O n fe current balance is 200.0
M Account:
s
N AR n-Bryant,
tra Owen
G E no
Customer:
Checking Account: current balance is 200.0
For this exercise, you work in the BankPrj project in the projects
directory.
Savings:
read <initial-balance> and <interest-rate)
create account and add account to customer
Checking:
read <initial-balance> and <overdraft-amount)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
com.mybank.test.TestReport.
For this exercise, you work in the BankPrj project in the projects
directory.
}
2. Add an import statement to import necessary class names:
import com.mybank.domain.*;
import java.io.File;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
import java.io.IOException;
import java.util.Scanner;
3. Add the dataFile instance variable to the DataSource class.
private File dataFile;
4. Add a public constructor that takes a string argument dataFilePath
and initializes the dataFile instance variable.
public DataSource(String dataFilePath) {
this.dataFile = new File(dataFilePath);
}
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
// Domain variables
Customer customer;
int numOfCustomers = input.nextInt();
for ( int idx = 0; idx < numOfCustomers; idx++ ) {
// Create customer object
String firstName = input.next();
String lastName = input.next();
Bank.addCustomer(firstName, lastName);
customer = Bank.getCustomer(idx);
// Create customer accounts s a
int numOfAccounts = input.nextInt(); ) h a
while ( numOfAccounts-- > 0 ) {
c o m
// Create a specific type of account ฺ
ail eฺ
char accountType = input.next().charAt(0); g m id
@ G u
switch ( accountType ) {
0 2 11 ent
// Savings account
n t 9 2
S t ud
sai this
case ’S’: {
(
float initBalance = input.nextFloat();
AN use
float interestRate = input.nextFloat();
R
LT se to
customer.addAccount(new SavingsAccount(initBalance,
E
O B en interestRate));
N le lic
break;
E
M
}
OR ferab
// Checking account
A RO -trans
case ’C’: {
TestAccount
TestAccount2
TestBatch
TestBanking
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 12
Objectives
Upon completion of this lab, you should be able to:
● Create a GUI for the ChatRoom project s a
(Optional) Create a GUI for the Banking project ) h a
●
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 12-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Creating the ChatClient GUI Part 1 (Level 1)
Figure 12-1 shows the GUI design that you will attempt to achieve.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
OR ferComponent
The JTextField
M ab Quit Button Component
A RO -Figure
t r ans12-1 GUI Layout for the ChatClient Application
G EN non
As shown in Figure 12-1, there are four components in this GUI. The main
component is a JTextArea. The bottom component is a JTextField.
There are two Button components on the right.
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
) h a
c o m
ฺ
For this exercise, you first create the ChatRoomPrj project in the
ail eฺ
projects directory, and then work in this project for all the following
g m id
exercises that are part of the ChatRoomPrj project.
@ G u
0 2 11 ent
Demonstration – The demonstration
n t 9for
S t ud can be found in the
2 this exercise
1
( ai this
demos/12_gui/exercise1sdirectory.
2
R AN use
LT se to
3
E
B en
O lic the ChatClient Class
Task R 1E–N Creating
l e
M O ferab
s task, you create the ChatClient class in the source package of the
RO -traInnthis
A
GEN non ChatRoomPrj project implement the GUI design in Figure 12-1 on
page 12-2.
Project: ChatRoomPrj
Location: Source Packages
Package: default package
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
The ChatClient class must implement the GUI design in Figure 12-1 on
page 12-2.
Preparation s a
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
Tool Reference – Tool references used in this
0 2 11exercise:
e n t
n t 9
Java Development: Java Application S t ud Creating Projects
2 Projects:
ai his Java Classes
●
R u
●
E LT se to
Java Development: Java Classes:
B en
Java Classes
O
E Java
●
l e lic
N Development: Java Classes: Modifying Java Classes: Executing
R
O fJava b
raPrograms
M e
A RO -trans Java Development: Java Classes: Terminating a Running Process
●
GEN non For this exercise, you first create the ChatRoomPrj project in the
projects directory, and then work in this project for all the following
exercises that are part of the ChatRoomPrj project.
page 12-2.
the figure, then edit the code to tweak the design to match this figure.
Preparation s a
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
Tool Reference – Tool references used in this2
0 11 ent
exercise:
t 9 d
2Projects:tuCreating
Java Development: Java Application
●
a i n i s S Projects
(s eCreating
Java Development: Java Classes:
●
N th Java Classes
T
Java Development: R A
t o usModifying Java Classes: Compiling
Java Classes:
EL nse
●
B
Java Classes
O lice Java Classes: Modifying Java Classes: Executing
Java
●N
E Programs
le
Development:
O RJava a b
O M sfer
A R -tranJava Development: Java Classes: Terminating a Running Process
●
G EN non For this exercise, you first create the ChatRoomPrj project in the
projects directory, and then work in this project for all the following
exercises that are part of the ChatRoomPrj project.
page 12-2.
above.
public void launchFrame() {
JFrame frame = new JFrame("Chat Room");
frame.add(output, BorderLayout.WEST);
frame.add(input, BorderLayout.SOUTH);
s a
) h a
// Create the button panel
c o m
JPanel p1 = new JPanel(); ฺ
ail eฺ
p1.setLayout(new GridLayout(2,1));
g m id
p1.add(sendButton); @ G u
p1.add(quitButton);
0 2 11 ent
n t 9 2
S t ud
// Add the button panel to the center ai is
( s t h
AN use
frame.add(p1, BorderLayout.CENTER);
R
LT se to
frame.pack(); E
B en
O
N le lic
frame.setVisible(true);
} E
R rab
M7.O Create
f e the main method. This method instantiates a new
O s
R -tranChatClient object and then calls the launchFrame method.
A
EN nstatic
Gpublic on void main(String[] args) {
ChatClient c = new ChatClient();
c.launchFrame();
}
the figure, then edit the code to tweak the design to match this figure.
the Bank project. You use a complex layout to properly position several
GUI components in a frame.
Figure 12-2 shows the GUI design that you will attempt to achieve. a
h a s
Action Button Panel
m
Output JTextArea Component )
ฺ c o
m ail eฺ
@ g u id
11 ent G
0 2
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A ns Entry JTextField Component
RO -traData
EN non
GKey Pad Panel Message JTextField Component
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
t 9 20 tude
user actions; you will do that in the next module.
s a in is S
N ( e th
Task 3 – Compiling Tthe R t o us
AATMClient Class
L
E nse
B
N Oyou compile
In this task, l i ce the ATMClient class.
O RE rable
O M sfe
A R -t4ra–nRunning the ATMClient Program
Task
G EN non
Complete the following steps:
1. Set the main class of the BankPrj project to
com.mybank.gui.ATMClient.
2. Run the BankPrj project. You should see the GUI shown in
Figure 12-2 on page 12-12.
Hints
These hints might help you to solve this exercise.
● Use the setEnabled(false) method to make a component
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
read-only.
● A grid layout can be used to create a vertical layout by placing a 1 in
the rows parameters of the GridLayout(int rows, int columns)
constructor.
● A grid layout can be used to create a horizontal layout by placing a 1
in the columns parameters of the GridLayout(int rows, int
columns) constructor.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications
●
R AN use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR_____________________________________________________________
e r a b
R O ransf
A t
G EN non-
Lab 13
Objectives
Upon completion of this lab, you should be able to:
● Create the GUI event handlers for the ChatRoom project s a
) h
(Optional) Create the GUI event handlers for the Banking project
a
●
o m
a ilฺc ฺ
@ gm uide
2 1 1 nt G
t 9 20 tude
s a in is S
N ( e th
T R A
t o us
B EL nse
N O lice
O RE rable
O M sfe
A R -tran
N on
GE n
Lab 13-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Creating the ChatClient GUI Part 2 (Level 1)
A RO -trans
G EN non Tool Reference – Tool references used in this exercise:
● Java Development: Java Classes: Modifying Java Classes: Compiling
Java Classes
● Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs
For this exercise, you work in the ChatRoomPrj project in the projects
directory.
L seT
their containing
R class t
toorefer components like the output text
area and E
B the input n text field. Remember that you made the
O l i c e
N le instance variables in the previous lab.
R Ecomponents
M e●rab to import the java.awt.event package.
O fRemember
A RO -trans To get the text from a JTextArea or JTextField, you can use the
●
N on
GE n getText method; to set the text, use either the setText or append
method.
s a
Preparation ) h a
c o m
ฺ
ail eฺ
There is no preparation for this exercise.
g m id
@ G u
Tool Reference – Tool references used in this 0 2 11
exercise:en
t
n t 9 2
S t ud
Java Development: Java Classes:
●
( s ai Modifying
t h i s Java Classes: Compiling
AN use
Java Classes
Java Development:
● R
LT Java to Modifying Java Classes: Executing
Classes:
E
B en
Java Programs s e
O
N le lic
E
R exercise,b you work in the ChatRoomPrj project in the projects
M Othis
For
e r a
R O ransf
directory.
A t
G EN non-Demonstration – The demonstration for this exercise can be found in the
1 demos/13_events/exercise1 directory.
2
3
Preparation s a
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
Tool Reference – Tool references used in this
0 2 11exercise:
e n t
Java Development: Java Classes:
n t 9 S t udJava Classes: Compiling
2Modifying
sai this
●
Java Classes (
R
Java Development:
● se Modifying Java Classes: Executing
ANJava Classes:
u
LT se to
Java Programs
E
O B en
N exercise,
ForEthis l e licyou work in the ChatRoomPrj project in the projects
R rab
Odirectory.
O M
n s fe
N AR n-traDemonstration – The demonstration for this exercise can be found in the
G E no 1 demos/13_events/exercise1 directory.
2
3
2. Add the ActionListener for the Send button. This listener must
extract the text from the text field and display that text in the text
area. Use an inner class for this listener.
private void launchFrame() {
// GUI component initalization code here
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
sendButton.addActionListener(new SendHandler());
// more code
}
5. Add the ActionListener for the Quit button. This listener must exit
the ChatClient program. Use an anonymous inner class for this
listener.
private void launchFrame() {
// GUI component initalization code here
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
quitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// more code
}
In this solution, the CloseHandler was not reused because the Quit
button requires an ActionListener rather than a WindowListener. a
How could you have satisfied both listener interfaces using the
h a s
CloseHandler class? m )
ฺ c o
m ail eฺ
Task 2 – Compiling the ChatClient Class @ g u id
11 ent G
0 2
2class. tud
n
In this task, you compile the ChatClient
i t 9 S
s a h i s
A N ( use t
Task 3 – Running L TRChatClient
the
e to Program
E
B en s
In this E
O
N youlerunlicthe ChatClient program. Test the behavior of the
task,
M ORlisteners
event
e r a byou added.
R O ransf
A t
G EN non-
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
For this exercise, you work in the BankPrj project in the projects
directory.
s a
1
Demonstration – The demonstration for this exercise can be found in the
demos/13_events/exercise2 directory. ) h a
c o m
2
3
ฺ
ail eฺ
g m id
@ G u
2 11 ent
Task 1 – Modifying the ATMClient 9 2Class
0
t ud
n t S
( s ai this
In this task, you modify the N
A ATMClient
u s e class in the source package of the
LTR sbehavior.
to rely on necessary event listeners to
BankPrj project. This class must
implemented theE required
B en e
O
N le lic
E
TaskM2O–RCompiling
f e r a b the ATMClient Class
O
R -tran s
A
G EN non In this task, you compile the ATMClient class.
Task 3 – Running the BankPrj Project
In this task, you run the BankPrj project.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications
●
R AN use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR_____________________________________________________________
e r a b
R O ransf
A t
G EN non-
Lab 14
GUI-Based Applications
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to add menus to the GUI
for the ChatRoom project.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 14-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise: Creating the ChatClient GUI, Part 3 (Level 1)
Figure 14-1 shows the GUI design that you will attempt to achieve.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
Figure 14-1 GUI Layout for the ChatClient Application
0 2 11 ent
You need to add four features to thein t92 GUI:
existing S tud
( sa component
t h is
●
A N use
Add the user name JComboBox under the Send and Quit
T R enables
buttons. This component
L t o you to select a name that is posted
B E ns
with every chat line e
that you enter. You must alter the Send button
NO lecomponent.
and JTextField e
lic listenersAdd
to write the username to the output
E
Ryour full
JTextAreab several user name options including
O a
M sfer name and a few nicknames, such as 1337dud3 or Java Geek.
O
R -tranPut the JTextArea component into a JScrollPane component. Add
A ●
G EN non a vertical scroll bar but no horizontal scroll bar. Auto scroll the text
to the bottom of the JTextArea as the user adds text to the text chat
window.
● Add the File menu. This menu must include a Quit menu item that
terminates the program when selected.
● Add the Help menu. This menu must include an About menu item
that pops up a simple dialog box, which displays a comment about
the program and about you, the developer.
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
For this exercise, you work in the ChatRoomPrj project in the projects
directory.
a
Demonstration – The demonstration for this exercise can be found) in
as
hthe
c o m
1 demos/14_guiapps/exercise1 directory. ฺ
ail eฺ
2
g m id
3
@ G u
0 2 11 ent
Task 1 – Modifying the ChatClient n t 9 2
S t ud
Class
( sai this
N use
Athe
L R
T This
In this task, you modify
t oclass must implement
ChatClient class in the source package of the
ChatRoomPrj
B E ns
project. e the GUI design in
NO on
Figure 14-1 page
l e
ic L14-2.
E
R rabl e
O
M 2s–feCompiling the ChatClient Class
OTask
R -tran
A
GEN non
In this task, you compile the ChatClient class.
Preparation s a
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
Tool Reference – Tool references used in this exercise:
●
n t 9 2
Java Development: Java Classes: Modifying
S t ud Classes: Compiling
Java
Java Classes
( sai this
●
R ANClasses:
Java Development: Java
u seModifying Java Classes: Executing
Java ProgramsLT
E e to
B en s
O
N leyoulicwork in the ChatRoomPrj project in the projects
For this exercise,
E
M OR ferab
directory.
A t ans
RO -Demonstration
r – The demonstration for this exercise can be found in the
G EN1 non demos/14_guiapps/exercise1 directory.
2
3
1. Add the user name JComboBox component under the Send and Quit
buttons. This component enables you to select a name that is posted
with every chat line that you enter. Add several user name options
including your full name and a few nicknames, such as 1337dud3 or
Java Geek.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
2. Enhance the listeners for the Send button and JTextField to write
the user name to the output JTextArea component.
3. Put the JTextArea component into a JScrollPane component. Add
a vertical scroll bar but no horizontal scroll bar. Auto scroll the text
to the bottom of the JTextArea as the user adds text to the text chat
window.
4. Add the File menu. This menu must include a Quit menu item that
terminates the program when selected.
s a
5. Add the Help menu. This menu must include an About menu item
) h a
c o m
that pops up a simple dialog box, which displays a comment about
the program and about you, the developer. ฺ
ail eฺ
g m id
@
1 nt G u
Task 2 – Compiling the ChatClient 2 1Class
t 9 2 0
t u de
s a in is S
N e th class.
In this task, you compile the( ChatClient
T R A
t o us
Task 3 – Running B EL the n seChatClient Program
NO le lic e
E
M OInRthis
e r a b you run the ChatClient program. You should see the GUI,
task,
R O rashown
n sf in Figure 14-1 on page L14-2. If your GUI does not look exactly like
A t the figure, then edit the code to tweak the design to match this figure.
GEN non-
Preparation s a
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
Tool Reference – Tool references used in this exercise:
●
n t 9 2
Java Development: Java Classes: Modifying
S t ud Classes: Compiling
Java
Java Classes
( sai this
●
R ANClasses:
Java Development: Java
u seModifying Java Classes: Executing
Java ProgramsLT
E e to
B en s
O
N leyoulicwork in the ChatRoomPrj project in the projects
For this exercise,
E
M OR ferab
directory.
A t ans
RO -Demonstration
r – The demonstration for this exercise can be found in the
G EN1 non demos/14_guiapps/exercise1 directory.
2
3
1. Add the user name JComboBox component under the Send and Quit
buttons. This component enables you to select a name that is posted
with every chat line that you enter. Add several user name options
including your full name and a few nicknames, such as 1337dud3 or
Java Geek.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
}
6. Add a JScrollPane component to the project and add the
JTextArea component to the a JScrollPane. Add a vertical scroll
bar but no horizontal scroll bar.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
// Add declaration
private JScrollPane textPane;
// existing code here
s a
// Add JScrollPane to Layout
) h a
frame.add(textPane, BorderLayout.WEST);
c o m
7. Auto scroll the text to the bottom of the JTextArea as the ฺ
ail usereadds
ฺ
text to the text chat window. g m i d
1 1 @ t Gu
02 uden
// Add to SendHandler to enable AutoScroll
2
output.setCaretPosition(output.getDocument().getLength()-1);
9
a i nt is St
8. Add the File menu. This N (s must
menu e thinclude a Quit menu item that
R s
A whenuselected.
T
terminates the program
t o
public void launchFrame() B E{ L nse
// existing code N O lice
here
// Create menu
O REbarraband le File menu
O M mb
JMenuBar
n s fe= new JMenuBar();
A R -tra = new JMenu("File");
JMenu file
N JMenuItem
on
GE
quitMenuItem = new JMenuItem("Quit");
nquitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
file.add(quitMenuItem);
mb.add(file);
frame.setJMenuBar(mb);
// existing code here
}
9. Add the Help menu. This menu must include an About menu item
that pops up a simple dialog box, that displays a comment about the
program and about you, the developer.
public void launchFrame() {
help.add(aboutMenuItem);
mb.add(help);
// existing code here
}
OR fer"to
to talk " +
M ab other ChatClients via a
ans b = new JButton("OK");
RO -trJButton
ChatServer"),BorderLayout.NORTH);
A
GEN non add(b,BorderLayout.SOUTH);
b.addActionListener(this);
pack();
}
// Hide the dialog box when the OK button is pushed
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
}
the figure, then edit the code to tweak the design to match this figure.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 15
Threads
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to create a simple
multithreaded application.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 15-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise: Using Multithreaded Programming (Level 1)
The purpose of this lab is to create three threads and run them at the same
time. While they are running, they print out their names to the standard
output stream. By observing what is printed, you can observe how the
threads run and in what order.
directory.
2. Create a PrintMe class in the source package of the
ThreadProject with the following characteristics:
Class Name: PrintMe
Project: ThreadProject
Implements: Runnable
Location: Source Packages
s a
Package: default package
) h a
c o m
The class implements the Runnable interface. The run method ฺ
aofilthe ofcurrent
the class
ฺ
performs the following actions 10 times: Print the name g m i d e
thread and then sleep for 2 seconds.
1 1 @ t Gu
9 2 02 uden
Task 2 – Creating the TestThreeThreadsa i nt is St Class
( s t h
R AN use
In this task, youLcreate
E to
T aeTestThreeThreads class in the source package
B n s
N O lice
of the ThreadProject with the following characteristics:
O REClass a b le TestThreeThreads
Name:
O er ThreadProject
M sfProject:
A R -tran Location: Source Packages
GEN non
Package: default package
The main method of the class creates three threads using the PrintMe
runnable class. Give each thread a unique name using the setName
method. Start each thread.
T3 - Moe
T2 - Curly
T1 - Larry
T1 - Larry
T3 - Moe
T2 - Curly
T1 - Larry
T3 - Moe
T2 - Curly
T1 - Larry
s a
T3 - Moe
) h a
T2 - Curly
c o m
T1 - Larry ฺ
ail eฺ
T3 - Moe g m id
@ G u
T2 - Curly
0 2 11 ent
ud
T1 - Larry
t 9 2 t
T3 - Moe n S
T2 - (
Curly sai this
T1 - AN use
Larry
R
T3
E
-
LT se to
Moe
T2
O B en
- Curly
E N le lic
T1 - Larry
OR ferab
T3 - Moe
M T2 - Curly
A RO -trans T1 - Larry
G EN non T3
T2
-
-
Moe
Curly
T1 - Larry
T3 - Moe
T2 - Curly
Run this program several times. You might see different results for each
execution.
Preparation s a
) h a
c o m
There is no preparation required for this exercise. ฺ
ail eฺ
g m id
@ G u
Tool Reference – Tool references used in this
0 2 11exercise:
e n t
n t 9
Java Development: Java Application S t ud Opening Projects
2 Projects:
ai his Java Classes
●
R u
●
E LT se to
Java Development: Java Classes:
B en
Java Classes
O
E Java
●
l e lic
N Development: Java Classes: Modifying Java Classes: Executing
R
O fJava b
raPrograms
M e
A nsthis exercise, you work in the ThreadProject project in the
RO -traFor
GEN non exercises/15_threads directory.
Demonstration – The demonstration for this exercise can be found in the
1 demos/15_threads directory.
2
3
directory.
2. Create the PrintMe class with the following characteristics:
Class Name: PrintMe
Project: ThreadProject
Implements: Runnable
Location: Source Packages
Package: default package
s a
This class must implement the Runnable interface. ) h a
c o m
3. ฺ
ail eฺ
Create the run method to loop the following 10 times: Print the name
g m
of the current thread and then sleep for 2 seconds.
id
@ G u
0 2 11 ent
Task 2 – Creating the TestThreeThreads
n t 9 2
S t udClass
( sai this
R AN use
In this task, you create a TestThreeThreads class in the source package
of the ThreadProject
E LT project.
e to
B en s
CompleteNtheO following
lic steps:
E l e
R ratheb TestThreeThreads class with the following
1.O Create
O M
n s fe
AR n-tra Class Name: TestThreeThreads
characteristics:
E N
G no
Project: ThreadProject
Location: Source Packages
Package: default package
2. Create the main method.
a. Create three Thread objects and pass an instance of the
PrintMe class to each constructor.
b. Give each thread a unique name using the setName method.
c. Start each thread.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Preparation s a
) h a
c o m
There is no preparation required for this exercise. ฺ
ail eฺ
g m id
@ G u
Tool Reference – Tool references used in this2
0 11 ent
exercise:
t 9 d
2Projects:tuOpening
●
a i n
Java Development: Java Application
i s S Projects
(s eCreating
Java Development: Java Classes:
●
N th Java Classes
T R
Java Development:
A
t o usModifying Java Classes: Compiling
Java Classes:
EL nse
●
B
Java Classes
O lice Java Classes: Modifying Java Classes: Executing
Java
● N
E Programs
le
Development:
O RJava a b
O M sfer
A R -For
t r n exercise, you work in the ThreadProject project in the
athis
G EN non exercises/15_threads directory.
Demonstration – The demonstration for this exercise can be found in the
1 demos/15_threads directory.
2
3
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
7i Business Solutions, SฺAฺ de CฺVฺ
Lab 16
Networking
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Objectives
Upon completion of this lab, you should be able to build a GUI client to
connect to a remote server by using Transmission Control
s a
Protocol/Internet Protocol (TCP/IP).
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non
Lab 16-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise: Creating a Socket Client (Level 1)
The chat server is responsible for sending messages received from one
client to all connected clients (including the original sender). Figure 16-1
shows an architecture diagram of several clients attached to the single
chat server. In this scenario, Simon types This is cool! into the
message JTextField component. Simon’s client then prepends his name
Simon: onto the message and sends it to the server over the output
stream (Step 1). The server receives the message and then forwards the
message to each attached client (Steps 2–4); the order of the forwarded
messages is unimportant.
s a
) h a
c o m
a il ฺ
client: PC/Win95
1 “Simon: This is cool!” g m i d eฺ
1 1 @ t Gu
ChatClient
3 “Simon: This is cool!”
9 2 02 uden
Simon
a i t
nserveri s St
N (s e th
T R A
t o us
client: SparcSol9
B EL nse
N O lice ChatServer
E e
R rabl 2 “Simon: This is cool!”
O
ChatClient
M sfe
Debbie O
R -tran
A
N on
GE n
client: PC/WinXP
Figure 16-1 The Chat Server Sends Any Message to All Attached Clients
«interface»
Runnable
The RemoteReader is a nested class
that reads messages from the serverIn
instance variable in the ChatClient. +run():void
RemoteReader server
ChatClient
s a
-serverIn : BufferedReader
) h a
-serverOut : PrintWriter
c o m ChatServer
«methods» ฺ
ail eฺ
-doConnect():void
g m id
@ G u
11 ent
SendHandler
0 2
n 9 2
«methods»
t S t ud
sai this
+actionPerformed(e:ActionEvent):void
(
R AN use
E LT se to
The SendHandler is a nested class
that sends messages to the serverOut
B en
instance variable in the ChatClient.
O
Figure
E 16-2 lic Design of the ChatClient Application
N leDetailed
M OR ferab
R O raThis
n s exercise contains the following sections:
A t
GEN non- “Task 1 – Modifying the ChatClient Class”
●
Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
For this exercise, you work in the ChatRoomPrj project in the projects
s a
directory.
) h a
c o m
Demonstration – The demonstration for this exercise can be
ฺ
il inฺ the
afound
1 demos/16_network directory.
@ g m
u ide
2
2 1 1 nt G
3
t 9 20 tude
s a in is S
N ( e th
Task 1 – Modifying the R us
AChatClient Class
T t o
B EL nse
In this task,O
N you modify
l i c ethe ChatClient class in the source package of the
RE rabproject.
ChatRoomPrj
onOthe detailed
le Implement the client-server communication based
design in Figure 16-2 on page L16-3.
M f e
A RO -trans
G EN Task
non 2 – Compiling the ChatClient Class
In this task, you compile the ChatClient class.
-DserverIP=<server-host>
-DserverPort=2000
Preparation
s a
) h a
There is no preparation for this exercise.
c o m
ฺ
ail eฺ
Tool Reference – Tool references used in this exercise gm id
@ G u
Java Development: Java Classes: Modifying
●
0 2 11Java eClasses:
n t Compiling
Java Classes
n t 9 2
S t ud
sai thethMain
Java Application Projects: (Setting
● is Class
ANApplication
Java Development:RJava u se Projects: Setting VM Options
to
●
E LT Java
s e
●
O B en
Java Development: Application Projects: Running Projects
E N le lic
O R rab you work in the ChatRoomPrj project in the projects
For this exercise,
O n s fe
Mdirectory.
N AR n-tra
G E no Demonstration – The demonstration for this exercise can be found in the
1 demos/16_network directory.
2
3
2. Add instance variables to hold the input and output streams for the
socket connection. You might need additional instance variables,
depending on your implementation.
3. Add the doConnect method to initiate the TCP/IP socket connection
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
to the server. Ask your instructor for the hostname (or IP address)
and port number of the server application.
a. Initialize server IP and port information.
b. Create the connection to the chat server.
c. Prepare the input stream and store it in an instance variable.
d. Prepare the output stream and store it in an instance variable.
e. Launch the reader thread.
f. Use a catch clause to capture any exceptions. s a
4. Modify the launchFrame method to call the doConnect method. ) h a
o m
5. Modify the SendHandler nested class to send the message
a ilฺc textฺ (and
m e
displayed the message to the output text1area.@ g
the user name) to the socket output stream. Delete the
G uid
code that
0 2 1 ent
6. Create the RemoteReader nested
t 9 class d
2 thattuimplements the Runnable
interface. The run methodamust n S
i readisa line at a time from the socket
(
input stream in an infinite s loop. th
A N us e
L seT R t o
B
Task 2 – Compiling
E nthe ChatClient Class
O l i c e
R EN ble
M OIn this
f e ra you compile the ChatClient class.
task,
A RO -trans
GEN non Task 3 – Running the ChatRoomPrj Project
Complete the following steps:
1. Set the main class of the ChatRoomPrj project to ChatClient.
text area will display a message from the server with a secret
passphrase. When you send that passphrase to the server, you then
trigger an event on the server that plays a gong. This event will
indicate that your application is working correctly.
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non
Preparation
s a
) h a
There is no preparation for this exercise.
c o m
ฺ
ail eฺ
g
Tool Reference – Tool references used in this exercise: m id
@ G u
●
0 2 11 Java
Java Development: Java Classes: Modifying
e n t
Classes: Compiling
Java Classes 2
t9 Stu d
i n is Main Class
● ( saSettingththe
Java Application Projects:
R
Java Development:AN u se
Java Application Projects: Setting VM Options
●
L T e to
●
O BE ens Java Application Projects: Running Projects
Java Development:
E N le lic
O R rexercise,
For this
a b you work in the ChatRoomPrj project in the projects
O n s fe
M directory.
N AR n-tra
GE no Demonstration – The demonstration for this exercise can be found in the
1 demos/16_network directory.
2
3
2. Add instance variables to hold the input and output streams for the
socket connection. You might need additional instance variables,
depending on your implementation.
public class ChatClient {
// existing code here
private Socket connection = null;
private BufferedReader serverIn = null;
private PrintStream serverOut = null;
s a
}
// existing code here
) h a
c o m
3. ฺ
ail eฺ
Add the doConnect method to initiate the TCP/IP socket connection
g m id
to the server. Ask your instructor for the hostname (or IP address)
@ G u
and port number of the server application.
0 2 11 ent
private void doConnect() {
n t 9 2
S t ud
a.
sai information.
Initialize server IP and port
( t h is
// Initialize server IP and port
R u se
ANinformation
L T e to
String serverIP = System.getProperty("serverIP", "127.0.0.1");
O BE ens
String serverPort = System.getProperty("serverPort", "2000");
E N le lic
M OR– You
Note f e r a b have hard coded the server IP address and port number
could
R O inrathensSocket constructor call below. The code for this step demonstrates
A
N on - t
how to make these values dynamic at runtime. The system properties,
G E n serverIP and serverPort, can be assigned on the java command using
the -D option, as follows:
java -DserverIP=myhost.example.com
-DserverPort=47 ChatClient
Exercise Summary
9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA
●
N use
E LT se to
B en
_____________________________________________________________
O
E N le lic
_____________________________________________________________
M OR f_____________________________________________________________
e rab
A RO -trans
GEN non
s a
) h a
c o m
ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non