Вы находитесь на странице: 1из 276

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ฺ
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 2
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
D67983
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.

Sun Microsystems, Inc. Disclaimer

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.

Restricted Rights Notice


If this documentation is delivered to the U.S. Government or anyone using the documentation on behalf of the U.S.
Government, the following notice is applicable:

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ฺ

This page intentionally left blank.

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ฺ

This page intentionally left blank.

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 inProgram i s S
Errors...................................... 1-2
s h
N ( Compilation t
Preparation ................................................................................... 1-2
A s e
ExerciseL R atoTestu Program (Level
Task – Correcting
2:TCreating
and Runtime Errors ................... 1-2
1)..................................... 1-4
E
B en
Preparation s e
................................................................................... 1-4
O
N leTask lic1 – 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
Object-Oriented Programming ........................................................2-1
Objectives ............................................................................................ 2-1

v
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 ................................... 2-2


Preparation ................................................................................... 2-2
Task – Using the Java API Documentation ................................. 2-2
Exercise 2: Exploring Encapsulation, Version 1 (Level 1) .................. 2-3
Preparation ................................................................................... 2-4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 1 – Deleting the Account Class ......................................... 2-4


Task 2 – Creating the Account Class ......................................... 2-4
Task 3 – Creating the TestAccount2 Class .............................. 2-5
Task 4 – Compiling the TestAccount2 Class........................... 2-5
Task 5 – Running the TestAccount2 Program......................... 2-5
Exercise 2: Exploring Encapsulation, Version 1 (Level 2) .................. 2-6
Preparation ................................................................................... 2-6
Task 1 – Deleting the Account Class ......................................... 2-7
Task 2 – Creating the Account Class ......................................... 2-7
Task 3 – Creating the TestAccount2 Class .............................. 2-7
s a
Task 4 – Compiling the TestAccount2 Class........................... 2-8
) h a
c o m
Task 5 – Running the TestAccount2 Program......................... 2-8

ail eฺ
Exercise 2: Exploring Encapsulation, Version 1 (Level 3) .................. 2-9
m id
Preparation ................................................................................... 2-9
g
@ G u
Task 1 – Deleting the Account Class ....................................... 2-10
2 11 ent
Task 2 – Creating the Account Class ....................................... 2-10
0
n t 9 2 t ud
Task 3 – Creating the TestAccount2 Class ............................ 2-10
S
sai this
Task 4 – Compiling the TestAccount2 Class......................... 2-11
(
R AN use
Task 5 – Running the TestAccount2 Program....................... 2-11

LT se to
Exercise 3: Exploring Encapsulation, Version 2 (Level 1) ................ 2-12
E
B en Preparation ................................................................................. 2-12
O
N le lic Task 1 – Modifying the Account Class.................................... 2-13
E Task 2 – Modifying the TestAccount Class........................... 2-13
M OR ferab Task 3 – Compiling the TestAccount Class........................... 2-13

A RO -trans Task 4 – Running the TestAccount Program ......................... 2-13

EN non
Exercise 3: Exploring Encapsulation, Version 2 (Level 2) ................ 2-14
G 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
Task 1 – Creating the Java Packages ......................................... 2-19
Task 2 – Moving and Modifying the Account Class ............... 2-19

vi Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Task 3 – Moving the TestAccount Class ............................... 2-20


Task 4 – Compiling the TestAccount Class........................... 2-20
Task 5 – Running the TestAccount Program ......................... 2-20
Exercise Summary .............................................................................. 2-21
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Identifiers, Keywords, and Types ...................................................3-1


Objectives ............................................................................................ 3-1
Exercise 1: Investigating Reference Assignment ................................. 3-2
Preparation ................................................................................... 3-2
Task 1 – Creating the TestMyPoint Class ................................ 3-3
Task 2 – Compiling the TestMyPoint Class............................. 3-4
Task 3 – Running the TestMyPoint Program ........................... 3-4
Exercise 2: Creating Customer Accounts (Level 1) ............................. 3-5
Preparation ................................................................................... 3-6
Task 1 – Creating the Customer Class....................................... 3-6
Task 2 – Copying the TestBanking Class ................................ 3-6 s a
Task 3 – Compiling the TestBanking Class............................. 3-7 ) h a
c o m
Task 4 – Running the TestBanking Program ........................... 3-7

ail eฺ
Exercise 2: Creating Customer Accounts (Level 2) ............................. 3-8
g m id
@ G u
Preparation ................................................................................... 3-8

0 2 11 ent
Task 1 – Creating the Customer Class....................................... 3-9

n t 2
S t ud
Task 2 – Copying the TestBanking Class ................................ 3-9
9
sai this
Task 3 – Compiling the TestBanking Class............................. 3-9
(
Task 4 – Running the TestBanking Program ......................... 3-10
R AN use
Exercise 2: Creating Customer Accounts (Level 3) ........................... 3-11
E LT se to Preparation ................................................................................. 3-11
O B en Task 1 – Creating the Customer Class..................................... 3-12
E N le lic Task 2 – Copying the TestBanking Class .............................. 3-13

M OR ferab Task 3 – Compiling the TestBanking Class........................... 3-13

RO -trans
Task 4 – Running the TestBanking Program ......................... 3-13
A Exercise Summary .............................................................................. 3-14
GEN non 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-3
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
Task 3 – Copying the TestBanking Class ................................ 4-6
Task 4 – Compiling the 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ฺ

Task 5 – Running the TestBanking Program ........................... 4-6


Exercise 2: Using Conditional Statements in the Account Class (Level 2)
4-8
Preparation ................................................................................... 4-8
Task 1 – Modifying the Account Class...................................... 4-9
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
Task 2 – Deleting the Current TestBanking Class..................... 4-11
Task 3 – Copying the TestBanking Class .............................. 4-11
s a
Task 4 – Compiling the TestBanking Class........................... 4-11
) h a
Task 5 – Running the TestBanking Program ......................... 4-12
c o m
ail eฺฺ
Exercise 3: Using Nested Loops (Advanced) ..................................... 4-13
m id
Preparation ................................................................................. 4-13
g
@ G u
Task 1 – Writing the isSubString Method............................ 4-13
2 11 ent
Task 2 – Compiling the TestIsSubString Class .................. 4-14
0
n t 9 2 t ud
Task 3 – Running the TestIsSubString Program ................ 4-14
S
sai this
Hints.......................................................................................... 4-15
(
AN use
Exercise Summary .............................................................................. 4-16
R
E LT se to
Arrays................................................................................................ 5-1
B ............................................................................................
Objectives
O e n 5-1
l i c
N le1 – Using Primitive Arrays (Level 1)..................................... 5-2
R EExercise
b
M O feraPreparation ................................................................................... 5-2

R O rans Task Task 1 – Creating the TestArrays Class .................................. 5-2

N A n-t 2 – Compiling the TestArrays Class ............................... 5-3


G E no Task 3 – Running the TestArrays Program ............................. 5-3
Exercise 1 – Using Primitive Arrays (Level 2)..................................... 5-4
Preparation ................................................................................... 5-4
Task 1 – Creating the TestArrays Class .................................. 5-4
Task 2 – Compiling the TestArrays Class ............................... 5-5
Task 3 – Running the TestArrays Program ............................. 5-5
Hint ............................................................................................. 5-6
Exercise 1 – Using Primitive Arrays (Level 3)..................................... 5-7
Preparation ................................................................................... 5-7
Task 1 – Creating the TestArrays Class .................................. 5-7
Task 2 – Compiling the TestArrays Class ............................... 5-9
Task 3 – Running the TestArrays Program ............................. 5-9
Exercise 2 – Using Arrays to Represent One-to-Many Associations (Level
1) ...................................................................................................... 5-10
Preparation ................................................................................. 5-11

viii Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Task 1 – Creating the Bank Class.............................................. 5-11


Task 2 – Deleting the Current TestBanking Class................ 5-11
Task 3 – Copying the TestBanking Class .............................. 5-11
Task 4 – Compiling the TestBanking Class........................... 5-12
Task 5 – Running the TestBanking Program ......................... 5-12
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Exercise 2 – Using Arrays to Represent One-to-Many Associations (Level


2) ...................................................................................................... 5-13
Task 1 – Creating the Bank Class.............................................. 5-14
Task 2 – Deleting the Current TestBanking Class................ 5-14
Task 3 – Copying the TestBanking Class .............................. 5-14
Task 4 – Compiling the TestBanking Class........................... 5-14
Task 5 – Running the TestBanking Program ......................... 5-15
Exercise 2 – Using Arrays to Represent One-to-Many Associations (Level
3) ...................................................................................................... 5-16
Task 1 – Creating the Bank Class.............................................. 5-17
s a
Task 2 – Deleting the Current TestBanking Class................ 5-18
) h a
c o m
Task 3 – Copying the TestBanking Class .............................. 5-18
ail eฺฺ
Task 4 – Compiling the TestBanking Class........................... 5-18
m id
Task 5 – Running the TestBanking Program ......................... 5-18
g
@ G u
Exercise Summary .............................................................................. 5-19
0 2 11 ent
n t 2
S t ud
Class Design .....................................................................................6-1
9
s a i
Objectives ............................................................................................
i s 6-1
N ( uAccount
Exercise 1: Creating Bank h
e t Subclasses (Level 1).................... 6-3 6-2
Preparation A s
...................................................................................
L
Task T1 R– Modifying
e to the Account Class...................................... 6-3
E s
BTask 2e–nCreating the SavingsAccount Class.......................... 6-4
O
N leTask lic3 – Creating the CheckingAccount Class ....................... 6-4
E
M OR ferab Task 4 – Deleting the Current TestBanking Class ................... 6-4

R O rans Task 5 – Copying the TestBanking Class ................................ 6-5

N A n-t Task 6 – Compiling the TestBanking Class............................. 6-5


GE no Task 7 – Running the TestBanking Program ........................... 6-5
Exercise 1: Creating Bank Account Subclasses (Level 2).................... 6-7
Preparation ................................................................................... 6-7
Task 1 – Modifying the Account Class...................................... 6-7
Task 2 – Creating the SavingsAccount Class.......................... 6-8
Task 3 – Creating the CheckingAccount Class ....................... 6-9
Task 4 – Deleting the Current TestBanking Class ................. 6-10
Task 5 – Copying the TestBanking Class .............................. 6-10
Task 6 – Compiling the TestBanking Class........................... 6-10
Task 7 – Running the TestBanking Program ......................... 6-10
Exercise 1: Creating Bank Account Subclasses (Level 3).................. 6-12
Preparation ................................................................................. 6-12
Task 1 – Modifying the Account Class.................................... 6-12
Task 2 – Creating the SavingsAccount Class........................ 6-13
Task 3 – Creating the CheckingAccount Class ..................... 6-14
Task 4 – Deleting the Current TestBanking Class ................. 6-15
Task 5 – Copying the TestBanking Class .............................. 6-15

ix
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Task 6 – Compiling the TestBanking Class........................... 6-15


Task 7 – Running the TestBanking Program ......................... 6-16
Exercise 2: Creating a Heterogeneous Collection of Customer Accounts
(Level 1)........................................................................................... 6-18
Preparation ................................................................................. 6-19
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 1 – Modifying the Customer Class ................................. 6-19


Task 2 – Copying and Completing the CustomerReport
Class........................................................................................ 6-19
Task 3 – Copying the TestReport Class ................................ 6-20
Task 4 – Compiling the TestReport Class ............................. 6-20
Task 5 – Running the TestReport Program ........................... 6-20
Exercise 2: Creating a Heterogeneous Collection of Customer Accounts
(Level 2)........................................................................................... 6-21
Task 1 – Modifying the Customer Class ................................. 6-21
Task 2 – Copying and Completing the CustomerReport
s a
h a
Class........................................................................................ 6-22
)
c o m
Task 3 – Copying the TestReport Class ................................ 6-23

ail eฺ
Task 4 – Compiling the TestReport Class ............................. 6-23
m id
Task 5 – Running the TestReport Program ........................... 6-23
g
@ G u
Exercise 2: Creating a Heterogeneous Collection of Customer Accounts
2 11 ent
(Level 3)........................................................................................... 6-24
0
n t 9 2 t ud
Task 1 – Modifying the Customer Class ................................. 6-24
S
sai this
Task 2 – Copying and Completing the CustomerReport
(
R AN use
Class........................................................................................ 6-25

LT se to
Task 3 – Copying the TestReport Class ................................ 6-26
E
B en Task 4 – Compiling the TestReport Class ............................. 6-26
O
N le lic Task 5 – Running the TestReport Program ........................... 6-26
E Exercise 3: Creating a Batch Program (Advanced) ............................ 6-27
M OR ferab Preparation ................................................................................. 6-28

A RO -trans Task 1 – Modifying the SavingsAccount Class .................... 6-28

EN non
Task 2 – Creating the AccumulateSavingsBatch
G Class........................................................................................ 6-28
Task 3 – Copying the TestBatch Class................................... 6-29
Task 4 – Compiling the TestBatch Class ............................... 6-29
Task 5 – Running the TestBatch Program ............................. 6-29
Exercise Summary .............................................................................. 6-31
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-3
Task 4 – Copying the TestReport Class .................................. 7-4
Task 5 – Compiling the TestReport Class ............................... 7-4

x Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Task 6 – Running the TestReport Program ............................. 7-4


Exercise 1: Applying Static Members to a Design (Level 2) ............... 7-5
Task 1 – Modifying the Bank Class ............................................ 7-6
Task 2 – Modifying the CustomerReport Class ...................... 7-6
Task 3 – Deleting the Current TestReport Class ..................... 7-6
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 4 – Copying the TestReport Class .................................. 7-7


Task 5 – Compiling the TestReport Class ............................... 7-7
Task 6 – Running the TestReport Program ............................. 7-7
Exercise 1: Applying Static Members to a Design (Level 3) ............... 7-8
Task 1 – Modifying the Bank Class ............................................ 7-9
Task 2 – Modifying the CustomerReport Class .................... 7-10
Task 3 – Deleting the Current TestReport Class ................... 7-10
Task 4 – Copying the TestReport Class ................................ 7-10
Task 5 – Compiling the TestReport Class ............................. 7-11
Task 6 – Running the TestReport Program ........................... 7-11
s a
Exercise 2: Working With Interfaces and Abstract Classes
) h a
c o m
(Level 1)........................................................................................... 7-12

ail eฺ
Preparation ................................................................................. 7-13
m id
Task 1 – Creating the Pet Interface............................................ 7-13
g
@ G u
Task 2 – Creating the Animal Classes ....................................... 7-14
2 11 ent
Task 3 – Creating the TestAnimals Class .............................. 7-14
0
n t 9 2 t ud
Task 4 – Compiling the TestAnimals Class........................... 7-15
S
( sai this
Task 5 – Running the TestAnimals Program ......................... 7-15
AN use
Exercise 2: Working With Interfaces and Abstract Classes
R
LT se to
(Level 2)........................................................................................... 7-16
E
B en Preparation ................................................................................. 7-16
O
N le lic Task 1 – Creating the Pet Interface............................................ 7-16
E Task 2 – Creating the Animal Classes ....................................... 7-17
M OR ferab Task 3 – Creating the TestAnimals Class .............................. 7-19

A RO -trans Task 4 – Compiling the TestAnimals Class........................... 7-20

EN non
Task 5 – Running the TestAnimals Program ......................... 7-20
G Exercise 2: Working With Interfaces and Abstract Classes
(Level 3)........................................................................................... 7-21
Preparation ................................................................................. 7-21
Task 1 – Creating the Pet Interface............................................ 7-21
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

xi
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Task 3 – Modifying the CheckingAccount Class .................... 8-4


Task 4 – Deleting the Current TestBanking Class ................... 8-4
Task 5 – Copying the TestBanking Class ................................ 8-4
Task 6 – Compiling the TestBanking Class............................. 8-5
Task 7 – Running the TestBanking Program ........................... 8-5
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Exercise: Creating Your Own Exception (Level 2).............................. 8-6


Task 1 – Creating the OverdraftException Class................. 8-7
Task 2 – Modifying the Account Class...................................... 8-7
Task 3 – Modifying the CheckingAccount Class .................... 8-8
Task 4 – Deleting the Current TestBanking Class ................... 8-8
Task 5 – Copying the TestBanking Class ................................ 8-8
Task 6 – Compiling the TestBanking Class............................. 8-8
Task 7 – Running the TestBanking Program ........................... 8-8
Exercise: Creating Your Own Exception (Level 3).............................. 8-9
Task 1 – Creating the OverdraftException Class............... 8-10
s a
Task 2 – Modifying the Account Class.................................... 8-11
) h a
Task 3 – Modifying the CheckingAccount Class .................. 8-11
c o m
ail eฺ
Task 4 – Deleting the Current TestBanking Class ................. 8-12ฺ
m id
Task 5 – Copying the TestBanking Class .............................. 8-12
g
@ G u
Task 6 – Compiling the TestBanking Class........................... 8-12
2 11 ent
Task 7 – Running the TestBanking Program ......................... 8-12
0
n t 9 2 t ud
Exercise Summary .............................................................................. 8-13
S
( sai this
Collections and Generics Framework............................................ 9-1
A N use
Objectives ............................................................................................ 9-1
T R t o
B EL nse
Exercise 1: Using Collections to Represent Association
(Level
O l i c e
1)............................................................................................. 9-2

R EN Preparation
b l ................................................................................... 9-3
e 1 – Modifying
M O feraTask 2 – Modifying the
Task Bank Class ............................................ 9-3

R O rans Task 3 – Compiling the the Customer Class ................................... 9-3

N A n-t TestReport Class ............................... 9-3


G E no Task 4 – Running the TestReport Program ............................ 9-4
Exercise 1: Using Collections to Represent Association
(Level 2)............................................................................................. 9-5
Preparation ................................................................................... 9-5
Task 1 – Modifying the Bank Class ............................................ 9-5
Task 2 – Modifying the Customer Class ................................... 9-6
Task 3 – Compiling the TestReport Class ............................... 9-6
Task 4 – Running the TestReport Program ............................. 9-6
Exercise 1: Using Collections to Represent Association
(Level 3)............................................................................................. 9-8
Preparation ................................................................................... 9-8
Task 1 – Modifying the Bank Class ............................................ 9-9
Task 2 – Modifying the Customer Class ................................... 9-9
Task 3 – Compiling the TestReport Class ............................. 9-10
Task 4 – Running the TestReport Program ........................... 9-11

xii Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Exercise Summary .............................................................................. 9-12


I/O Fundamentals ...........................................................................10-1
Console I/O and File I/O .................................................................11-1
Objectives .......................................................................................... 11-1
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Exercise 1: Reading a Data File (Level 1) .......................................... 11-2


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
s a
h a
Preparation ................................................................................. 11-7
)
c o m
Task 1 – Creating a data Directory .......................................... 11-8

ail eฺ
Task 2 – Copying the Resource File.......................................... 11-8
g m id
Task 3 – Creating the DataSource Class ................................ 11-8
@ G u
0 2 11 ent
Task 4 – Deleting Unnecessary Classes .................................... 11-9
Task 5 – Copying the TestReport Class ................................ 11-9
n t 9 2 t ud
Task 6 – Compiling the TestReport Class ............................. 11-9
S
sai this
Task 7 – Running the BankPrj Project .................................... 11-9
(
AN use
Exercise 1: Reading a Data File (Level 3) ........................................ 11-11
R
E LT se to
Preparation ............................................................................... 11-11

O B en Task 1 – Creating a data Directory ........................................ 11-12

E N le lic Task 2 – Copying the Resource File........................................ 11-12

OR ferab
Task 3 – Creating the DataSource Class .............................. 11-12
M Task 4 – Deleting Unnecessary Classes .................................. 11-15

A RO -trans Task 5 – Copying the TestReport Class .............................. 11-15

GEN non Task 6 – Compiling the TestReport Class ........................... 11-15


Task 7 – Running the BankPrj Project .................................. 11-15
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-5
Task 2 – Compiling the ChatClient Class ............................. 12-6

xiii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Task 3 – Running the ChatClient Program ........................... 12-6


Task 4 – Terminating the Running ChatClient Program ...... 12-7
Exercise 1: Creating the ChatClient GUI Part 1 (Level 3) ................. 12-8
Preparation ................................................................................. 12-8
Task 1 – Creating the ChatClient Class ................................ 12-8
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 2 – Compiling the ChatClient Class ........................... 12-10


Task 3 – Running the ChatClient Program ......................... 12-10
Task 4 – Terminating the Running ChatClient Program .... 12-11
Exercise 2: Creating the Bank ATM GUI Part 1
(Advanced)..................................................................................... 12-12
Preparation ............................................................................... 12-13
Task 1 – Copying the ATMClient Class................................. 12-13
Task 2 – Modifying the ATMClient Class ............................. 12-14
Task 3 – Compiling the ATMClient Class ............................. 12-14
Task 4 – Running the ATMClient Program ........................... 12-14
s a
h a
Hints......................................................................................... 12-15
)
c o m
Exercise Summary ............................................................................ 12-16
Handling GUI-Generated Events ..................................................

ail eฺ13-1
g m id 13-1
@
1 2 (Level G u
Objectives ..........................................................................................
Exercise 1: Creating the ChatClient GUI1Part
2 e n t 1)............. 13-2
2 0 ud............................. 13-2
Preparation .................................................................................
9
Task 1 – Modifying the ChatClient i n t S t
Class 13-3
s
Task 2 – Compiling(the ChatClient
a t h i s Class ............................. 13-3
Task 3 – Running A Nthe ChatClient
u s e Program ........................... 13-3
L seT R t o
Hints........................................................................................... 13-3
E
B1: Creating n the ChatClient GUI Part 2 (Level 2)............. 13-4
Exercise
O l i c e
R EN Preparation
b l ................................................................................. 13-4
e 1 – Modifying
M O feraTask 2 – Compiling the
Task the ChatClient Class ............................. 13-4

R O rans Task 3 – Running the ChatClient ChatClient Class ............................. 13-5

N A n-t Program ........................... 13-5


G E no Exercise 1: Creating the ChatClient GUI Part 2 (Level 3)............. 13-6
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

xiv Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Preparation ................................................................................. 14-3


Task 1 – Modifying the ChatClient Class ............................. 14-3
Task 2 – Compiling the ChatClient Class ............................. 14-3
Task 3 – Running the ChatClient Program ........................... 14-3
Exercise: Creating the ChatClient GUI, Part 3 (Level 2)............... 14-4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Preparation ................................................................................. 14-4


Task 1 – Modifying the ChatClient Class ............................. 14-4
Task 2 – Compiling the ChatClient Class ............................. 14-5
Task 3 – Running the ChatClient Program ........................... 14-5
Exercise: Creating the ChatClient GUI, Part 3 (Level 3)............... 14-6
Preparation ................................................................................. 14-6
Task 1 – Modifying the ChatClient Class ............................. 14-6
Task 2 – Compiling the ChatClient Class ............................. 14-9
Task 3 – Running the ChatClient Program ........................... 14-9
Exercise Summary ............................................................................ 14-10
s a
)
Threads............................................................................................15-1 h a
o m
ilฺc ฺ 15-2
Objectives .......................................................................................... 15-1
Exercise: Using Multithreaded Programming (Level a 1).....................
gm uide 15-2
Preparation .................................................................................
@
Task 1 – Creating the PrintMe Class 1 n G
1.......................................
t 15-3
0 2 e
Task 2 – Creating the TestThreeThreads
n t 9 2
S t ud Class ................... 15-3
Task 3 – Compiling the
s a i TestThreeThreads
i s Class................ 15-3
Task 4 – Running
N ( theusTestThreeThreads
t h
eProgramming Program .............. 15-4
Exercise: UsingA Multithreaded (Level 2)..................... 15-5
L TR .................................................................................
Preparation
e to 15-5
E s
BTask 1e–nCreating the PrintMe Class ....................................... 15-6
O
N leTask lic2 – Creating the TestThreeThreads Class ................... 15-6
E
M OR ferab Task 3 – Compiling the TestThreeThreads Class................ 15-6

R O rans Exercise:
Task 4 – Running the TestThreeThreads Program .............. 15-7

N A n-t Using Multithreaded Programming (Level 3)..................... 15-8


GE no Preparation ................................................................................. 15-8
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

xv
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Task 1 – Modifying the ChatClient Class ............................. 16-6


Task 2 – Compiling the ChatClient Class ............................. 16-7
Task 3 – Running the ChatRoomPrj Project ........................... 16-7
Exercise: Creating a Socket Client (Level 3)...................................... 16-9
Preparation ................................................................................. 16-9
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 1 – Modifying the ChatClient Class ............................. 16-9


Task 2 – Compiling the ChatClient Class ........................... 16-13
Task 3 – Running the ChatRoomPrj Project ......................... 16-13
Exercise Summary ............................................................................ 16-14

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

xvi Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Lab Preface
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

About This Workbook

Lab Goals
Upon completion of this workbook, you should be able to: a
Write a Java™ technology program using the fundamental language) h

as
c
elements: primitive types, reference types, arithmetic operators,o m
relational

ail eฺ
operators, conditional statements, and iterative statements
g m d
@
Write a Java technology program using good1object-orientedG uiprogramming

2
concepts and principles: encapsulation,0inheritance, n t
1 einterfaces,
polymorphism, object association,t9
n and
S t ud in associations
2 multiplicity
( sai program
Write a robust Java technology t h isusing exception handling, generic
AN ucontrol se

R
collections, and concurrency
to program using the graphical user interface
T technology
LJava
E
Write a rich
● s e
B enprogramming interfaces (APIs), input/output (I/O) APIs,
O
(GUI)
lic APIs
application
N networking
E l e
OR ferab
and
M
A nsworkbook presents the lab exercises for each module of the Student Guide.
RO -traThis
GEN non

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

Performing the Exercises


You have the option to complete any one of three versions of a lab. To decide
which to choose, consult the following descriptions of the levels:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

● Level 1 – This version of the lab provides the least amount of guidance.
Each bulleted paragraph provides a task description, but you must
determine your own way of accomplishing each task.
● Level 2 – This version of the lab provides more guidance. Although each
step describes what you should do, you must determine which commands
(and options) to input.
● Level 3 – This version of the lab is the easiest to accomplish because each
step provides exactly what you should input to the system. This level also
includes the task solutions for all three levels. s a
) h a
c o m
Also, several modules have advanced labs. These labs are optional. These labs are

ail eฺ
intended for more advanced students who complete the primary labs easily.
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

Lab Preface-xviii Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Conventions

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 dir to list all files.
system% You have mail.

s a
Courier is also used to indicate programming constructs, such as class names,
) h a
methods, and keywords; for example:
c o m

ail eฺ
The getServletInfo method is used to get author information.
g m id
The java.awt.Dialog class contains Dialog constructor.
@ G u
0 2 11 ent
Courier bold is used for characters and
t 9 d you type; for example:
2numberstuthat
n S
( sai type:
To list the files in this directory, t h is
# dir
R AN use
E LT se to
Courier bold
O B is also e nused for each line of programming code that is referenced
N le
in a textual l i c
description; for example:
E
M OR f1erimport
ab java.io.*;
A RO -trans 23 import javax.servlet.*;

GEN non import javax.servlet.http.*;


Notice the javax.servlet interface is imported to allow access to its life cycle
methods (Line 2).

Courier italics is used for variables and command-line placeholders that are
replaced with a real name or value; for example:
To delete a file, use the rm filename command.

Courier italic bold is used to represent variables whose values are to be


entered by the student as part of an activity; for example:
Type chmod a+rwx filename to grant read, write, and execute rights for
filename to world, group, and users.

About This Workbook Lab Preface-xix


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Conventions

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.
“The doIt() method...” refers to a method called doIt that takes no s a
arguments. ) h a
c o m
● ฺ
ail eฺ
Line breaks occur only where there are separations (commas), conjunctions
g m id
(operators), or white space in the code. Broken code is indented four spaces
@ G u
under the starting code.
0 2 11 ent

different from a command used ininthe
2 System
If a command used in the Solaris™ Operating
t9Microsoft
S ud (Solaris
tWindows OS) is
platform, both
( sa this
commands are shown; for example:
If working in the T R AN OS o u
se
E L se t
Solaris
B en
$ cd $SERVER_ROOT/bin
O
IfEworking lic Windows
N lineMicrosoft
M ORC:\>e r a b%SERVER_ROOT%\bin
O ransf
cd

A R t
G EN non-

Lab Preface-xx Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Lab 1
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Getting Started

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

Exercise 1: Exploring Java™ Program Errors


In this exercise, you view the source of several simple Java programs, and correct
their compilation and runtime errors.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task – Correcting Compilation and Runtime 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ฺ
Java Development: Java Classes: Modifying Java Classes: m
g Compilingid Java

@ G u
Classes
0 2 11 ent

t 9
Java Development: Java Classes: Modifying d Executing Java
2 JavatuClasses:
n S
Programs
( sai this
R AN u se
L T e to
For this exercise, you work in the TestProject project in the
E ns
d:\labs\student\exercises\01_intro\exercise1
B directory.
NO le lic e
E
R rab Compilation and Runtime Errors
TaskM–OCorrecting
fe
O n s
N AR n-Intrathis task, you are presented with four Java programs that contain errors. The
G E no errors can be either compilation or runtime errors. Your job is to diagnose and fix
those errors so the programs will execute.

Lab 1-2 Java™ Programming Language


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

Complete the following steps for the files Test1.java, Test2.java,


Test3.java and Test4.java:

Tool Reference – Java Development: Java Classes: Opening Java Classes


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1. Open the Java file.

Tool Reference – Java Development: Java Classes: Modifying Java Classes:


Compiling Java Classes
2. Compile the Java file.
3. If a compilation error occurs, identify the source of the error and fix it.
4. Repeat step 2 and step 3 until there are no more errors.
s a
Tool Reference – Java Development: Java Classes: Modifying Java Classes: ) h a
o m
Executing Java Programs
a ilฺc ฺ
5. Execute the Java program.
@ gm uide
1 1of the error
n t Gand fix it.
2
6. If a runtime error occurs, identify the source
20no more e
derrors.
t 9 t u
s a in is S
7. Repeat step 2 and step 3 until there are

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

Getting Started Lab 1-3


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Test Program (Level 1)

Exercise 2: Creating a Test Program (Level 1)


In this exercise, you create a test program (also known as a test harness) to
exercise a pre-provided class. These are the Level 1 instructions that provide
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

additional hints.

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
+deposit(amt:double):void
c o m
+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 – CopyingAthe

R
NAccount
u seClass”
LT sthe
“Task 2 –ECreating

e to
TestAccount Class”
B n
N
“Task ●
l ce the TestAccount Class”
O 3 – Compiling
i
O RE “Taska b le– Running the TestAccount Program”
M sfer
●4
O
R -tran
A
G EN noPreparation
n
No preparation is needed for this exercise.

Tool Reference – Tool references used in this exercise:


● Java Development: Java Application Projects: Creating Projects
● Java Development: Java Classes: Modifying Java Classes: Copying Java
Classes
● Java Development: Java Classes: Creating Java Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs

Lab 1-4 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Test Program (Level 1)

Task 1 – Copying the Account Class


In this task, you create the BankPrj project, and copy the pre-provided
Account class to the project.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Java Development: Java Application Projects: Creating


Projects
1. Create the BankPrj Java Application Project with the following
characteristics:
Project Name: BankPrj
Project Location: d:\labs\student\projects
Project Folder: d:\labs\student\projects\BankPrj
s a
Set as Main Project: No ) h a
c o m
Create Main Class: No ฺ
ail eฺ
m
g Java idClasses:
Tool Reference – Java Development: Java Classes: @ G u
Copying Java Classes 0 2 11 ent
Modifying

t 9 2 t u d
n S
sai this source file from the directory
2. Copy the pre-provided Account.java
(
se project.
ANof the uBankPrj
d:\labs\student\resources\01_intro\exercise2
R
to the source package
LT se to
E
B en
Task 2 E –N
O
Creating lic the TestAccount Class
l e
M OR ferab
s task, you complete the following steps to create a new TestAccount
RO -traInnthis
A
GEN non Java class.
Tool Reference – Java Development: Java Classes: Creating Java Classes
1. Create a new Java class in the BankPrj project with the following
characteristics:
Class Name: TestAccount
Project: BankPrj
Location: Source Packages
Package: default package
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.

Getting Started Lab 1-5


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Test Program (Level 1)

Task 3 – Compiling the TestAccount Class


Compile the TestAccount class, and make necessary changes to correct
compilation errors.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 4 – Running the TestAccount Program


Run the TestAccount program. If there are runtime errors, make necessary
changes to the TestAccount class, recompile it, and run the program again.

The output of the TestAccount program should be similar to the following:

Final account balance is: 3.0 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

Lab 1-6 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Test Program (Level 2)

Exercise 2: Creating a Test Program (Level 2)


In this exercise, you create a test harness (a test class) to exercise a pre-provided
class. These are the Level 2 instructions that provide additional hints.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Copying the Account Class”
● “Task 2 – Creating the TestAccount Class”
● “Task 3 – Compiling the TestAccount Class”
● “Task 4 – Running the TestAccount Program”

s a
Preparation
) h a
c o m
No preparation is needed for this exercise. ฺ
ail eฺ
g m id
@ G u
11 ent
Tool Reference – Tool references used in this2exercise:
0
t 9 d Projects
2Projects:tuCreating
n
Java Development: Java Application S
sai Modifying

( t h is Java Classes: Copying Java


AN use
Java Development: Java Classes:

Classes R
LT sJava to
E e
B en Classes: Creating Java Classes
Java Development:

O lic Java Classes: Modifying Java Classes: Compiling Java
N Development:
E Java

l e
M OR fClasses
e rab
A RO -trans Java
● Development: Java Classes: Modifying Java Classes: Executing Java

GEN non Programs

Getting Started Lab 1-7


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Test Program (Level 2)

Task 1 – Copying the Account Class


In this task, you create the BankPrj project, and copy the pre-provided
Account class to the project.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Java Development: Java Application Projects: Creating


Projects
1. Create the BankPrj Java Application Project with the following
characteristics:
Project Name: BankPrj
Project Location: d:\labs\student\projects
Project Folder: d:\labs\student\projects\BankPrj
s a
Set as Main Project: No ) h a
c o m
Create Main Class: No ฺ
ail eฺ
m id
g Java uClasses:
Tool Reference – Java Development: Java Classes: Modifying @
11 ent G
Copying Java Classes
2 0 2 d
n t 9 S t u
2. Copy the pre-provided Account.java
( sai thsource
is file from the directory
AN se project.
d:\labs\student\resources\01_intro\exercise2
R
to the source package of u
the BankPrj
E LT se to
O B en
Task 2 – Creating
E N le lthe ic TestAccount Class
M OR ferab
A RO -Intrathisnstask, you complete the following steps to create a new TestAccount
G EN non 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.

Lab 1-8 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Test Program (Level 2)

4. Use the deposit method to add 50 to the account.


5. Use the withdraw method to subtract 147 from the account.
6. Use the getBalance method to retrieve the new account balance and use
the System.out.println method to display the balance to the standard
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

output stream.

Task 3 – Compiling the TestAccount Class


Compile the TestAccount class, and make necessary changes to correct
compilation errors.

Task 4 – Running the TestAccount Program s a


) h a
c o m

ail eฺ
Run the TestAccount program. If there are runtime errors, make necessary
g m
changes to the TestAccount class, recompile it and run the program again.
id
@ G u
The output of the TestAccount program should2be
0 11similarentot the following:
n t 9 2
S t ud
Final account balance sis:
( ai 3.0 t h is
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non

Getting Started Lab 1-9


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Test Program (Level 3)

Exercise 2: Creating a Test Program (Level 3)


In this exercise, you create a test harness (a test class) to exercise a pre-provided
class. These are the Level 3 instructions that provide additional hints with code
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

snippets.

This exercise contains the following sections:


● “Task 1 – Copying the Account Class”
● “Task 2 – Creating the TestAccount Class”
● “Task 3 – Compiling the TestAccount Class”
● “Task 4 – Running the TestAccount Program”

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 this 9 2 02 uden
exercise:
i n t S t
a
(s eProjects:
Java Development: Java Application
● i s
th Creating Projects
N s
AClasses:uModifying

L T R
Java Development: Java
t o Java Classes: Copying Java
Classes
B E nse
JavaN
● O liceJava Classes: Creating Java Classes
Development:
E Development:
RJava b le Java Classes: Modifying Java Classes: Compiling Java
O ●
M Classes
f er a
O s
R -tranJava Development: Java Classes: Modifying Java Classes: Executing Java
A
G EN non ●
Programs

Lab 1-10 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Test Program (Level 3)

Task 1 – Copying the Account Class


In this task, you create the BankPrj project, and copy the pre-provided
Account class to the project.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Java Development: Java Application Projects: Creating


Projects
1. Create the BankPrj Java Application Project with the following
characteristics:
Project Name: BankPrj
Project Location: d:\labs\student\projects
Project Folder: d:\labs\student\projects\BankPrj
s a
Set as Main Project: No ) h a
c o m
Create Main Class: No ฺ
ail eฺ
m
g Java idClasses:
Tool Reference – Java Development: Java Classes: @ G u
Copying Java Classes 0 2 11 ent
Modifying

t 9 2 t u d
n S
sai this source file from the directory
2. Copy the pre-provided Account.java
(
se project.
ANof the uBankPrj
d:\labs\student\resources\01_intro\exercise2
R
to the source package
LT se to
E
B en
Task 2 E –N
O
Creating lic the TestAccount Class
l e
M OR ferab
s task, you complete the following steps to create a new TestAccount
RO -traInnthis
A
GEN non 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
}
}

Getting Started Lab 1-11


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Test Program (Level 3)

3. Declare a variable of type Account and initialize that variable by creating


an instance of the Account class with an initial balance of 100.
Account acct = new Account(100.0);
4. Use the deposit method to add 50 to the account.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

acct.deposit(50.0);
5. Use the withdraw method to subtract 147 from the account.
acct.withdraw(147.0);
6. Use the getBalance method to retrieve the new account balance and use
the System.out.println method to display the balance to the standard
output stream.
System.out.println(“Final account balance is ” + acct.getBalance());

s a
Task 3 – Compiling the TestAccount Class ) h a
c o m

atoilcorrecteฺ
Compile the TestAccount class, and make necessary changes
g m id
@ G u
11 ent
compilation errors.
0 2
n t 9 2
S t ud
Task 4 – Running the TestAccount ( sai thisProgram
R AN use
Run the TestAccount
E LTprogram.
e toIf there are runtime errors, make necessary
s
B en class, recompile it and run the program again.
changes to the TestAccount
O
N le lic
E
M OR
The
e r b TestAccount program should be similar to the following:
output ofathe

R O Final
a n sf
A tr
EN non-
account balance is: 3.0
G

Lab 1-12 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

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

Getting Started Lab 1-13


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 2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Object-Oriented Programming

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

Exercise 1: Using the Java API Documentation


In this exercise, you explore the Java™ Platform, Standard Edition 6 (Java SE 6)
API documentation to explore the methods of a class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task – 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
1. Open the Java™ Platform, Standard Edition 2 61
1 nt G
2 0 d e
API Specification Web page
in the browser.
i n t9 Stu
( sa this
ANfor Java
u e
sPlatform
L T R
Note – The API documentation
t o SE 6 can be found at
E nse
http://java.sun.com/javase/6/docs/api.
B
N O lice
E thebjava.text
Rpanel
2. Select le package in the package list in the upper-left corner
O a
M sfeofr the API frameset.
O
R -t3.ranSelect the NumberFormat class in the class list in the lower-left panel.
A
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.

Lab 2-2 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Exploring Encapsulation, Version 1 (Level 1)

Exercise 2: Exploring Encapsulation, Version 1 (Level 1)


In this exercise, you explore the purpose of proper object encapsulation. You
create a class in two steps to demonstrate the use of information hiding. In this
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
@
1 NonHidingG u
Figure 2-1 UML Class Diagram of Account 2 1With e t
9 2 0 ud
i n t S t
saapplies
There is only one business rule(that t htoisthe Account class: The balance of
A
the bank account must never
R
Ngo below
u sezero. In this exercise, you will discover
LT cannot
that the Account class
E e toensure this business rule.
B en s
O lic the following sections:
N lcontains
This exercise
E e
M OR f“Taske
● rab1 – Deleting the Account Class”
A RO -trans “Task 2 – Creating the Account Class”

GEN non “Task 3 – Creating the TestAccount2 Class”


● “Task 4 – Compiling the TestAccount2 Class”


● “Task 5 – Running the TestAccount2 Program”

Object-Oriented Programming Lab 2-3


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Exploring Encapsulation, Version 1 (Level 1)

Preparation
No preparation is needed for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Tool references used in this exercise:


● Java Development: Other Files: Deleting Files
● Java Development: Java Classes: Creating Java Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
s a
For this exercise, you work in the BankPrj project in the
) h a
d:\labs\student\projects directory.
c o m

ail eฺ
g m id
Task 1 – Deleting the Account Class @ G u
0 2 11 ent
n t 9 2
S t ud
( sai Other
Tool Reference – Java Development: t h isFiles: Deleting Files
R AN use
In this task, you L
E delete to class copied in Lab 1.
T theeAccount
B en s
O
N le lic
E
OR2 –feCreating
Task
M rab the Account Class
A RO -trans
G EN non In this task, you create the Account class according to the UML diagram in
Figure 2-1. The class should have the following characteristics:
Class Name: Account
Project: BankPrj
Location: Source Packages
Package: default package

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.

Lab 2-4 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Exploring Encapsulation, Version 1 (Level 1)

Task 3 – Creating the TestAccount2 Class


In this task, you create the TestAccount2 class with the following
characteristics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Class Name: TestAccount2


Project: BankPrj
Location: Source Packages
Package: default package

This class acts as a program to create an Account object with an initial balance
of 100. The test program will then add 47 and then subtract 150. Finally, the test
program must print out the balance of the object to the standard output stream.
s a
) h a
Task 4 – Compiling the TestAccount2 Class ilฺcom
g ma ideฺ
In this task, you compile the TestAccount2 class, 1 @ G
and make u
necessary
1 t
changes to correct compilation errors.
9 2 02 uden
a i nt is St
Task 5 – Running the N (s e th
TestAccount2 Program
R A u s
E LT se to
B run ethenTestAccount2 program.
In this task, you
O
E N le lic
R output
OThe r a bshould be similar to the following:
M e
sf account balance is -3.0
O raFinal
R n
E NA on-t
G n

Object-Oriented Programming Lab 2-5


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Exploring Encapsulation, Version 1 (Level 2)

Exercise 2: Exploring Encapsulation, Version 1 (Level 2)


In this exercise, you explore the purpose of proper object encapsulation. These
are the Level 2 instructions, which provide additional hints.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Deleting the Account Class”
● “Task 2 – Creating the Account Class”
● “Task 3 – Creating the TestAccount2 Class”
● “Task 4 – Compiling the TestAccount2 Class”
● “Task 5 – Running the TestAccount2 Program”
s a
) h a
Preparation c o m

ail eฺ
g m id
No preparation is needed for this exercise. @ G u
0 2 11 ent
9
Tool Reference – Tool references used in tthis2exercise:tud
a i n i s S
s h

A N ( uDeleting
Java Development: Other Files:
s e t Files
Java Development:

L R Classes:
TJava t o Creating Java Classes
BE eJava
Java Development: n e
sClasses: Modifying Java Classes: Compiling Java

O
N le lic
E
Classes

M ORJavafeDevelopment:
● rab Java Classes: Modifying Java Classes: Executing Java
O s
R -tranPrograms
A
G EN non For this exercise, you work in the BankPrj project in the
d:\labs\student\projects directory.

Lab 2-6 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Exploring Encapsulation, Version 1 (Level 2)

Task 1 – Deleting the Account Class

Tool Reference – Java Development: Other Files: Deleting Files


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

In this task, you delete the Account class copied in Lab 1.

Task 2 – Creating the Account Class


In this task, you complete the following steps to create a Java class named
Account:
1. Create the Account class with the following characteristics:
s a
Class Name: Account ) h a
c o m
Project: BankPrj
a il ฺ
Location: Source Packages g m i d eฺ
1 1 @ t Gu
Package: default package
9 2 02 uden
2. Add the balance instance variable.
a i nt is St
3. Add a constructor that sets
N (sthe balance
e th instance variable to the initial
balance argument
T R A to the
passed
t o usconstructor.
B EL nse
Task 3 E –N O licethe TestAccount2 Class
Creating
O R rable
O M sfe
A nthis task, you complete the following steps to create a Java class named
R -traInTestAccount2:
GEN non
1. Create the TestAccount2 class with the following characteristics:
Class Name: TestAccount2
Project: BankPrj
Location: Source Packages
Package: default package
2. Add the main method:
a. Declare a variable within the main method of type Account named
acct. Also, in the same statement, initialize the variable acct to a
new instance of Account by passing 100.00 to the constructor as the
initial balance.
b. Use the addition operator to add 47 to the account object’s balance.
c. Use the subtraction operator to subtract 150 from the account object’s
balance.
Object-Oriented Programming Lab 2-7
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Exploring Encapsulation, Version 1 (Level 2)

d. Use the System.out.println method to display the balance to the


standard output stream.

Task 4 – Compiling the TestAccount2 Class


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

In this task, you compile the TestAccount2 class and the Account class, and
make necessary changes to correct compilation errors.

Task 5 – Running the TestAccount2 Program


In this task, you run the TestAccount2 program.

s a
The output should be similar to the following:
) h a
c o m
Final account balance is -3.0

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

Lab 2-8 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Exploring Encapsulation, Version 1 (Level 3)

Exercise 2: Exploring Encapsulation, Version 1 (Level 3)


In this exercise, you explore the purpose of proper object encapsulation. These
are the Level 3 instructions, which provide additional hints with code snippets.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Deleting the Account Class”
● “Task 2 – Creating the Account Class”
● “Task 3 – Creating the TestAccount2 Class”
● “Task 4 – Compiling the TestAccount2 Class”
● “Task 5 – Running the TestAccount2 Program”
s a
) h a
Preparation c o m

ail eฺ
g m id
No preparation is needed for this exercise. @ G u
0 2 11 ent
Tool Reference – Tool references usedt9
n S t ud
in2this exercise:
sai Deleting
Java Development: Other(Files: t h is Files

N use
AJava
R
Java Development:

L o
T e tClasses: Creating Java Classes
BE ensJava Classes: Modifying Java Classes: Compiling Java
Java Development:
O
N le lic

E Classes

M OR fJava
e ●
b
raDevelopment: Java Classes: Modifying Java Classes: Executing Java
O s
R -tran Programs
A
GEN non For this exercise, you work in the BankPrj project in the
d:\labs\student\projects directory.

Object-Oriented Programming Lab 2-9


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Exploring Encapsulation, Version 1 (Level 3)

Task 1 – Deleting the Account Class

Tool Reference – Java Development: Other Files: Deleting Files


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

In this task, you delete the Account class copied in Lab 1.

Task 2 – Creating the Account Class


In this task, you complete the following steps to create a Java class named
Account:
1. Create the Account class with the following characteristics:
s a
Class Name: Account ) h a
c o m
Project: BankPrj
a il ฺ
Location: Source Packages g m i d eฺ
1 1 @ t Gu
Package: default package
9 2 02 uden
2. Add the balance instance variable.
a i nt is St
public double balance;
N (s e th
3. Add a constructor that
T R t o us to the initial balance argument
Asets the balance
passed to the E L se
constructor.
O B e n {
l i c
EN ble
public Account(double initBalance)
R
balance = initBalance;
O fera
} M
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

Lab 2-10 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Exploring Encapsulation, Version 1 (Level 3)

2. Add the main method:


public static void main(String[] args) {
// code here
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

3. Declare a variable within the main method of type Account named acct.
Also, in the same statement, initialize the variable acct to a new instance
of Account by passing 100.00 to the constructor as the initial balance.
Account acct = new Account(100.0);
4. Use the addition operator to add 47 to the account object’s balance.
acct.balance = acct.balance + 47.0;
5. Use the subtraction operator to subtract 150 from the account object’s
balance.
s a
acct.balance = acct.balance - 150.0;
) h a
6. m
Use the System.out.println method to display the balance to the
c o
standard output stream. ฺ
ail eฺ
System.out.println(“Final account balance is ” + acct.balance); g m id
@ G u
0 2 11 ent
Task 4 – Compiling the TestAccount2 n t 9 2
S t udClass
( sai this
R
In this task, you compile u se
AtheNTestAccount2
to compilation class
LT stoecorrect
make necessaryEchanges
and the Account class, and
errors.
O B en
E N le lic
Task
M OR a
5 – eRunning
f r b the TestAccount2 Program
A RO -trans
GEN non In this task, you run the TestAccount2 program.
The output should be similar to the following:
Final account balance is -3.0

Object-Oriented Programming Lab 2-11


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 3: Exploring Encapsulation, Version 2 (Level 1)

Exercise 3: Exploring Encapsulation, Version 2 (Level 1)


In this exercise, you explore the purpose of proper object encapsulation. You
modify the Account class to hide its data member and provide public methods to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
Account
) h a
c o m
-balance : double

ail eฺ
«constructors»
g m id
+Account(initBalance:double) @ G u
0 2 11 ent
ud
«methods»
t 9 2 t
+getBalance():double
n S
+deposit(amt:double):void
( sai this
AN use
+withdraw(amt:double):void

Figure 2-2
R
LT Diagram toof Account With Information Hiding
E
UML Class
B en s e
O licone business rule that must be maintained: The balance
Nthere lisestill
E
R raccount
Remember,
b must never go below zero. This business rule should be
MofO
the banke a
R a n sfin the withdraw method.
O enforced
A tr
G EN non- 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.

Lab 2-12 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 3: Exploring Encapsulation, Version 2 (Level 1)

Tool Reference – Tool references used in this exercise:


● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

● Java Development: Java Classes: Modifying Java Classes: Executing Java


Programs

For this exercise, you work in the BankPrj project in the


d:\labs\student\projects directory.

Task 1 – Modifying the Account Class


In this task, you modify the Account class source file. This class must satisfy the s a
UML diagram in Figure 2-2. ) h a
c o m

ail eฺ
Task 2 – Modifying the TestAccount Class g m id
@ G u
0 2 11 ent
t 9
In this task, you modify the TestAccount d 47 to and withdraw
2 class totudeposit
150 from the Account object. ai n is S
( s t h
R AN use
Task 3 – Compiling LT the e o
tTestAccount Class
B E n s
NO le lic e
In E
Rthis task, byou compile the TestAccount class and the Account class.
O
M sfe r a
O
R -tran
A
GEN noTask
n 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

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.

Object-Oriented Programming Lab 2-13


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 3: Exploring Encapsulation, Version 2 (Level 2)

Exercise 3: Exploring Encapsulation, Version 2 (Level 2)


In this exercise, you explore the purpose of proper object encapsulation. These
are the Level 2 instructions, which provide additional hints.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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”

s a
Preparation
) 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:
t 9 d Compiling Java
2 JavatuClasses:
n
Java Development: Java Classes: Modifying S
sai this

Classes (
R
Java Development: Java se
N uModifying
AClasses: Java Classes: Executing Java

L T e to
BE ens
Programs
O
N lyou c in the BankPrj project in the
liwork
For thisEexercise, e
M OR ferab
d:\labs\student\projects directory.

A RO -trans
G EN Task
non 1 – Modifying the Account Class
In this task, you complete the following steps to modify the Account class:
1. Change the balance instance variable from public to private.
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 instance variable.
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.

Lab 2-14 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 3: Exploring Encapsulation, Version 2 (Level 2)

This operation might set the balance to a value below zero if the 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> ) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

<statement_when_true>*
} else {
<statement_when_false>*
}
4. Add the getBalance method to return the balance instance variable.

Task 2 – Modifying the TestAccount Class


s a
In this task, you complete the following steps to modify the TestAccounth
) a
class:
o m
ilฺc ฺ
1. Change the amount in the call to the deposit method to 47.0.
a
2. Change the amount in the call to the withdraw method
@ ide
gm to u150.0.
2 1 1 nt G
Task 3 – Compiling the TestAccount t 9 de
20 tuClass
s a in is S
N ( e th
In this task, you compile
T R t o us
Athe TestAccount class and the Account class.
L
E nse
B
O licethe TestAccount Program
Task 4 E –N Running
O R rable
O M sfe
A R -tratoInnthe
this task, you run the TestAccount program. The output should be similar

GEN non following:


Final account balance is 147.0

Object-Oriented Programming Lab 2-15


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 3: Exploring Encapsulation, Version 2 (Level 3)

Exercise 3: Exploring Encapsulation, Version 2 (Level 3)


In this exercise, you explore the purpose of proper object encapsulation. These
are the Level 3 instructions, which provide additional hints with code snippets.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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”

s a
Preparation
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
11 ent
Tool Reference – Tool references used in this2exercise:
0
Java Development: Java Classes:n t 9 2
S
Modifyingt ud Classes: Compiling Java
Java
sai this

Classes (
R
Java Development:
N Classes:
AJava u seModifying Java Classes: Executing Java
ProgramsELT to

B en s e
O
N exercise, c work in the BankPrj project in the
liyou
ForEthis l e
R rab
Od:\labs\student\projects
M f e directory.

A RO -trans
G EN noTask
n 1 – Modifying the Account Class
In this task, you complete the following steps to modify the Account class:
1. Change the balance instance variable from public to private.
private double balance;
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;
}
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.

Lab 2-16 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 3: Exploring Encapsulation, Version 2 (Level 3)

public void withdraw(double amt) {


if ( amt <= balance ) {
balance = balance - amt;
}
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

4. Add the getBalance method to return the balance instance variable.


public double getBalance() {
return balance;
}

Task 2 – Modifying the TestAccount Class


In this task, you complete the following steps to modify the TestAccount class:
s a
1. Change the amount in the call to the deposit method to 47.0. ) h a
c o m
acct.deposit(47.0); ฺ
ail eฺ
m id
g to u150.0.
2. Change the amount in the call to the withdraw method
@
11 ent G
acct.withdraw(150.0);
0 2
n t 9 2
S t ud
Task 3 – Compiling the ( sai this Class
TestAccount
R AN use
E to
LT sthee TestAccount
O B en
In this task, you compile class and the Account class.

E N le lic
Task
M OR rab
4 –feRunning the TestAccount Program
O
R -tran s
A
GEN non In this task, you run the TestAccount program. The output should be similar
to the following:
Final account balance is 147.0

Object-Oriented Programming Lab 2-17


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 4: Creating Java Packages

Exercise 4: Creating Java Packages


In this exercise, you will place the Account class and TestAccount class into
different packages.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
TestAccount Account ) h a
c o m

ail eฺ
-balance : double
+main(args:String[])
g m id
«constructors»
@ G u
0 2 11 ent
+Account(initBalance:double)

n 9 2
«methods»
t S t ud
sai +deposit(amt:double):void
is
+getBalance():double
( t h
R AN use+withdraw(amt:double):void
E LT se to
O B en
Figure E2-3N The l e lic Structure of the Banking Project
Package
M OR ferab
RO -This s contains the following sections:
anexercise
A t r
G EN non 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

Lab 2-18 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 4: Creating Java Packages

Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Tool references used in this exercise:


● Java Development: Java Packages: Creating Java Packages
● Java Development: Java Classes: Moving Java Classes (without refactoring)
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
s a
For this exercise, you work in the BankPrj project in the
) h a
d:\labs\student\projects directory.
c o m

ail eฺ
g m id
Task 1 – Creating the Java Packages @ G u
0 2 11 ent
n t 9 2
S t ud
( sai JavathPackages:
Tool Reference – Java Development: is Creating Java Packages
A N us e
T R t o
EL twoeJava Source Packages in the BankPrj project with
In this task, you create
the followingBnames:ens
N O lic
E le
R com.mybank.domain
b
O er a
M sfcom.mybank.test
O
R -tran
A
GEN non Task 2 – Moving and Modifying the Account Class
In this task, you complete the following steps to move the Account class and
add the appropriate package statement to the class:

Tool Reference – Java Development: Java Classes: Moving Java Classes


(without refactoring)
1. Move the Account class source file to the com.mybank.domain
package.
2. Add the following package statement at the top of the Account class:
package com.mybank.domain;

Object-Oriented Programming Lab 2-19


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 4: Creating Java Packages

Task 3 – Moving the TestAccount Class


In this task, you complete the following steps to move the TestAccount class
and add the appropriate package and import statements to the class:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1. Move the TestAccount class source file to the com.mybank.test


package.
2. Add the following package statement at the top of the TestAccount
class:
package com.mybank.test;
3. Add the following import statement under the package statement in the
TestAccount class if has not already been added by your editor:
import com.mybank.domain.Account;
s a
) h a
Task 4 – Compiling the TestAccount Class c o m

ail eฺ
g m id
@ G u
In this task, you compile the TestAccount class and
0 2 11 ent
the Account class.

n t 9 2
S t ud
Task 5 – Running the TestAccount ( sai thisProgram
R AN use
LTTestAccount
In this task, you run the
E e to program. The code has not changed, so
the output shouldBbe similare s
nto the following:
O l i c
N lebalance is 147.0
R Eaccount
M O ferab
Final

A RO -trans
G EN non

Lab 2-20 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

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

Object-Oriented Programming Lab 2-21


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 3
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Identifiers, Keywords, and Types

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

Exercise 1: Investigating Reference Assignment


In this exercise, you will investigate reference variables, object creation, and
reference variable assignment.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
+y : int s a
) h a
+toString() : String
c o m

ail eฺ
Figure 3-1 UML Class Diagram for the MyPoint Class g m id
@ G u
0 211object
e n t
Your task is to create a test program that 2
n t 9 explores
S t ud references.

( sai sections:
This exercise contains the following t h is
R u se Class”
AtheNTestMyPoint

E LT se to
“Task 1 – Creating
“Task B e
2 – Compilingn the TestMyPoint Class”

O l i c
R EN “Taskb3le
● – Running the TestMyPoint Program”
O
M sfer a
O an
R Preparation
r
A - t
G EN non
No preparation is needed for this exercise.

Tool Reference – Tool references used in this exercise:


● Java Development: Java Application Projects: Opening Projects
● Java Development: Java Classes: Creating Java Classes
● 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 PointProject project in the


d:\labs\student\exercises\03_types\exercise1 directory.

Lab 3-2 Java™ Programming Language


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

Task 1 – Creating the TestMyPoint Class

Tool Reference – Java Development: Java Application Projects: Opening


Projects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Complete the following steps:


1. Open the PointProject project in the
d:\labs\student\exercises\03_types\exercise1 directory.
2. Create the TestMyPoint class with the following characteristics:
Class Name: TestMyPoint
Project: PointProject
s a
Location: Source Packages
) h a
Package: default package c o m

aiinl theemain

3. Create a main method, and complete the following m steps d
g
@ t Gu i
method:
1 1 n start and end.
a. 2 02 uanddecalled
Declare two variables of type MyPoint
9
i nt a new
Assign both of these variables t
SMyPoint object.
s a
( of start h i s
t to 10. Set the x value of end to 20
b. Set the x and y N
A values
u s e
R to t30.
and the yTvalue
L o
B
c. Print e variables. Use code similar to:
Eout bothnspoint
e
NO System.out.println("Start
lic
R E b l e point is " + start);
M O fd.eraTo make sure that you are using the MyPoint class correctly, you
A RO -trans might want to compile and run TestMyPoint now (see “Task 2 –

GEN non Compiling the TestMyPoint Class” and “Task 3 – Running the
TestMyPoint Program”). If you do so, the output will look
something like the following:
Start point is [10,10]
End point is [20,30]
e. Declare a new variable of type MyPoint and call it stray. Assign
stray the reference value of the existing variable end.
f. Print out stray and end.
g. Assign new values to the x (such as 47) and y (such as 50) members
of the variable stray.
h. Print out stray, end, and start.

Identifiers, Keywords, and Types Lab 3-3


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

Task 2 – Compiling the TestMyPoint Class


In this task, you compile the TestMyPoint class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 3 – Running the TestMyPoint Program


In this task, you run the TestMyPoint program.

The output should look similar to the following:


Start point is [10,10]
End point is [20,30]

s a
Stray point is [20,30]
) h a
End point is [20,30]
c o m

ail eฺ
Stray point is [47,50]
g m id
End point is [47,50] @ G u
Start point is [10,10]
0 2 11 ent
n t 9 2
S t ud
i
The values reported by end reflect theachange
s is in stray, indicating that
made
(
both variables refer to the sameNMyPointe t h
changed, which indicates R s object.of However,
Ait is independent
u
start has not

L T e to
that the other two variables.

O BE ens
E N le lic
M OR ferab
A RO -trans
G EN non

Lab 3-4 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating Customer Accounts (Level 1)

Exercise 2: Creating Customer Accounts (Level 1)


In this exercise, you expand the Banking project by adding a Customer class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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 -balance : double
-lastName : String
s a
-account : Account
«constructors»
) h a
c o m
+Account(initBalance:double)
«constructors»

ail eฺ
«methods»
+Customer(f:String, l:String)
g m id
+getBalance():double
«methods»
@ G u
11 ent
+deposit(amt:double):void
+getFirstName():String
0 2 +withdraw(amt:double):void
+getLastName():String
n t 9 2
S t ud
sai this
+getAccount():Account
+setAccount(acct:Account):void (
R AN use
Figure 3-2 E
UML to for the Customer Class
LTClassseDiagram
O B en
E e lic the following sections:
N lcontains
OR ferab
This exercise
M
O rans “Task 1 – Creating the Customer Class”

A R t
GEN non- ● “Task 2 – Copying the TestBanking Class”
● “Task 3 – Compiling the TestBanking Class”
● “Task 4 – Running the TestBanking Program”

Identifiers, Keywords, and Types Lab 3-5


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating Customer Accounts (Level 1)

Preparation
No preparation is needed for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Tool references used in this exercise:


● Java Development: Java Classes: Creating Java Classes
● Java Development: Java Classes: Modifying Java Classes: Copying Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
s a
) h a
For this exercise, you work in the BankPrj project in the
c o m
d:\labs\student\projects directory. ฺ
ail eฺ
g m id
@ G u
Task 1 – Creating the Customer Class 0 2 11 ent
n t 9 2
S t ud
i
saclass is
(
In this task, you create the Customer t
to hsatisfy the UML diagram in
Figure 3-2. The class has RtheAfollowing se
N ucharacteristics:
E LT se to
Class Name:
O B en
Customer

E N BankPrj
Project:
l e lic
M ORLocation:
e r a bSource Packages
R sf
O ranPackage:
N A n-t com.mybank.domain
G E no In the constructor, initialize the firstName and lastName instance variables
with the constructor parameters.

Task 2 – Copying the TestBanking Class


In this task, you copy the TestBanking.java file from the
d:\labs\student\resources\03_types\exercise2 directory into the
com.mybank.test source package of the BankPrj project.

Lab 3-6 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating Customer Accounts (Level 1)

Task 3 – Compiling the TestBanking Class


In this task, you compile the TestBanking class. If there are compilation
errors, you should correct them by modifying the Customer class accordingly
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

and then compile the TestBanking class again.

Task 4 – Running the TestBanking Program


In this task, you run the TestBanking program. The output should be similar
to the following:
Creating the customer Jane Smith.
Creating her account with a 500.00 balance.
s a
Withdraw 150.00
Deposit 22.50 ) h a
c o m
Withdraw 47.62 ฺ
ail eฺ
Customer [Smith, Jane] has a balance of 324.88
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

Identifiers, Keywords, and Types Lab 3-7


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating Customer Accounts (Level 2)

Exercise 2: Creating Customer Accounts (Level 2)


In this exercise you expand the Banking project by adding a Customer class.
These are the Level 2 instructions, which provide additional hints.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Creating the Customer Class”
● “Task 2 – Copying the TestBanking Class”
● “Task 3 – Compiling the TestBanking Class”
● “Task 4 – Running the TestBanking Program”

s a
Preparation
) 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 this exercise:
0 2 11 ent
n t
Java Development: Java Classes: Creating 9 S t ud
2 Java Classes

i
saModifying isJava Classes: Copying Java
( t h
AN use
Java Development: Java Classes:

Classes R to
LTJavasClasses:
E
B en
Java Development:
● e Modifying Java Classes: Compiling Java
O
N le lic
Classes
E
M ORJavafeDevelopment:

r ab Java Classes: Modifying Java Classes: Executing Java

RO -trans
Programs
A
G EN non For this exercise, you work in the BankPrj project in the
d:\labs\student\projects directory.

Lab 3-8 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating Customer Accounts (Level 2)

Task 1 – Creating the Customer Class


In this task, you create the Customer class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Complete the following steps:


1. Create the Customer class with the following characteristics:
Class Name: Customer
Project: BankPrj
Location: Source Packages
Package: com.mybank.domain
2. Declare three private instance variables: firstName, lastName, and
s a
account.
) h a
3. m
Declare a public constructor that takes two parameters (f and l) that
c o
populate the object instance variables. ฺ
ail eฺ
m
g variables;idthe methods
4. Declare two public accessors for the object instance
@ G
1 appropriate u
getFirstName and getLastName return1the
2 e n t instance
variable.
9 2 0 ud
n t S t
5. Declare the getAccount s
( ai tothretrieve
method is the account instance
variable.
R AN use
6. Declare the L T e tomethod to assign the account instance variable.
setAccount
E
B ens
O
N le lic
E
M OR
Task 2 – Copying
e r a b the TestBanking Class
R O ransf
A t In this task, you copy the TestBanking.java file from the
GEN non- d:\labs\student\resources\03_types\exercise2 directory into the
com.mybank.test source package of the BankPrj project.

Task 3 – Compiling the TestBanking Class


In this task, you compile the TestBanking class. If there are compilation
errors, you should correct them by modifying the Customer class accordingly
and then compile the TestBanking class again.

Identifiers, Keywords, and Types Lab 3-9


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating Customer Accounts (Level 2)

Task 4 – Running the TestBanking Program


In this task, you run the TestBanking program. The output should be similar
to the following:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Creating the customer Jane Smith.


Creating her account with a 500.00 balance.
Withdraw 150.00
Deposit 22.50
Withdraw 47.62
Customer [Smith, Jane] has a balance of 324.88

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

Lab 3-10 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating Customer Accounts (Level 3)

Exercise 2: Creating Customer Accounts (Level 3)


In this exercise you will expand the Banking project by adding a Customer
class. These are the Level 3 instructions, which provide additional hints with code
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

snippets.

This exercise contains the following sections:


● “Task 1 – Creating the Customer Class”
● “Task 2 – Copying the TestBanking Class”
● “Task 3 – Compiling the TestBanking Class”
● “Task 4 – Running the TestBanking Program”

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 9 02exercise:
in2this u d en
i n t S t
a
(s eCreating
Java Development: Java Classes:
● i s
th Java Classes
N us Modifying Java Classes: Copying Java
AJava Classes:
Java Development:

T R t o
Classes EL
B e n se
N ODevelopment:
Java

l ic Java Classes: Modifying Java Classes: Compiling Java
E
R Classes bl e
O
M sfJava r a
e Development: Java Classes: Modifying Java Classes: Executing Java
O n ●

N AR n-tra Programs
GE no
For this exercise, you work in the BankPrj project in the
d:\labs\student\projects directory.

Identifiers, Keywords, and Types Lab 3-11


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating Customer Accounts (Level 3)

Task 1 – Creating the Customer Class


In this task, you create the Customer class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Complete the following steps:


1. Create the Customer class with the following characteristics:
Class Name: Customer
Project: BankPrj
Location: Source Packages
Package: com.mybank.domain
2. Declare three private instance variables: firstName, lastName, and
s a
account.
) h a
private String firstName;
c o m
private String lastName; ฺ
ail eฺ
private Account account;
g m id
@
1 nt
3. Declare a public constructor that takes two1parameters G
(f
u
and l) that
2
20 tude
populate the object instance variables.
t 9
in is S
public Customer(String f, String l) {
s a
( e th
firstName = f;
A N us
lastName = l;
T R t o
}
B EL nse
N
4. Declare e accessors for the object instance variables; the methods
O twolicpublic
O RE getFirstName
r a b le and getLastName return the appropriate instance

O M sfe variable.
A R String
public
- t r an getFirstName() {
G EN return
non firstName;
}
public String getLastName() {
return lastName;
}
5. Declare the getAccount method to retrieve the account instance
variable.
public Account getAccount() {
return account;
}
6. Declare the setAccount method to assign the account instance variable.
public void setAccount(Account acct) {
account = acct;
}

Lab 3-12 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating Customer Accounts (Level 3)

Task 2 – Copying the TestBanking Class


In this task, you copy the TestBanking.java file from the
d:\labs\student\resources\03_types\exercise2 directory into the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

com.mybank.test source package of the BankPrj project.

Task 3 – Compiling the TestBanking Class


In this task, you compile the TestBanking class. If there are compilation
errors, you should correct them by modifying the Customer class accordingly
and then compile the TestBanking class again.

s a
Task 4 – Running the TestBanking Program
) h a
c o m

il beฺ similar
In this task, you run the TestBanking program. The outputashould
to the following:
@ g m
u ide
Creating the customer Jane Smith.021
1 nt G
Creating her account with a 500.00 t 9 t de
2 balance.
u
Withdraw 150.00 s a in is S
N ( e th
us
Deposit 22.50
Withdraw 47.62 TR
A
t o
Customer [Smith,
B EL nJane] se has a balance of 324.88
NO le lic e
E
M OR ferab
A RO -trans
GEN non

Identifiers, Keywords, and Types Lab 3-13


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

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 3-14 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Lab 4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Expressions and Flow Control

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

a l eฺ
(Optional) Use nested loops to implement a string search ioperation

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 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

Exercise 1: Using Loops and Branching Statements


In this exercise, you will use a simple integer loop and branching statements to
play a fictitious game of foo bar baz.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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:

Code 4-1 (Partial) Output From the FooBarBaz Program


1
2
3 foo
s a
4
5 bar ) h a
c o m
6 foo ฺ
ail eฺ
7 baz
g m id
8 @ G u
9 foo
0 2 11 ent
10 bar
n t 9 2
S t ud
11
12 foo ( sai this
13 R AN use
14 baz
E LT se to
B en
15 foo bar
O
16E N le lic
M OR ferab
R O anda n
so son.
A tr
G EN non-This exercise contains the following sections:
● “Task 1 – Creating the FooBarBaz Class”
● “Task 2 – Compiling the FooBarBaz Class”
● “Task 3 – Running the FooBarBaz Program”

Lab 4-2 Java™ Programming Language


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

Preparation
There is no preparation required for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Tool references used in this exercise:


● Java Development: Java Application Projects: Opening Projects
● Java Development: Java Classes: Creating Java Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
s a
For this exercise, you work in the LoopProject project in the
) h a
d:\labs\student\exercises\04_stmts\exercise1 directory.
c o m

ail eฺ
g m id
Task 1 – Creating the FooBarBaz Class @ G u
0 2 11 ent
n t 9 2
S t ud
sai this
Complete the following steps:
(
1. Open the LoopProject
R AN project
u sein the
T e to
d:\labs\student\exercises\04_stmts\exercise1
L directory.
2. Create B
E ns class with the following characteristics:
N O l i ce
the FooBarBaz

O REClassa b le FooBarBaz
Name:

O er LoopProject
M sfProject:
A R -tran Location: Source Packages
GEN non
Package: default package
3. Declare the main method.
4. Use a for loop to iterate from 1–50 in the main method.
a. Print the current number.
b. Use three if statements to test if the current number is divisible by
three, five, or seven; if so, then print foo, bar, and baz as necessary.

Task 2 – Compiling the FooBarBaz Class


In this task, you compile the FooBarBaz program.

Expressions and Flow Control Lab 4-3


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

Task 3 – Running the FooBarBaz Program


In this task, you run the FooBarBaz program.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

The output should be similar to Code 4-1 on page L4-2.

Hints
These hints might help you to solve this exercise:
● Use the System.out.print method to print a string or value without
printing a new line character. You can use multiple print methods to print
a single line of text. You can use a single println method, with no
s a
arguments, to print a new line character.
) h a
● o m
The % operator calculates an integer remainder.
c

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

Lab 4-4 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Using Conditional Statements in the Account Class (Level 1)

Exercise 2: Using Conditional Statements in the Account


Class (Level 1)
In this exercise, you modify the withdraw method to return a boolean value to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

specify whether the operation was successful.

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
Customer
has-a 1
Account ) h a
c o m
-firstName : String -balance : double ฺ
ail eฺ
-lastName : String
g m id
«constructors»
@ G u
11 ent
-account : Account
+Account(initBalance:double)
«constructors»
2 0 2 d
n t 9
«methods»
S t u
sai +getBalance():double
+Customer(f:String, l:String)
«methods» ( t h is
+getFirstName():String A N use+withdraw(amt:double):boolean
+deposit(amt:double):boolean

+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.

Expressions and Flow Control Lab 4-5


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Using Conditional Statements in the Account Class (Level 1)

Tool Reference – Tool references used in this exercise:


● Java Development: Other Files: Deleting Files
● Java Development: Java Classes: Modifying Java Classes: Copying Java
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Classes: Executing Java Programs

For this exercise, you work in the BankPrj project in the


d:\labs\student\projects directory.

s a
Task 1 – Modifying the Account Class
) h a
c o m
In this task, you modify the Account class source file. This class a ฺ
il satisfyฺ the
must
m
UML diagram in Figure 4-1. In particular, the deposit andgwithdrawidmethods e
@ G u
1in this exercise.
must return a boolean value as described previously
2 1 n t
t 9 20 tude
a n is S
iTestBanking
Task 2 – Deleting the Current s
( e th Class
A N us
T R t
L the current o
B E
In this task, you delete
e n seof the
TestBanking class in the
O lic
com.mybank.test
N
package BankPrj project.

O RE rable
Task
O n fe
M3 – Copying
s the TestBanking Class
A R -tra
G EN non In this task, you copy the new version of the TestBanking.java file from the
d:\labs\student\resources\04_stmts\ directory into the
com.mybank.test package of the BankPrj project.

Task 4 – Compiling the TestBanking Class


In this task, you compile the TestBanking class.

Task 5 – Running the TestBanking Program


In this task, you run the TestBanking program. The output should be similar
to the following:

Lab 4-6 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Using Conditional Statements in the Account Class (Level 1)

Creating the customer Jane Smith.


Creating her account with a 500.00 balance.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Withdraw 400.00: false


Customer [Smith, Jane] has a balance of 324.88

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

Expressions and Flow Control Lab 4-7


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Using Conditional Statements in the Account Class (Level 2)

Exercise 2: Using Conditional Statements in the Account


Class (Level 2)
In this exercise, you will modify the withdraw method to return a Boolean value
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

to specify whether the operation was successful.

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”
s a
● “Task 5 – Running the TestBanking Program”
) h a
c o m

ail eฺ
Preparation m
@ g u id
11 ent G
0
There is no preparation required for this exercise. 2
n t 9 2
S t ud
saiin thisthexercise:
Tool Reference – Tool references (used is
R se Files
ANFiles: uDeleting

E LT se to
Java Development: Other
B eJava
Java Development:

O n Classes: Modifying Java Classes: Copying Java
l i c
R EN ble
Classes

M ● ra
O JavafeDevelopment: Java Classes: Modifying Java Classes: Compiling Java
O s
R -tranClasses
A
G EN non Java Development: Java Classes: Modifying Java Classes: Executing Java

Programs

For this exercise, you work in the BankPrj project in the


d:\labs\student\projects directory.

Lab 4-8 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Using Conditional Statements in the Account Class (Level 2)

Task 1 – Modifying the Account Class


In this task, you complete the following steps to modify the Account class:
1. Modify the deposit method. Because an account has no upper limit, this
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

method must always return true to indicate it always succeeds.


2. Modify the withdraw method. Because an account cannot drop below
zero, the method must check that the amount of the withdrawal is less than
the current balance. If this is the case, then the withdraw operation is
successful and must return true; otherwise the operation fails and the
method must return false.

Task 2 – Deleting the Current TestBanking Class a


h a s
m )
In this task, you delete the current TestBanking class in the
ฺ c o
com.mybank.test package of the BankPrj project.
m ail eฺ
@ g u id
1 nt
1Class G
Task 3 – Copying the TestBanking 2 0 2 de
t 9 t u
s a in is S
N e h TestBanking.java file from the
In this task, you copy the new (version of tthe
R A
d:\labs\student\resources\04_stmts\
T t o us directory into the
com.mybank.test
B EL package
n s e of the BankPrj project.
N O lice
Task R E ble
4 – Compiling the TestBanking Class
M O f e ra
s
RO -traInnthis
A
GEN non task, you compile the TestBanking class.

Task 5 – Running the TestBanking Program


In this task, you run the TestBanking program. The output should be similar
to the following:
Creating the customer Jane Smith.
Creating her account with a 500.00 balance.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Withdraw 400.00: false
Customer [Smith, Jane] has a balance of 324.88

Expressions and Flow Control Lab 4-9


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Using Conditional Statements in the Account Class (Level 3)

Exercise 2: Using Conditional Statements in the Account


Class (Level 3)
In this exercise, you will modify the withdraw method to return a boolean
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

value to specify whether the operation was successful.

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”
s a
● “Task 5 – Running the TestBanking Program”
) h a
c o m

ail eฺ
Preparation m
@ g u id
11 ent G
0
There is no preparation required for this exercise. 2
n t 9 2
S t ud
saiin thisthexercise:
Tool Reference – Tool references (used is
R se Files
ANFiles: uDeleting

E LT se to
Java Development: Other
B eJava
Java Development:

O n Classes: Modifying Java Classes: Copying Java
l i c
R EN ble
Classes

M ● ra
O JavafeDevelopment: Java Classes: Modifying Java Classes: Compiling Java
O s
R -tranClasses
A
G EN non Java Development: Java Classes: Modifying Java Classes: Executing Java

Programs

For this exercise, you work in the BankPrj project in the


d:\labs\student\projects directory.

Lab 4-10 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Using Conditional Statements in the Account Class (Level 3)

Task 1 – Modifying the Account Class


In this task, you complete the following steps to modify the Account class:
1. Modify the deposit method. Because an account has no upper limit, this
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

method must always return true to indicate it always succeeds.


public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
2. Modify the withdraw method. Because an account cannot drop below
zero, the method must check that the amount of the withdrawal is less than
the current balance. If this is the case, then the withdraw operation is
successful and must return true; otherwise the operation fails and the
s a
method must return false.
) h a
public boolean withdraw(double amt) {
c o m
boolean result = false; // assume operation failure ฺ
ail eฺ
if ( amt <= balance ) { g m id
@ G u
balance = balance - amt;
0 2 11 ent
result = true; // operation succeeds
n t 9 2
S t ud
sai this
}
return result; (
}
R AN use
E LT se to
Task 2 E
–N O B licethe
Deleting
n
Current TestBanking Class
l e
M OR ferab
R s task, you delete the current TestBanking class in the
O raInnthis
A t com.mybank.test package of the BankPrj project.
GEN non-
Task 3 – Copying the TestBanking Class
In this task, you copy the new version of the TestBanking.java file from the
d:\labs\student\resources\04_stmts\ directory into the
com.mybank.test package of the BankPrj project.

Task 4 – Compiling the TestBanking Class


In this task, you compile the TestBanking class.

Expressions and Flow Control Lab 4-11


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Using Conditional Statements in the Account Class (Level 3)

Task 5 – Running the TestBanking Program


In this task, you run the TestBanking program. The output should be similar
to the following:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Creating the customer Jane Smith.


Creating her account with a 500.00 balance.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Withdraw 400.00: false
Customer [Smith, Jane] has a balance of 324.88

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

Lab 4-12 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 3: Using Nested Loops (Advanced)

Exercise 3: Using Nested Loops (Advanced)


In this exercise, you use nested loops to implement a string search operation.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Writing the isSubString Method”
● “Task 2 – Compiling the TestIsSubString Class”
● “Task 3 – Running the TestIsSubString Program”

Note – There are several advanced exercises in this course. These exercises are
optional and should only be attempted if you completed all of the previous
exercises for this module. s a
) h a
c o m

ail eฺ
Preparation g m id
@ G u
0 2 11 ent
n t 2
There is no preparation required for this exercise.
9 S t ud
( s ai this
Tool Reference – Tool references
N uused ein this exercise:
A s
L TR Java
Java Development:

e o
tApplication Projects: Opening Projects
E s
B en Java Classes: Modifying Java Classes: Compiling Java
Java
● O
N le lic
Development:
E Classes
M OR fJava
e
b
raDevelopment:
O n s ● Java Classes: Modifying Java Classes: Executing Java

N AR n-tra Programs
GE no For this exercise, you work in the AdvancedLoopProject project in the
d:\labs\student\exercises\04_stmts\exercise3 directory.

Task 1 – Writing the isSubString Method


In this task, you open the AdvancedLoopProject project in the
d:\labs\student\exercises\04_stmts\exercise3 directory, open
the TestIsSubString class, and write the isSubString method. The
method searches for a specific string within another string; the method must
return true if the former exists in the latter string. For example:
isSubString("cat", "The cat in the hat.") is true, but
isSubString("bat", "The cat in the hat.") is false.

Expressions and Flow Control Lab 4-13


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 3: Using Nested Loops (Advanced)

Also, verify that the following boundary conditions are met:


● isSubString("The", "The cat in the hat.") is true
● isSubString("hat.", "The cat in the hat.") is true
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

There is an easy way to do this by using the indexOf method of the String
class. You can determine if a String s is a substring of some String x by
evaluating the expression x.indexOf(s) != -1. However, the purpose of this
exercise is to practice using loops, so you should solve the problem by using only
the charAt method and nested loops.

Task 2 – Compiling the TestIsSubString Class

s a
In this task, you compile the TestIsSubString class.
) h a
c o m
Task 3 – Running the TestIsSubString Program ฺ
ail eฺ
g m id
@ G u
0 2
In this task, you run the TestIsSubString program.11 Theenoutput
t of the
9
program should be similar to the example tshown
n S t ud1 – Writing the
2 in ‘‘Task
isSubString Method’’ on page L4-13.
( 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

Lab 4-14 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 3: Using Nested Loops (Advanced)

Hints
These hints might help you to solve this exercise.
● Use the charAt(int index) method in the String class to retrieve a
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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

Expressions and Flow Control Lab 4-15


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

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-16 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Lab 5
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Arrays

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 1)

Exercise 1 – Using Primitive Arrays (Level 1)


In this exercise, you declare, create, and manipulate one-dimensional arrays of
primitive types.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Creating the TestArrays Class”
● “Task 2 – Compiling the TestArrays Class”
● “Task 3 – Running the TestArrays Program”

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: g m id
@
1 nProjectsG u
Java Development: Java Application Projects: 2 1Opening
e t

9 0 ud
2 Java Classes

i n t
Java Development: Java Classes: Creating S t
( saModifying
t h isJava Classes: Compiling Java
AN use
● Java Development: Java Classes:
Classes R to
LTJavasClasses:
● E
B en
Java Development: e Modifying Java Classes: Executing Java
O
N le lic
Programs
E
M OR ferab you work in the ArrayProject project in the
ans
For this exercise,
A RO -d:\labs\student\exercises\05_arrays\exercise1
t r directory.
E N n
G no
Task 1 – Creating the TestArrays Class
Complete the following steps:
1. Open the ArrayProject project in the
d:\labs\student\exercises\05_arrays\exercise1 directory.

Lab 5-2 Java™ Programming Language


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 1)

2. Create the TestArrays class int he ArrrayProject project with the


following characteristics:
3. Add a main method. In the main method, declare two variables called
array1 and array2. They should be of type int[] (array of int).
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

4. Using the curly-brace notation, {}, initialize array1 to the first eight prime
numbers.
5. Display the contents of array1.
6. Assign the array2 variable equal to the array1. Modify the even indexed
element in array2 to be equal to the index value (for example,
array2[0] = 0; and array2[2] = 2; and so on). Print out array1.

Task 2 – Compiling the TestArrays Class a


h a s
m )
In this task, you compile the TestArrays class.
ฺ c o
m ail eฺ
@ g u id
Task 3 – Running the TestArrays Program 11 ent G
0 2
n t 9 2
S t ud
Run the TestArrays program. a
( sThei output
t h isshould be similar to the following:
array1 is <2, 3, 5, AN 7, 11,u e 17, 19>
s13,
array1 is <0,L3, R
T 2, e7,to4, 13, 6, 19>
E
BWhat hasn s
O
N le lic
Discussion – e happened to array1?
E
!
M OR ferab
RO -trans
?

A
GEN non

Arrays Lab 5-3


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)

Exercise 1 – Using Primitive Arrays (Level 2)


In this exercise, you declare, create, and manipulate one-dimensional arrays of
primitive types.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Creating the TestArrays Class”
● “Task 2 – Compiling the TestArrays Class”
● “Task 3 – Running the TestArrays Program”

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
2 11 Opening
Java Development: Java Application Projects:

0 e n t Projects
n
Java Development: Java Classes:t 9 2 t udClasses
CreatingSJava
sai Modifying

Java Development: Java (Classes: t h is Java Classes: Compiling Java


AN use

Classes R
LT sJava to
E
B en
Java Development:
● e Classes: Modifying Java Classes: Executing Java
O
N le lic
Programs
E
R rab
M OFor fe exercise, you work in the ArrayProject project in the
O n sthis

N AR n-trad:\labs\student\exercises\05_arrays\exercise1 directory.
G E no
Task 1 – Creating the TestArrays Class
Complete the following steps:
1. Open the ArrayProject project in the
d:\labs\student\exercises\05_arrays\exercise1 directory.

Lab 5-4 Java™ Programming Language


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)

2. Create the TestArrays class with the following characteristics:


Class Name: TestArrays
Project: ArrayProject
Location: Source Packages
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Package: default package


3. Add a main method. In the main method, declare two variables called
array1 and array2. They should be of type int[] (array of int).
4. Using the curly-brace notation, {}, initialize array1 to the first eight prime
numbers: 2, 3, 5, 7, 11, 13, 17, and 19.
5. Display the contents of array1. You might want to use the printArray
method (see ‘‘Hint’’ on page L5-6) to display these integer arrays.
s a
6. Assign the array2 variable equal to the array1. Modify the even indexed
) h a
element in array2 to be equal to the index value (for example,
c o m

ail eฺ
array2[0] = 0; and array2[2] = 2; and so on). Print out array1.
g m id
@
1 nt G u
Task 2 – Compiling the TestArrays 2 1Class
t 9 2 0
t u de
a in iclass.
s S
s h
N ( use t
In this task, you compile the TestArrays
A
L TR e to
Task 3 – Running
O BE ethe n s TestArrays Program
E N le lic
M OInRthisfetask,
r abyou run the TestArrays program. The output should be similar to
R O rathensfollowing:
A t
GEN non- array1 is <2, 3, 5, 7, 11, 13, 17, 19>
array1 is <0, 3, 2, 7, 4, 13, 6, 19>

Discussion – What has happened to array1?


!
?

Arrays Lab 5-5


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)

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ฺ

public static void printArray(int[] array) {


System.out.print(’<’);
for ( int i = 0; i < array.length; i++ ) {
// print an element
System.out.print(array[i]);
// print a comma delimiter if not the last element
if ( (i + 1) < array.length ) {
System.out.print(", ");
}
}
s a
System.out.print(’>’);
) h a
}
c o m

ail eฺ
g m id to
Note – You can also use the java.util.Arrays.toString@
1 nt G u
method
2 1example:
generate a string representation of an array.0
t 9 2 For
t u de
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

Lab 5-6 Java™ Programming Language


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 3)

Exercise 1 – Using Primitive Arrays (Level 3)


In this exercise, you declare, create, and manipulate one-dimensional arrays of
primitive types.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Creating the TestArrays Class”
● “Task 2 – Compiling the TestArrays Class”
● “Task 3 – Running the TestArrays Program”

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
● 2 11Opening
Java Development: Java Application Projects:
0 e n t Projects
n
Java Development: Java Classes: t 9 2 Java
Creating S t udClasses
sai Modifying

( t h is Java Classes: Compiling Java


AN use
●Java Development: Java Classes:
Classes R
LT sJava to
● E e
B en Classes: Modifying Java Classes: Executing Java
Java Development:
O
N le lic
Programs
E
R rab
M OFor fe exercise, you work in the
O n sthis

N AR n-trad:\labs\student\exercises\05_arrays\exercise1 directory.
GE no
Task 1 – Creating the TestArrays Class
Complete the following steps:
1. Open the ArrayProject project in the
d:\labs\student\exercises\05_arrays\exercise1 directory.

Arrays Lab 5-7


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 3)

2. Create the TestArrays class with the following characteristics:


Class Name: TestArrays
Project: ArrayProject
Location: Source Packages
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Package: default package


3. Add a main method. In the main() method, declare two variables called
array1 and array2. They should be of type int[] (array of int).
public class TestArrays {
public static void main(String[] args) {
int[] array1;
int[] array2;
// insert code here
s a
}
}
) h a
c o m
4. ฺ
ail eฺ
Using the curly-brace notation, {}, initialize array1 to the first eight prime
m
g uid
numbers: 2, 3, 5, 7, 11, 13, 17, and 19.
int[] array1 = { 2, 3, 5, 7, 11, 13, 17, 19 }; 11@ t G
0 2 e n
int[] array2;
n t 9 2
S t ud
( s i to might
5. Display the contents of array1.aYou
t h iswant to use the printArray

A N use
method (see ‘‘Hint’’ on page L5-6) display these integer arrays.
System.out.print("array1 isT");
L R to
printArray(array1); BE
e n se
NO le lic
System.out.println();
E
6.ORAssign athebarray2 variable equal to the array1. Modify the even indexed
M e r
R sf in array2 to be equal to the index value (for example,
O ranelement
N A n-t array2[0] = 0; and array2[2] = 2; and so on).
G E array2
no= array1;
// modify array2
array2[0] = 0;
array2[2] = 2;
array2[4] = 4;
array2[6] = 6;
// print array 1
System.out.print("array1 is ");
printArray(array1);
System.out.println();

Lab 5-8 Java™ Programming Language


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 3)

7. Print out array1 using the print method provided below.


public static void printArray(int[] array) {
System.out.print(’<’);
for ( int i = 0; i < array.length; i++ ) {
// print an element
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

System.out.print(array[i]);
// print a comma delimiter if not the last element
if ( (i + 1) < array.length ) {
System.out.print(", ");
}
}
System.out.print(’>’);
}

s a
) h a
Task 2 – Compiling the TestArrays Class c o m

ail eฺ
In this task, you compile the TestArrays class. @g
m id
G u
0 2 11 ent
n t 9 2
S t ud
Task 3 – Running the TestArrays
( sai this Program
R AN useprogram. The output should be similar to
E L se to
In this task, you runTthe TestArrays
the following:
O B en
N is l<2, c 5, 7, 11, 13, 17, 19>
li3,
E
array1 e
R raisb <0, 3, 2, 7, 4, 13, 6, 19>
M Oarray1fe
O n s
N AR n-tra
GE no

Arrays Lab 5-9


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2 – Using Arrays to Represent One-to-Many Associations (Level 1)

Exercise 2 – Using Arrays to Represent One-to-Many


Associations (Level 1)
In this exercise, you use arrays to implement the association between a bank and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

its multiple customers.

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

This exercise contains the following sections:


● “Task 1 – Creating the Bank 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”

Lab 5-10 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2 – Using Arrays to Represent One-to-Many Associations (Level 1)

Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Tool references used in this exercise:


● Java Development: Java Classes: Creating Java Classes
● Java Development: Other Files: Deleting Files
● Java Development: Java Classes: Modifying Java Classes: Copying Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
Java Development: Java Classes: Modifying Java Classes: Executing Java s a

Programs ) h a
c o m

ail eฺdirectory.
For this exercise, you work in the BankPrj project in the projects
g m id
@ G u
0 2 11 ent
Task 1 – Creating the Bank Class
n t 9 2
S t ud
( sai this
In this task, you create the N
A s
Bank class
u ethat must satisfy the UML diagram in
TR eThetoclass has the following characteristics:
Figure 5-1 on page L5-10.
L
BE Bank
Class Name:
O e n s
E N lBankPrj
e lic
OR fLocation:
rab Source Packages
Project:
M e
A RO -trans Package: com.mybank.domain
GEN non
Task 2 – Deleting the Current TestBanking Class
In this task, you delete the current TestBanking class in the
com.mybank.test source package of the BankPrj project.

Task 3 – Copying the TestBanking Class


In this task, you copy the TestBanking.java file from the
d:\labs\student\resources\05_arrays directory to the
com.mybank.test source package of the BankPrj project.

Arrays Lab 5-11


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2 – Using Arrays to Represent One-to-Many Associations (Level 1)

Task 4 – Compiling the TestBanking Class


In this task, you compile the TestBanking class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 5 – Running the TestBanking Program


In this task, you run the TestBanking program. The output should be similar
to the following:
Customer [1] is Simms, Jane
Customer [2] is Bryant, Owen
Customer [3] is Soley, Tim
Customer [4] is Soley, Maria
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

Lab 5-12 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2 – Using Arrays to Represent One-to-Many Associations (Level 2)

Exercise 2 – Using Arrays to Represent One-to-Many


Associations (Level 2)
In this exercise, you use arrays to implement the association between a bank and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

its multiple customers.

This exercise contains the following sections:


● “Task 1 – Creating the Bank Class”
● “Task 2 – Deleting the Current TestBanking Class”
● “Task 3 – Copying the TestBanking Class”
● “Task 4 – Compiling the TestBanking Class”
s a
● “Task 5 – Running the TestBanking Program”
) h a
c o m

ail eฺ
Preparation m
@ g u id
1 nt G
There is no preparation for this exercise. 021
t 9 2 t u de
s a in is S
Tool Reference – Tool references
N ( usedeinththis exercise:
T
Java Development:R t o us Creating Java Classes
AJava Classes:
EL nsJava

B e Classes: Modifying Java Classes: Copying Java


NO le lic

e
Java Development:
E Classes

M OR fJava
e●
b
raDevelopment: Other Files: Deleting Files
O s
R -tran Java Development: Java Classes: Modifying Java Classes: Compiling Java
A ●

GEN non Classes


● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs

For this exercise, you work in the BankPrj project in the


d:\labs\student\projects directory.

Arrays Lab 5-13


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2 – Using Arrays to Represent One-to-Many Associations (Level 2)

Task 1 – Creating the Bank Class


Complete the following steps:
1. Create the Bank class with the following characteristics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Class Name: Bank


Project: BankPrj
Location: Source Packages
Package: com.mybank.domain
2. Add two instance variables to the Bank class: customers (an array of
Customer objects) and numberOfCustomers (an integer that keeps track
of the next customers array index).
s a
3. Add a public constructor that initializes the customers array with some
) h a
appropriate maximum size (at least bigger than five).
c o m
4. Add the addCustomer method. This method must construct

aial new eฺ
Customer object from the parameters (first name and g m d place
iand
@ G u
last name)
it on the customers array. It must also increment
0 2 11 theent
numberOfCustomers instance variable.2
n t 9 S t ud
5. Add the getNumOfCustomers s i
aaccessor is which returns the
method,
( t h
R AN use
numberOfCustomers instance variable.
LT smethod.
6. Add the getCustomer
E e to This method returns the customer
associated B n index parameter.
O l i c e
with the given

R EN ble
M
Task 2
O– Deleting
f e ra the Current TestBanking Class
A RO -trans
G EN non In this task, you delete the current TestBanking class in the
com.mybank.test source package of the BankPrj project.

Task 3 – Copying the TestBanking Class


In this task, you copy the TestBanking.java file from the
d:\labs\students\resources\05_arrays directory to the
com.mybank.test source package of the BankPrj project.

Task 4 – Compiling the TestBanking Class


In this task, you compile the TestBanking class.

Lab 5-14 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2 – Using Arrays to Represent One-to-Many Associations (Level 2)

Task 5 – Running the TestBanking Program


In this task, you run the TestBanking program. The output should be similar
to the following:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Customer [1] is Simms, Jane


Customer [2] is Bryant, Owen
Customer [3] is Soley, Tim
Customer [4] is Soley, Maria

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

Arrays Lab 5-15


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2 – Using Arrays to Represent One-to-Many Associations (Level 3)

Exercise 2 – Using Arrays to Represent One-to-Many


Associations (Level 3)
In this exercise, you use arrays to implement the association between a bank and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

its multiple customers.

This exercise contains the following sections:


● “Task 1 – Creating the Bank Class”
● “Task 2 – Deleting the Current TestBanking Class”
● “Task 3 – Copying the TestBanking Class”
● “Task 4 – Compiling the TestBanking Class”
s a
● “Task 5 – Running the TestBanking Program”
) h a
c o m

ail eฺ
Preparation m
@ g u id
11 ent G
There is no preparation for this exercise. 0 2
n t 9 2
S t ud
sai in this
Tool Reference – Tool References(used t h is
exercise:
N use
AClasses:
Java Development:

L R
T e to Creating Java Classes
Java
BE eJava
Java Development:

O n sClasses: Modifying Java Classes: Copying Java
E N le lic
Classes

M ORJavafeDevelopment:
● rab Other Files: Deleting Files
O s
R -tranJava Development: Java Classes: Modifying Java Classes: Compiling Java
A ●

G EN non Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs

For this exercise, you work in the BankPrj project in the


d:\labs\student\projects directory.

Lab 5-16 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2 – Using Arrays to Represent One-to-Many Associations (Level 3)

Task 1 – Creating the Bank Class


Complete the following steps:
1. Create the Bank class with the following characteristics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Class Name: Bank


Project: BankPrj
Location: Source Packages
Package: com.mybank.domain
package com.mybank.domain;
public class Bank {
// insert code here
} s a
) h a
2. Add two instance variables to the Bank class: customers (an array of
c o m

ail eฺ
Customer objects) and numberOfCustomers (an integer that keeps track
of the next customers array index).
g m id
@ G u
public class Bank {
private Customer[] customers; 0 2 11 ent
private int numberOfCustomers;
n t 9 2
S t ud
// insert methods here
( sai this
}
R AN use
T e tothat initializes the customers array with some
3. Add a publicLconstructor
E
B maximum
n s size (at least bigger than five).
appropriate
O
N le lic e
public Bank() {E
customers
M O=Rnewe r a b
Customer[10];
O ransf = 0;
numberOfCustomers
R
}A t
GEN non- 4. Add the addCustomer method. This method must construct a new
Customer object from the parameters (first name, last name) and place it
on the customers array. It must also increment the numberOfCustomers
instance variable.
public void addCustomer(String f, String l) {
int i = numberOfCustomers++;
customers[i] = new Customer(f, l);
}
5. Add the getNumOfCustomers accessor method, which returns the
numberOfCustomers instance variable.
public int getNumOfCustomers() {
return numberOfCustomers;
}

Arrays Lab 5-17


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

6. Add the getCustomer method. This method returns the customer


associated with the given index parameter.
public Customer getCustomer(int customer_index) {
return customers[customer_index];
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 2 – Deleting the Current TestBanking Class


In this task, you delete the current TestBanking class in the
com.mybank.test source package of the BankPrj project.

Task 3 – Copying the TestBanking Class a


h a s
m )
In this task, you copy the TestBanking.java file from the
ฺ c o
d:\labs\student\resources\05_arrays directory to the
m ail eฺ
g
com.mybank.test source package of the BankPrj project.
@ u id
11 ent G
2 0 2 d
Task 4 – Compiling the TestBanking n t 9 S t uClass
( sai this
R
In this task, you compile u se
N TestBanking
Athe class.
T t o
B EL nse
O licethe TestBanking Program
Task 5E–NRunning
O R rable
O n fetask, you run the TestBanking program. The output should be similar
M In sthis
N AR n-trato the following:
GE no Customer [1] is Simms, Jane
Customer [2] is Bryant, Owen
Customer [3] is Soley, Tim
Customer [4] is Soley, Maria
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

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

Arrays Lab 5-19


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary
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

Lab 5-20 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Lab 6
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Class Design

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)

Exercise 1: Creating Bank Account Subclasses (Level 1)


In this exercise, you create two subclasses of the Account class in the Banking
project: SavingsAccount and CheckingAccount. These account types have
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

the following business rules:


● A savings account gains interest. The bank permits customers to store
money in a savings account and, on a monthly basis, the savings account
will accumulate based on the following formula: balance = balance +
(interestRate * balance).
● A checking account enables the customer to make any number of deposits
and withdrawals. To protect their customers, the bank will permit a fixed
amount of overdraft protection. This protection enables the customer’s
balance to drop below zero, but not below the amount of overdraft
s a
protection. The account’s overdraft amount is decremented as it is used.
) h a
c o m

Figure 6-1 shows the UML class diagram for a design that satisfiesilthe business
rules described above. g ma ideฺ
1 1 @ t Gu
9 2 02 uden
com.mybank.domain
a i nt is St
N (s e th
us
Account
RA
#balanceL:Tdouble to
B E nse
N O l i ce
«constructors»

O RE ra«methods»
ble
#Account(initBalance:double)

O M sfe +getBalance():double
A R -tran
E N on +deposit(amt:double):boolean

G n +withdraw(amt:double):boolean

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

Figure 6-1 Two Subclasses of the Account Class

Lab 6-2 Java™ Programming Language


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)

This exercise contains the following sections:


● “Task 1 – Modifying the Account Class”
● “Task 2 – Creating the SavingsAccount Class”
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

● “Task 3 – Creating the CheckingAccount Class”


● “Task 4 – Deleting the Current TestBanking Class”
● “Task 5 – Copying the TestBanking Class”
● “Task 6 – Compiling the TestBanking Class”
● “Task 7 – Running the TestBanking Program”

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
@
1 Classes G u
Java Development: Java Classes: Creating

2 1Java e n t
9 0
2 Filestud
n t
Java Development: Other Files: Deleting

i S
s a h i s

A N ( useModifying
Java Development: Java Classes: t Java Classes: Copying Java

TR e to
Classes
L

O BE ensJava Classes: Modifying Java Classes: Compiling Java
Java Development:

E N le lic
Classes

M OR fJava
e

r b
aDevelopment: Java Classes: Modifying Java Classes: Executing Java

R O rans Programs
A t
GEN non- For this exercise, you work in the BankPrj project in the
d:\labs\student\projects directory.

Task 1 – Modifying the Account Class


In this task, you modify the Account class in the com.mybank.domain source
package of the BankPrj project. This class must satisfy the UML diagram in
Figure 6-1; in particular, the balance instance variable and Account class
constructor are now protected (indicated by the # character instead of the -
character).

Class Design Lab 6-3


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)

Task 2 – Creating the SavingsAccount Class


In this task, you create the SavingsAccount class source file in the
com.mybank.domain source package of the BankPrj project with the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

following characteristics:
Class Name: SavingsAccount
Project: BankPrj
Location: Source Packages
Package: com.mybank.domain

Add code so that SavingsAccount extends the Account class.

s a
This class must satisfy the UML diagram in Figure 6-1 on page L6-2 and the
) h a
c o m
business rules defined in the introduction to ‘‘Exercise 1: Creating Bank Account
Subclasses (Level 1)’’ on page L6-2. ฺ
ail eฺ
g m id
@ G u
Task 3 – Creating the CheckingAccount 0 2 11 Class
e n t
n t 9 2
S t ud
( sai thiclass
In this task, you create the CheckingAccount s source file in the
com.mybank.domain source
R A N sethe BankPrj project with the
package of
u
LT se to
following characteristics:
E
O B CheckingAccount
e n
Class Name:
l i c
R EN BankPrj
Project: b le
O
M Location:f a
er Source Packages
O
R -tran s
A
G EN non Package: com.mybank.domain

Add code so that CheckingAccount extends the Account class.

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.

Task 4 – Deleting the Current TestBanking Class


In this task, you delete the current TestBanking class in the
com.mybank.test source package of the BankPrj project.

Lab 6-4 Java™ Programming Language


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)

Task 5 – Copying the TestBanking Class


In this task, you copy the TestBanking.java file from the
d:\labs\student\resources\06_class1 directory into the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

com.mybank.test source package of the BankPrj project. The new


TestBanking class sets CheckingAccount and SavingsAccount
objects to different customers.

Task 6 – Compiling the TestBanking Class


In this task, you compile the TestBanking class.

s a
Task 7 – Running the TestBanking Program
) h a
c o m

il beฺ similar
In this task, you run the TestBanking program. The outputashould
to the following:
@ g m
u ide
2 1 1 nt G
Creating the customer Jane Smith.
Creating her Savings Account with a 500.00 tbalance9 20 tand u de3% interest.
Creating the customer Owen Bryant. s a in is S
Creating his Checking Account withNa 500.00
h
( e tbalance
A u s and no overdraft
protection.
Creating the customer TimESoley. LTR se to
O B ewith n a 500.00 balance and 500.00 in
Creating his Checking Account
l i c
R EN ble
overdraft protection.
M
Creating theOcustomer
f e raMaria Soley.
RO -traher
Maria shares
A nsChecking Account with her husband Tim.
N on
ERetrieving
G n the customer Jane Smith with her savings account.
Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Withdraw 400.00: false
Customer [Simms, Jane] has a balance of 324.88

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
Withdraw 400.00: false
Customer [Bryant, Owen] has a balance of 324.88

Class Design Lab 6-5


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)

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
Customer [Soley, Maria] has a balance of 150.0

Jane’s savings account and Owen’s checking account behave fundamentally as a


s a
basic bank account. But Tim and Maria’s joint checking account has 500.00
) h a
c o m
worth of overdraft protection. Tim’s transactions dip into that protection and

ail eฺ
therefore his ending balance is 0.00. His account’s overdraft protection level is
g m id
424.88. Finally, Maria deposits 150.00 into this joint account; raising the balance
@ G u
0 2 11 ent
from 0.00 to 150.00. Then she tries to withdraw 750.00, which fails because
neither the balance nor the overdraft protection can cover that requested amount.
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

Lab 6-6 Java™ Programming Language


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 2)

Exercise 1: Creating Bank Account Subclasses (Level 2)


In this exercise, you create two subclasses of the Account class in the Banking
project: SavingsAccount and CheckingAccount.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This section contains the following sections:


● “Task 1 – Modifying the Account Class”
● “Task 2 – Creating the SavingsAccount Class”
● “Task 3 – Creating the CheckingAccount Class”
● “Task 4 – Deleting the Current TestBanking Class”
● “Task 5 – Copying the TestBanking Class”
s a
● “Task 6 – Compiling the TestBanking Class”
) h a
● “Task 7 – Running the TestBanking Program”
c o m

ail eฺ
g m id
Preparation @ G u
0 2 11 ent
n t 9 2
S t ud
sai this
There is no preparation for this exercise.
(
Tool Reference – Tool R AN uused sein this exercise:
E LT se to
references
B en Java Classes: Creating Java Classes
Java Development:
O lic Other Files: Deleting Files

E N Development:
l e
OR fJava b
Java

M e raDevelopment:
R O rans Classes
● Java Classes: Modifying Java Classes: Copying Java
A t
GEN 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


d:\labs\student\projects directory.

Task 1 – Modifying the Account Class


In this task, you modify the Account class in the com.mybank.domain source
package of the BankPrj project.

Class Design Lab 6-7


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 2)

Complete the following steps:


1. Change the balance instance variable from private to protected.
2. Change the Account constructor from public to protected.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 2 – Creating the SavingsAccount Class


In this task, you create the SavingsAccount class source file in the
com.mybank.domain source package of the BankPrj project.

Complete the following steps:


1. Create the SavingsAccount class source file in the
com.mybank.domain source package of the BankPrj project with the
s a
following characteristics:
) h a
c o m
Class Name: SavingsAccount ฺ
ail eฺ
Project: BankPrj g m id
@ G u
Location: Source Packages
0 2 11 ent
Package: com.mybank.domain
n t 9 2
S t ud
( sai extends
Add code so that SavingsAccount t h is the Account class.
AN u e
svariable
L R
T e to
2. Add the interestRate instance to the SavingsAccount class.
3. Add a public
O BEconstructor
e n s that takes two arguments: initBalance and
N le licPass the initBalance parameter to the super
interestRate.
E
M ORconstructor.
e r a b Save the interestRate parameter to the instance variable.
R O ransf
A t
G EN non-

Lab 6-8 Java™ Programming Language


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 2)

Task 3 – Creating the CheckingAccount Class


In this task, you create the CheckingAccount class source file in the
com.mybank.domain source package of the BankPrj project.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Complete the following steps:


1. Create the CheckingAccount class source file in the
com.mybank.domain source package of the BankPrj project with the
following characteristics:
Class Name: CheckingAccount
Project: BankPrj
Location: Source Packages
s a
Package: com.mybank.domain
) h a
c o m

Add code so that CheckingAccount extends the Account class.
ail eฺ
2. Add the overdraftAmount instance variable to the g m id
CheckingAccount
@ G u
class.
0 2 11 ent
t92 arguments:
3. Add a public constructor that takes two d initBalance and
tuparameter
a n
overdraftAmount. Pass the iinitBalance
i s S to the super
s h
( e t parameter to the instance
constructor. Save the overdraftAmount
A N us
variable.
T R t o
B EL public
4. Add a second
n seconstructor that takes only one argument:
N
initBalance. e
O lic Call the first constructor with the initBalance parameter
E e default value 0.0 for the overdraftAmount parameter.
R andrauseblthe
O e
M 5. sfOverride
R O a n the withdraw method to use the overdraftAmount variable.
A tr
EN non-
Here is the pseudo-code for the withdraw method:
G 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

Class Design Lab 6-9


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 2)

Task 4 – Deleting the Current TestBanking Class


In this task, you delete the current TestBanking class in the
com.mybank.test source package of the BankPrj project.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 5 – Copying the TestBanking Class


In this task, you copy the TestBanking.java file from the
d:\labs\student\resources\06_class1 directory into the
com.mybank.test source package of the BankPrj project. The new
TestBanking class sets CheckingAccount and SavingsAccount
objects to different customers.
s a
) h a
Task 6 – Compiling the TestBanking Class o m
ฺ c
m ail eฺ
In this task, you compile the TestBanking class.
@ g u id
11 ent G
0 2
Task 7 – Running the TestBanking n t 9 2
S t ud
Program
( sai this
e
AN usprogram.
L T R t o
In this task, you run the TestBanking The output should be similar
to the following: E
B e n se
Creating the customerNJane O Smith.lic
E l e
OR feAccount
Creating her Savings
Creating the M rab Bryant.
with a 500.00 balance and 3% interest.

ns Account with a 500.00 balance and no overdraft


customer Owen
O Checking
Rhis r a
A
Creating
N on- t
E
protection.
Creating n
G the customer Tim Soley.
Creating his Checking Account with a 500.00 balance and 500.00 in
overdraft protection.
Creating the customer Maria Soley.
Maria shares her Checking Account with her husband Tim.

Retrieving the customer Jane Smith with her savings account.


Withdraw 150.00: true
Deposit 22.50: true
Withdraw 47.62: true
Withdraw 400.00: false
Customer [Simms, Jane] has a balance of 324.88

Lab 6-10 Java™ Programming Language


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 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ฺ

Withdraw 400.00: false


Customer [Bryant, Owen] has a balance of 324.88

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

Class Design Lab 6-11


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 3)

Exercise 1: Creating Bank Account Subclasses (Level 3)


In this exercise, you will create two subclasses of the Account class in the
Banking project: SavingsAccount and CheckingAccount.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Modifying the Account Class”
● “Task 2 – Creating the SavingsAccount Class”
● “Task 3 – Creating the CheckingAccount Class”
● “Task 4 – Deleting the Current TestBanking Class”
● “Task 5 – Copying the TestBanking Class”
s a
● “Task 6 – Compiling the TestBanking Class”
) h a
● “Task 7 – Running the TestBanking Program”
c o m

ail eฺ
g m id
Preparation @ G u
0 2 11 ent
n t 9 2
S t ud
sai this
There is no preparation for this exercise.
(
Tool Reference – ToolT R AN usedusinethis exercise:
E L se to
references
B eJava
Java Development:
O n Classes: Creating Java Classes

l i c
R ENDevelopment:
Java

b le Other Files: Deleting Files
O
M Java f r a
eDevelopment:
R O a n

s Java Classes: Modifying Java Classes: Copying Java
A tr Classes
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


d:\labs\student\projects directory.

Task 1 – Modifying the Account Class


In this task, you modify the Account class in the com.mybank.domain source
package of the BankPrj project.

Lab 6-12 Java™ Programming Language


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 3)

Complete the following steps:


1. Change the balance instance variable from private to protected.
protected double balance;
2. Change the Account constructor from public to protected.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

protected Account(double initBalance) {


balance = initBalance;
}

Task 2 – Creating the SavingsAccount Class


In this task, you create the SavingsAccount class source file in the
com.mybank.domain source package of the BankPrj project.
s a
) h a
Complete the following steps:
c o m
1. Create the SavingsAccount class source file in thema
il ฺ
g i d eฺ
1 @
com.mybank.domain source package of the BankPrj u with the
project
G
following characteristics: 21 den t
2 0
Class Name: SavingsAccount
i n t9 Stu
Project: BankPrj ( sa this
N use
APackages
R
LT se to
Location: Source
E
B com.mybank.domain
n
Package:
O l i c e
N codeleso that SavingsAccount extends the Account class.
R EAdd
M O ferab
ns
package com.mybank.domain;
public
A ROclassra
- t SavingsAccount extends Account {
E N n
G}
//
no
insert code here

2. Add the interestRate instance variable to the SavingsAccount class.


private double interestRate;

Class Design Lab 6-13


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 3)

3. Add a public constructor that takes two arguments: initBalance and


interestRate. Pass the initBalance parameter to the super
constructor. Save the interestRate parameter to the instance variable.
public SavingsAccount(double initBalance, double interestRate) {
super(initBalance);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

this.interestRate = interestRate;
}

Task 3 – Creating the CheckingAccount Class


In this task, you create the CheckingAccount class source file in the
com.mybank.domain source package of the BankPrj project.

s a
Complete the following steps:
) h a
1. Create the CheckingAccount class source file in the c o m

ail eฺ
com.mybank.domain source package of the BankPrj project with the
g m id
following characteristics:
@ G u
Class Name: CheckingAccount
0 2 11 ent
n t 9 2
S t ud
Project: BankPrj
( s ai this
AN use
Location: Source Packages
R
LT se to
Package: com.mybank.domain
E
O B that CheckingAccount
e n extends the Account class.
Add code
N
so
l i c
O RE rable
O M sfe
package com.mybank.domain;
publicAclass
- t an
R CheckingAccount
r extends Account {
N
E insert n
G
}
//
no code here
2. Add the overdraftAmount instance variable to the CheckingAccount
class.
private double overdraftAmount;
3. Add a public constructor that takes two arguments: initBalance and
overdraftAmount. Pass the initBalance parameter to the super
constructor. Save the overdraftAmount parameter to the instance
variable.
public CheckingAccount(double initBalance, double overdraftAmount) {
super(initBalance);
this.overdraftAmount = overdraftAmount;
}

Lab 6-14 Java™ Programming Language


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 3)

4. Add a second public constructor that takes only one argument:


initBalance. Call the first constructor with the initBalance parameter
and use the default value 0.0 for the overdraftAmount parameter.
public CheckingAccount(double initBalance) {
this(initBalance, 0.0);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

}
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 ) {
result = false;
} else {
s a
balance = 0.0;
) h a
overdraftAmount -= overdraftNeeded;
c o m
} ฺ
ail eฺ
} else { g m id
@ G u
}
balance -= amount;
0 2 11 ent
return result;
n t 9 2
S t ud
}
( sai this
R AN use
Task 4 – Deleting E to
LTtheseCurrent TestBanking Class
B e n
E NO le lic
Rthis task,
a byou delete the current TestBanking class in the
Ocom.mybank.test
In
r
O M s f e source package of the BankPrj project.
AR n-tra n
E N
G no Task 5 – Copying the TestBanking Class
In this task, you copy the TestBanking.java file from the
d:\labs\student\resources\06_class1 directory into the
com.mybank.test source package of the BankPrj project. The new
TestBanking class sets CheckingAccount and SavingsAccount
objects to different customers.

Task 6 – Compiling the TestBanking Class


In this task, you compile the TestBanking class.

Class Design Lab 6-15


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 3)

Task 7 – Running the TestBanking Program


In this task, you run the TestBanking program. The output should be similar
to the following:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Creating the customer Jane Smith.


Creating her Savings Account with a 500.00 balance and 3% interest.
Creating the customer Owen Bryant.
Creating his Checking Account with a 500.00 balance and no overdraft
protection.
Creating the customer Tim Soley.
Creating his Checking Account with a 500.00 balance and 500.00 in
overdraft protection.
Creating the customer Maria Soley.
Maria shares her Checking Account with her husband Tim.
s a
) h a
Retrieving the customer Jane Smith with her savings account.
c o m
Withdraw 150.00: true ฺ
ail eฺ
Deposit 22.50: true g m id
@ G u
Withdraw 47.62: true
Withdraw 400.00: false 0 2 11 ent
n
Customer [Simms, Jane] has a balance of 324.88t 9 2
S t ud
( sai this
Retrieving the customer Owen Bryant AN with
u e checking account with no
shis
overdraft protection. R
LT se to
Withdraw 150.00: true BE
O c e n
Deposit 22.50: true N le
Etrue l i
Withdraw 47.62: R
O ffalse rab
M
Withdraw 400.00: e
RO [Bryant,
Customer
A t r a ns Owen] has a balance of 324.88
G EN non-
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

Lab 6-16 Java™ Programming Language


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 3)

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ฺ

Customer [Soley, Maria] has a balance of 150.0

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

Class Design Lab 6-17


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Heterogeneous Collection of Customer Accounts (Level 1)

Exercise 2: Creating a Heterogeneous Collection of


Customer Accounts (Level 1)
In this exercise, you create a heterogeneous array to represent the aggregation of
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

customers to accounts. That is, a given customer can have several accounts of
different types.

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 R
CustomerTWith Oneto
L se or More Different Accounts
E
B en
O
Nto modify c Customer class to support a heterogeneous collection
lithe
ofO
E
Your job
R ra
Account
is
b l e
objects.
M
O This sf e
A R a n
tr exercise 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”

Lab 6-18 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Heterogeneous Collection of Customer Accounts (Level 1)

Preparation
There is no preparation required for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Tool references used in this exercise:


● Java Development: Java Packages: Creating Java Packages
● Java Development: Java Classes: Modifying Java Classes: Copying Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
s a
) h a
For this exercise, you work in the BankPrj project in the
c o m
d:\labs\student\projects directory. ฺ
ail eฺ
g m id
@ G u
Task 1 – Modifying the Customer 0 2 11 ent
Class
n t 9 2
S t ud
( sai class
In this task, you modify the Customer t h iins the com.mybank.domain source
package of the BankPrj R
N uModify
Aproject. se the Customer class to handle the
LT saccounts,
association with multiple
E e to just as you did in the Exercise 2 of Lab 5. It
must includeB the publice nmethods: addAccount(Account),
O l i c
EN ble and getNumOfAccounts().
getAccount(int),
R
M O fera
A ROTask
t r a n2s– Copying and Completing the CustomerReport
n-
EN noClass
G
Complete the following steps:
1. Create the com.mybank.report source package in the BankPrj project.
2. Copy the CustomerReport.java file from the
d:\labs\student\resources\06_class1 directory into the
com.mybank.report source package of the BankPrj project.
3. Complete the CustomerReport.java code. You will find comment
blocks that start and end with /*** ... ***/. These comments indicate
the location in the code that you must supply.

Class Design Lab 6-19


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Heterogeneous Collection of Customer Accounts (Level 1)

Task 3 – Copying the TestReport Class


In this task, you copy the TestReport.java file from the
d:\labs\student\resources\06_class1 directory into the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

com.mybank.test source package of the BankPrj project.

Task 4 – Compiling the TestReport Class


In this task, you compile the TestReport class.

Task 5 – Running the TestReport Program


s a
)
In this task, you run the TestReport program. The output should be similar h
to
a
o m
ilฺc ฺ
the following:
a
CUSTOMERS REPORT
================1@
gm uide
1 n t G
2
20 tude
Customer: Simms, Jane t 9
in isisS500.0
Savings Account: current s abalance
( balance th is 200.0
Checking Account: current
A N us e
T R t o
Customer: Bryant,
B EL Owen n se
NO lAccount:
Checking e
lic current balance is 200.0
E e
M OR feraSoley,
Customer:
b Tim
s
RO -tranSavings Account: current balance is 1500.0
A
G EN non Checking Account: current balance is 200.0

Customer: Soley, Maria


Checking Account: current balance is 200.0
Savings Account: current balance is 150.0

Lab 6-20 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Heterogeneous Collection of Customer Accounts (Level 2)

Exercise 2: Creating a Heterogeneous Collection of


Customer Accounts (Level 2)
In this exercise, you create a heterogeneous array to represent the aggregation of
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

customers to accounts. That is, a given customer can have several accounts of
different types.

This exercise contains the following sections:


● “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” s a
“Task 5 – Running the TestReport Program” ) h a

c o m

ail eฺ
g m id
Preparation @ G u
0 2 11 ent
n t
There is no preparation required for this9 2
S
exercise. t ud
( sai this
AN uused
Tool Reference – Tool references
R sein this exercise:
LT sJava e o
tPackages:
E
B en
Java Development:
● Creating Java Packages
O lic Java Classes: Modifying Java Classes: Copying Java
N Development:
E Java

l e
M OR fClasses
e rab
A RO -trans Java
● Development: Java Classes: Modifying Java Classes: Compiling Java

GEN non Classes


● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs

For this exercise, you work in the BankPrj project in the


d:\labs\student\projects directory.

Task 1 – Modifying the Customer Class


In this task, you modify the Customer class in the com.mybank.domain source
package of the BankPrj project. Modify the Customer class to 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().

Class Design Lab 6-21


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Heterogeneous Collection of Customer Accounts (Level 2)

Complete the following steps:


1. Add two instance variables to the Customer class: accounts (an array of
Account objects) and numberOfAccounts (an integer that keeps track of
the next accounts array index). This replaces the single account
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

reference variable, which should be removed.


2. Modify the constructor to initialize the accounts array.
3. Add the addAccount method. This method takes a single parameter, an
Account object, and stores it in the accounts array. It must also
increment the numberOfAccounts instance variable. This method replaces
the setAccount method, which should be removed.
4. Add the getNumOfAccounts accessor method, which returns the
numberOfAccounts instance variable.
5. Add the getAccount method. This method returns the account associated s a
with the given index parameter. This method replaces the previous ) h a
c o m
getAccount method, which should be removed. ฺ
ail eฺ
g m id
@
1 nt G u
Task 2 – Copying and Completing the 2 1CustomerReport
Class t 9 2 0
t u de
s a in is S
N ( e th
T R A
Complete the following steps:
t o us
B EL nse
1. Create the com.mybank.report source package in the BankPrj project.
2. Copy Nthe e
O CustomerReport.java
lic file from the
E l e
M ORcom.mybank.report
a b
d:\labs\student\resources\06_class1
f e r directory into the
O n s source package of the BankPrj project.

N AR n-tra
G E no

Lab 6-22 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Heterogeneous Collection of Customer Accounts (Level 2)

3. Complete the CustomerReport.java code. You will find comment


blocks that start and end with /*** ... ***/. These comments indicate
the location in the code that you must supply.
a. Use the instanceof operator to test what type of account this is and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

set account_type to an appropriate value, such as Savings


Account or Checking Account.
b. Print out the type of account and the balance.

Task 3 – Copying the TestReport Class


In this task, you copy the TestReport.java file from the
d:\labs\student\resources\06_class1 directory into the
com.mybank.test source package of the BankPrj project. s a
) h a
c o m
Task 4 – Compiling the TestReport Class ail eฺ ฺ
@ gm uid
2
In this task, you compile the TestReport class. 1 1 nt G
t 9 20 tude
s a in is S
Task 5 – Running the N ( e th Program
TestReport
T R A
t o us
L the TestReport
Erun se
O B
In this task, you
e n program. The output should be similar to
E N listed
the output
l e licpage L6-20.
on

M OR ferab
A RO -trans
GEN non

Class Design Lab 6-23


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Heterogeneous Collection of Customer Accounts (Level 3)

Exercise 2: Creating a Heterogeneous Collection of


Customer Accounts (Level 3)
In this exercise, you create a heterogeneous array to represent the aggregation of
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

customers to accounts. That is, a given customer can have several accounts of
different types.

This exercise contains the following sections:


● “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” s a
“Task 5 – Running the TestReport Program” ) h a

c o m

ail eฺ
g m id
Preparation @ G u
0 2 11 ent
There is no preparation required for n t
this9 2
S
exercise. t ud
( sai this
Tool Reference – Tool A
R
N uused
references se in this exercise:
E LT sJava e toPackages: Creating Java Packages
O

B en
Java Development:

E N ●
l e lic Java Classes: Modifying Java Classes: Copying Java
Java Development:

M OR feClasses
rab
A RO -trans Java ● Development: Java Classes: Modifying Java Classes: Compiling Java

G EN non Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs

For this exercise, you work in the BankPrj project in the


d:\labs\student\projects directory.

Task 1 – Modifying the Customer Class


In this task, you modify the Customer class in the com.mybank.domain source
package of the BankPrj project. Modify the Customer class to 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().

Complete the following steps:


Lab 6-24 Java™ Programming Language
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Heterogeneous Collection of Customer Accounts (Level 3)

1. Add two instance variables to the Customer class: accounts (an array of
Account objects) and numberOfAccounts (an integer that keeps track of
the next accounts array index). This replaces the single account
reference variable, which should be removed.
private Account[] accounts;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

private int numberOfAccounts;


2. Modify the constructor to initialize the accounts array.
public Customer(String f, String l) {
firstName = f;
lastName = l;
// initialize accounts array
accounts = new Account[10];
numberOfAccounts = 0;
}
s a
3. Add the addAccount method. This method takes a single parameter, ) h
an
a
o m
increment the numberOfAccounts instance variable. Thisa ฺc ฺreplaces
Account object, and stores it in the accounts array. It must also
ilmethod
the setAccount method, which should be removed.
@ gm uide
2 1 1 nt G
20 tude
public void addAccount(Account acct) {
int i = numberOfAccounts++; t 9
in is S
accounts[i] = acct;
s a
( e th
}
A N usaccessor method, which returns the
T R t o
EL nseinstance variable.
4. Add the getNumOfAccounts
B
numberOfAccounts
O lice {
N
RE rable
public int getNumOfAccounts()
O
return numberOfAccounts;
M sfe
} O
R -tra5.n Add the getAccount method. This method returns the account associated
A
GEN non with the given index parameter. This method replaces the previous
getAccount method, which should be removed.
public Account getAccount(int account_index) {
return accounts[account_index];
}

Task 2 – Copying and Completing the CustomerReport


Class
Complete the following steps:
1. Create the com.mybank.report source package in the BankPrj project.

Class Design Lab 6-25


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating a Heterogeneous Collection of Customer Accounts (Level 3)

2. Copy the CustomerReport.java file from the


d:\labs\student\resources\06_class1 directory into the
com.mybank.report source package of the BankPrj project.
3. Complete the CustomerReport.java code. You will find comment
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

blocks that start and end with /*** ... ***/. These comments indicate
the location of the code that you must supply.
a. Use the instanceof operator to test what type of account this is and
set account_type to an appropriate value, such as Savings
Account or Checking Account.
if ( account instanceof SavingsAccount ) {
account_type = "Savings Account";
} else if ( account instanceof CheckingAccount ) {
account_type = "Checking Account";
} else { s a
account_type = "Unknown Account Type"; ) h a
}
c o m
il ฺ
b. Print out the type of account and the balance. ma eฺ
g
@current i d
ubalance
System.out.println(" " + account_type + ":
1 1 t G is "

9 2 02 uden
+ account.getBalance());

a i nt is St
Task 3 – Copying the N (s e th Class
TestReport
T R A
t o us
In this task, B ELcopy nthesTestReport.java
e
O you
l i c e file from the
EN ble source package of the BankPrj
d:\labs\student\resources\06_class1
R
directory into the

M O fera
com.mybank.test project.

A RO -trans
G EN noTask
n 4 – Compiling the TestReport Class
In this task, you compile the TestReport class.

Task 5 – Running the TestReport Program


In this task, you run the TestReport program. The output should be similar to
the output listed on page L6-20.

Lab 6-26 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 3: Creating a Batch Program (Advanced)

Exercise 3: Creating a Batch Program (Advanced)


In this exercise, you create a batch program to accumulate interest for each
savings account on a monthly basis.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Note – This is an advanced exercise. This exercise is optional and should only be
attempted if you completed all of the previous exercises for this module.

Figure 6-3 shows the dependencies between the class used by the TestBatch
program.

TestBatch
s a
) h a
c o m

ail eฺ
g m id
AccumulateSavingsBatch
@ u
CustomerReport
G
-bank : Bank
0 2 11: Bank
-bank
e n t
«methods»
n t 9 S t ud
2 «methods»
+setBank(bank:Bank):void(s
+doBatch():void ai thi+generateReport():void
s
AN use
+setBank(bank:Bank):void

R
LT se to
E
B en
O lic
N SavingsAccount
E l e
M OR-interestRate
f e r a b
O n s : double

N AR n-tra «constructors»
GE no +SavingsAccount(initBalance:double,
interestRate:double)

«methods»
+accumulateInterest():void

Figure 6-3 Class Dependencies for the TestBatch Program

This exercise contains the following sections:


● “Task 1 – Modifying the SavingsAccount Class”
● “Task 2 – Creating the AccumulateSavingsBatch Class”
● “Task 3 – Copying the TestBatch Class”
● “Task 4 – Compiling the TestBatch Class”

Class Design Lab 6-27


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 3: Creating a Batch Program (Advanced)

● “Task 5 – Running the TestBatch Program”

Preparation
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

There is no preparation required for this exercise.

Tool Reference – Tool references used in this exercise:


● Java Development: Java Classes: Creating Java Classes
● Java Development: Java Classes: Modifying Java Classes: Copying Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes s a
) h a

c o m
Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs ฺ
ail eฺ
m
gthe uid
For this exercise, you work in the BankPrj project
1 @
1 nt G
in
d:\labs\student\projects directory. 2
20 tude
t 9
in is S
s a
( e th
Task 1 – Modifying the A N SavingsAccount
u s Class
L TR e to
BE gains
A savings account
O e n sinterest. The bank permits customers to store money in a
E N account
savings
l e lic on a monthly basis, the savings account will accumulate
and,
R onratheb following formula: balance = balance + (balance * (interestRate /
Obased
O M s
12)).
n fe
N AR n-tra
G E no In this task, you add the accumulateInterest method to perform this
operation.

Task 2 – Creating the AccumulateSavingsBatch


Class
Complete the following steps:
1. Create the AccumulateSavingsBatch class with the following
characteristics:
Class Name: AccumulateSavingsBatch
Project: BankPrj
Location: Source Packages
Package: com.mybank.batch

Lab 6-28 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 3: Creating a Batch Program (Advanced)

The class must conform to the specification defined in Figure 6-3 on


page L6-27.
2. Add an instance variable bank of the type Bank.
3. Add a setBank method to set the method parameter to the bank instance
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

variable.
4. Add a doBatch method using the following hints:
for each Customer in the Bank do
for each Account in the Customer do
if the Account is a SavingsAccount,
then call the accumulateInterest method

Task 3 – Copying the TestBatch Class a


h a s
m )
In this task, you copy the TestBatch.java file from the
ฺ c o
ail eฺ
d:\labs\student\resources\06_class1 directory into the
m
g
com.mybank.test source package of the BankPrj project.
@ u id
11 ent G
0 2
Task 4 – Compiling the TestBatch n t 9 2 Class
S t ud
( sai this
In this task, you compileA
R the u se class.
NTestBatch
E LT se to
O B en
Task 5 E –N Runningl e lic the TestBatch Program
M OR ferab
RO -trathe s task, you run the TestBatch program. The output should be similar to
Innthis
A
EN non
following:
G CUSTOMERS REPORT
================

Customer: Simms, Jane


Savings Account: current balance is 500.0
Checking Account: current balance is 200.0

Customer: Bryant, Owen


Checking Account: current balance is 200.0

Customer: Soley, Tim


Savings Account: current balance is 1500.0
Checking Account: current balance is 200.0

Customer: Soley, Maria


Checking Account: current balance is 200.0

Class Design Lab 6-29


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 3: Creating a Batch Program (Advanced)

Savings Account: current balance is 150.0

ACCUMULATE SAVINGS BATCH EXECUTED

CUSTOMERS REPORT
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

================

Customer: Simms, Jane


Savings Account: current balance is 501.25
Checking Account: current balance is 200.0

Customer: Bryant, Owen


Checking Account: current balance is 200.0

Customer: Soley, Tim


s a
Savings Account: current balance is 1509.375
) h a
Checking Account: current balance is 200.0
c o m

ail eฺ
Customer: Soley, Maria
g m id
@
1 nt
Checking Account: current balance is 200.0 G u
Savings Account: current balance 2 is1 150.625
t 9 2 0
t u de
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
G EN non

Lab 6-30 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

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

Class Design Lab 6-31


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary
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

Lab 6-32 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Lab 7
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Advanced Class Features

Objectives
Upon completion of this lab, you should be able to:
● Apply static class members to resolve a design decision. s a
Create abstract classes and interfaces, and explore the polymorphic ) h a

c o m
properties of these types of components ฺ
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 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)

Exercise 1: Applying Static Members to a Design (Level 1)


In this exercise, you apply static class members to resolve a design decision. The
Banking Project currently uses a concrete class to represent the concept of a bank,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
com.mybank.domain
) h a
c o m
Bank

ail eฺ
g m id
-customers : Customer[] @ G u
-numberOfCustomers : int
0 2 11 ent
«constructors»
n t 9 2
S t ud
-Bank()
( sai this
«methods»
R AN use
+getNumOfCustomers():int EL
T e to
+addCustomer(f:String, l:String)

O B ens
N le lic
+getCustomer(index:int):Customer
E
M OR ferab
R O rans serves

N A n-t Customer has-a 1


Account
G E no 0..*

Figure 7-1 UML Diagram of the Bank Utility Class

This exercise contains the following sections:


● “Task 1 – Modifying the Bank Class”
● “Task 2 – Modifying the CustomerReport Class”
● “Task 3 – Deleting the Current TestReport Class”
● “Task 4 – Copying the TestReport Class”
● “Task 5 – Compiling the TestReport Class”
● “Task 6 – Running the TestReport Program”

Lab 7-2 Java™ Programming Language


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)

Preparation
There is no preparation required for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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: Modifying Java Classes: Copying Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
Java Development: Java Classes: Modifying Java Classes: Executing Java s a

Programs ) h a
c o m
For this exercise, you work in the BankPrj project in the ai
l ฺ
g m i d eฺ
d:\labs\student\projects directory.
1 1 @ t Gu
9 2 02 uden
Task 1 – Modifying the Bank a i t
nClass i s St
N (s e th
In this task, you openT R A
t
the BankPrjo usproject in the
B EL nse
d:\labs\student\projects directory, and modify the Bank class in the
com.mybank.domain e
NO(bothleinstance
lic source package of the BankPrj project. All the
R E
members b variables and methods) should be changed to static, as
O
M shown f a
einr Figure 7-1 on page L7-2. Also, move the original variable initialization
O n s
R -tradeclarations.
code from the constructor to either a static block or on the static variable
A
GEN non
Task 2 – Modifying the CustomerReport Class
In this task, you modify the CustomerReport class source file in the
com.mybank.report source package of the BankPrj project. The updated
CustomerReport class uses the Bank class as a utility class.

Task 3 – Deleting the Current TestReport Class


In this task, you delete the current TestReport class in the
com.mybank.test source package of the BankPrj project.

Advanced Class Features Lab 7-3


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)

Task 4 – Copying the TestReport Class


In this task, you copy the TestReport.java file from the
d:\labs\student\resources\07_class2 directory to the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

com.mybank.test source package of the BankPrj project.

Task 5 – Compiling the TestReport Class


In this task, you compile the TestReport class.

Task 6 – Running the TestReport Program


s a
h a
m) 1).
In this task, you run the TestReport program. The output should be similar to
the output from previous tests as shown in Exercise 2, Task 5 of Lab 6co
(Level
a ilฺ ฺ
@ 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
G EN non

Lab 7-4 Java™ Programming Language


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 2)

Exercise 1: Applying Static Members to a Design (Level 2)


In this exercise, you apply static class members to resolve a design decision. The
Banking Project currently uses a concrete class to represent the concept of a bank,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.

This exercise contains the following sections:


s a
“Task 1 – Modifying the Bank Class” ) h a

c o m
● “Task 2 – Modifying the CustomerReport Class” ฺ
ail eฺ
g m id
●“Task 3 – Deleting the Current TestReport Class”
@ G u
●“Task 4 – Copying the TestReport Class”
0 2 11 ent
t 9 2 Class”tud

a i n
“Task 5 – Compiling the TestReport
i s S
s h
( e t Program”
●“Task 6 – Running the
A NTestReport
us
T R t o
B EL nse
Preparation
N O lice
O RE rable
O M There
n s feis no preparation required for this exercise.
N AR n-tra
GE no 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: Modifying Java Classes: Copying Java
Classes
● 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


d:\labs\student\projects directory.

Advanced Class Features Lab 7-5


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 2)

Task 1 – Modifying the Bank Class


In this task, you modify the Bank class in the com.mybank.domain source
package of the BankPrj project. All the members (both instance variables and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

methods) should be changed to static, as shown in Figure 7-1 on page L7-2.

Complete the following steps:


1. Open the BankPrj project in the d:\labs\student\projects
directory if you have closed it.
2. Open the Bank class in the com.mybank.domain source package of the
BankPrj project.
3. Change all instance variables to static.
s a
4. Move the original variable initialization code from the constructor to either
) h a
a static block or on the static variable declarations.
c o m
5. Change the constructor to be private and remove the body of a l
itheฺ
constructor. g m i d eฺ
1 1 @ t Gu
6. Change all methods to static.
9 2 02 uden
a i nt is St
Task 2 – Modifying the CustomerReport
N (s e th Class
A s
L TR e to u
In this task, you B E thenCustomerReport
modify s class source file in the
N O
com.mybank.report l ic e
source package of the BankPrj project. The updated
E e
R rabl class uses the Bank class as a utility class.
CustomerReport
O
M sfe
O an the following steps:
R -Complete
r
A t
G EN non 1. Remove the bank instance variable and the getBank and setBank
methods.
2. Modify the generateReport method to use the static methods from the
new Bank utility class design.

Task 3 – Deleting the Current TestReport Class


In this task, you delete the current TestReport class in the
com.mybank.test source package of the BankPrj project.

Lab 7-6 Java™ Programming Language


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 2)

Task 4 – Copying the TestReport Class


In this task, you copy the TestReport.java file from the
d:\labs\student\resources\07_class2 directory to the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

com.mybank.test source package of the BankPrj project.

Task 5 – Compiling the TestReport Class


In this task, you compile the TestReport class.

Task 6 – Running the TestReport Program


s a
In this task, you run the TestReport program. The output should be similar ) h a to
the output from previous tests as shown in Exercise 2, Task 5 of Lab c o6m(Level 1).
i l ฺ
g ma ideฺ
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
N on
GE n

Advanced Class Features Lab 7-7


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)

Exercise 1: Applying Static Members to a Design (Level 3)


In this exercise, you apply static class members to resolve a design decision. The
Banking Project currently uses a concrete class to represent the concept of a bank,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.

This exercise contains the following sections:


s a
“Task 1 – Modifying the Bank Class” ) h a

c o m
● “Task 2 – Modifying the CustomerReport Class” ฺ
ail eฺ
g m id
“Task 3 – Deleting the Current TestReport Class”

@ G u
“Task 4 – Copying the TestReport Class”

0 2 11 ent
t 9 2 Class”tud

a i n
“Task 5 – Compiling the TestReport
i s S
s h
( e t Program”
“Task 6 – Running the

A NTestReport
us
T R t o
B EL nse
Preparation
N O lice
O RE rable
O M There
n s feis no preparation required for this exercise.
N AR n-tra
G E no 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: Modifying Java Classes: Copying Java
Classes
● 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


d:\labs\student\projects directory.

Lab 7-8 Java™ Programming Language


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)

Task 1 – Modifying the Bank Class


In this task, you modify the Bank class in the com.mybank.domain source
package of the BankPrj project. All the members (both instance variables and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

methods) should be changed to static, as shown in Figure 7-1 on page L7-2.

Complete the following steps:


1. Open the BankPrj project in the d:\labs\student\projects
directory if you have closed it.
2. Open the Bank class in the com.mybank.domain source package of the
BankPrj project.
3. Change all instance variables to static.
s a
private static Customer[] customers;
private static int numberOfCustomers; ) h a
c o m
4. ฺ
ail eฺ
Move the original variable initialization code from the constructor to either
g m id
a static block or on the static variable declarations.
@ G u
static {
0 2 11 ent
customers = new Customer[10];
n t 9 2
S t ud
sai this
numberOfCustomers = 0;
} (
R
5. Change the constructor se and remove the body of the
ANto beuprivate
E
constructor. LT se to
private Bank() { O
B en
E N lshould
e lic never be called
OR ferab
// this constructor
} M
A RO -tra6.ns Change all methods to static.
GENpublic
nonstatic 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)

Task 2 – Modifying the CustomerReport Class


In this task, you modify the CustomerReport class source file in the
com.mybank.report source package of the BankPrj project. The updated
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

CustomerReport class uses the Bank class as a utility class.

Complete the following steps:


1. Remove the bank instance variable and the getBank and setBank
methods.
2. Modify the generateReport method to use the static methods from the
new Bank utility class design.
public void generateReport() {
s a
// Print report header
) h a
System.out.println("CUSTOMERS REPORT");
c o m
System.out.println("================"); ฺ
ail eฺ
g m id
@ G u
// For each customer...
for ( int cust_idx = 0; 0 2 11 ent
cust_idx < Bank.getNumOfCustomers();
n t 9 2
S t ud
cust_idx++ ) { ( sai this
AN use
Customer customer = Bank.getCustomer(cust_idx);
R
// and so on...
E LT se to
}
O B en
}
E N le lic
M OR ferab
RTask s
O 3ra–nDeleting the Current TestReport Class
A
N on - t
GE n In this task, you delete the current TestReport class in the
com.mybank.test source package of the BankPrj project.

Task 4 – Copying the TestReport Class


In this task, you copy the TestReport.java file from the
d:\labs\student\resources\07_class2 directory to the
com.mybank.test source package of the BankPrj project.

Lab 7-10 Java™ Programming Language


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)

Task 5 – Compiling the TestReport Class


In this task, you compile the TestReport class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 6 – Running the TestReport Program


In this task, you run the TestReport program. The output should be similar to
the output from previous tests as shown in Exercise 2, Task 5 of Lab 6 (Level 1).

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

Advanced Class Features Lab 7-11


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 1)

Exercise 2: Working With Interfaces and Abstract Classes


(Level 1)
In this exercise, you create abstract classes and interfaces, and explore the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

polymorphic properties of these types of components. You create a hierarchy of


animals that is rooted in an abstract class Animal. Several of the animal classes
implement an interface called Pet. Figure 7-2 shows a UML class diagram of the
animal classes that you create.

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 thisFish
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

Figure 7-2 Animal and Pet Hierarchy

This exercise contains the following sections:


● “Task 1 – Creating the Pet Interface”
● “Task 2 – Creating the Animal Classes”
● “Task 3 – Creating the TestAnimals Class”
● “Task 4 – Compiling the TestAnimals Class”
● “Task 5 – Running the TestAnimals Program”

Lab 7-12 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 1)

Preparation
There is no preparation required for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Tool references used in this exercise:


● Java Development: Java Application Projects: Opening Projects
● Java Development: Java Classes: Creating Java Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
s a
For this exercise, you work in the InterfaceProject project in the ha
m )
d:\labs\student\exercises\07_class2\exercise2 directory. o
a ilฺc ฺ
@ gm uide
Task 1 – Creating the Pet Interface11
n t G
2
20 tude
Complete the following steps: t 9
in is S
s a
( eproject th in the
A
1. Open the InterfaceProject N us
T R t o
d:\labs\student\exercises\07_class2\exercise2
B
directory. EL nse
NO the
2. ECreate l i ceinterface with the following characteristics:
R rable
Pet
O
M sfClasse Name: Pet
O
R -tran Project: InterfaceProject
A
GEN non Location: Source Packages
Package: default package

The Pet interface must satisfy the UML diagram in Figure 7-1 on page L7-2.

Advanced Class Features Lab 7-13


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 1)

Task 2 – Creating the Animal Classes


Complete the following steps:
1. Create the Animal class with the following characteristics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Class Name: Animal


Project: InterfaceProject
Location: Source Packages
Package: default package

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 for the Animal class might
s a
say something similar to This animal walks on 4 legs, where 4 is the
) h a
value of the legs instance variable.
c o m

ail eofฺ the
m
2. Create the Spider, Cat, and Fish classes in the Source Packages
id 7-1 on
g in Figure
@
InterfaceProject project to satisfy the UML diagram
G u
page L7-2.
0 2 11 ent
n t 9 2
S t ud
( s ai this
Task 3 – Creating the TestAnimals N use Class
A
L TR e to
BE steps:
Complete the following
O e n s
1. InEthis
c the TestAnimals class with the following
N task,leyoulicreate
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();

Lab 7-14 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 1)

Experiment by:
● Calling the methods in each object
● Casting objects
Using polymorphism
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

● Using super to call superclass methods

Task 4 – Compiling the TestAnimals Class


In this task, you compile the TestAnimals class.

Task 5 – Running the TestAnimals Program s a


) h a
c o m

In this task, you run the TestAnimals program.
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

Advanced Class Features Lab 7-15


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 2)

Exercise 2: Working With Interfaces and Abstract Classes


(Level 2)
In this exercise, you create abstract classes and interfaces, and explore the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

polymorphic properties of these types of components. You create a hierarchy of


animals that is rooted in an abstract class Animal. Several of the animal classes
will implement an interface called Pet. Use Figure 7-2 on page L7-12 as a
reference. You experiment with variations of these animals, their methods, and
polymorphism.

This exercise contains the following sections:


● “Task 1 – Creating the Pet Interface”
● “Task 2 – Creating the Animal Classes” s a
) h a
● “Task 3 – Creating the TestAnimals Class”
c o m
“Task 4 – Compiling the TestAnimals Class”
● ฺ
ail eฺ
“Task 5 – Running the TestAnimals Program” @g
m id

G u
0 2 11 ent
n t 9 2
S t ud
Preparation
( sai this
ANfor this
u e
sexercise.
There is no preparationT R
L se to
required
E
B en
O
N –leTool
Tool Reference licreferences used in this exercise
E
M ORJavafeDevelopment:
● rab Java Application Projects: Opening Projects
O s
R -tranJava Development: Java Classes: Creating Java Classes
A ●

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 InterfaceProject project in the


d:\labs\student\exercises\07_class2\exercise2 directory.

Task 1 – Creating the Pet Interface


Complete the following steps:

Lab 7-16 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 2)

1. Open the InterfaceProject project in the


d:\labs\student\exercises\07_class2\exercise2
directory.
2. Create the Pet interface with the following characteristics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Class Name: Pet


Project: InterfaceProject
Location: Source Packages
Package: default package

The Pet interface must satisfy the UML diagram in Figure 7-1 on page L7-2.

Task 2 – Creating the Animal Classes s a


) h a
c o m
Complete the following steps: ฺ
ail eฺ
g m id
1. Create the Animal class.
@ G u
a. Create the Animal class with the 2
0 11 echaracteristics:
following n t
Class Name: Animal int9
2
S tud
( sa this
AN use
Project: InterfaceProject
R
LTSource
Location: toPackages
E
B default n s e
N O Package:
l i c e package

O REb. raDeclare
ble a protected integer instance variable called legs, which
O M sfe records the number of legs for this animal.
A R -tran c. Define a protected constructor that initializes the legs instance
GEN non 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).

Advanced Class Features Lab 7-17


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 2)

2. Create the Spider class.


a. Create the Spider class with the following characteristics:
Class Name: Spider
Project: InterfaceProject
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Location: Source Packages


Package: default package
Add code so that Spider extends the Animal class.
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
Location: Source Packages
0 2 11 ent
n t 9 2
S t ud
Package: default package
( s ai this
Add code so that Cat
Pet interface. RA
N extends
u sethe Animal class and implements the
T e to
Lmust
E
B eninclude
b. This class s a String instance variable to store the name
O
Nof the lpet.lic
E e
M ORc. feDefine
rab a constructor that takes one String parameter that specifies
A RO -trans the cat’s name. This constructor must also call the superclass

EN non
constructor to specify that all cats have four legs.
G 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
Location: Source Packages
Package: default package

Lab 7-18 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 2)

Add code so that Fish extends the Animal class and implements the
Pet interface.

b. This class must include a String instance variable to store the name
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

of the pet.
c. Define a no-arg constructor that calls the superclass constructor to
specify that fish do not have legs.
d. Implement the Pet interface methods.
e. Override the walk method. This method should call the super method
and they print a message that fish do not walk
f. Implement the eat method.

s a
) h a
Task 3 – Creating the TestAnimals Class m
ฺ c o
a il
Complete the following steps: g m i d eฺ
1 1 @ t Gu
1. In this task, you create the TestAnimals
0 2 dwith
class
e nthe following
characteristics: 2
t9 Stu
i n
Class Name: TestAnimals ( sa this
R AN use
Project: InterfaceProject
E LT sPackages
e to
B en
Location:
O
Source

E N ledefault
Package: lic package
R b
rathe main method to create and manipulate instances of the classes you
O2. f.Add
M e
A RO -trans created previously.
GEN non 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
● Using super to call superclass methods

Advanced Class Features Lab 7-19


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 2)

Task 4 – Compiling the TestAnimals Class


In this task, you compile the TestAnimals class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 5 – Running the TestAnimals Program


In this task, you run the TestAnimals program.

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

Lab 7-20 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 3)

Exercise 2: Working With Interfaces and Abstract Classes


(Level 3)
In this exercise, you create a hierarchy of animals that is rooted in an abstract
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

class Animal. Several of the animal classes implement an interface called Pet.
Use Figure 7-2 on page L7-12 as a reference. You experiment with variations of
these animals, their methods, and polymorphism.

This exercise contains the following sections:


● “Task 1 – Creating the Pet Interface”
● “Task 2 – Creating the Animal Classes”
● “Task 3 – Creating the TestAnimals Class”
s a
● “Task 4 – Compiling the TestAnimals Class”
) h a
c o m
● “Task 5 – Running the TestAnimals Program” ฺ
ail eฺ
g m id
@ G u
Preparation
0 2 11 ent
n t 9 2
S t ud
(
There is no preparation required aithis exercise.
sfor t h is
R AN use
Tool Reference –LTool
E e to used in this exercise:
T references
s
B en Java Application Projects: Opening Projects
Java
● O
N le lic
Development:
E
M OR fJava
e
● b
raDevelopment: Java Classes: Creating Java Classes

A RO -trans Java
● Development: Java Classes: Modifying Java Classes: Compiling Java

GEN non Classes


● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs

For this exercise, you work in the InterfaceProject project in the


d:\labs\student\exercises\07_class2\exercise2 directory.

Task 1 – Creating the Pet Interface


Complete the following steps:
1. Open the InterfaceProject project in the
d:\labs\student\exercises\07_class2\exercise2
directory.

Advanced Class Features Lab 7-21


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 3)

2. Create the Pet interface with the following characteristics:


Class Name: Pet
Project: InterfaceProject
Location: Source Packages
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Package: default package

The Pet interface must satisfy the UML diagram in Figure 7-1 on page L7-2.
public interface Pet {
public String getName();
public void setName(String n);
public void play();
}
s a
) h a
Task 2 – Creating the Animal Classes c o m

ail eฺ
g m id
Complete the following steps: @ G u
0 2 11 ent
1. Create the Animal class.
n t 9 2
S t ud
a. ai thethfollowing
Create the Animal classswith
( is characteristics:
AN use
Class Name: Animal
R
Project:E LT se to
InterfaceProject
O B en
E N le lSource
Location: ic Packages

M OR fePackage:
rab default package
A RO -trana.s Declare a protected integer instance variable called legs, which
EN non
Gprotected
records the number of legs for this animal.
int legs;
b. Define a protected constructor that initializes the legs instance
variable.
protected Animal(int legs) {
this.legs = legs;
}
c. Declare an abstract method eat.
public abstract void eat();
d. Declare a concrete method walk that prints out something about how
the animals walks (include the number of legs).
public void walk() {
System.out.println("This animal walks on " + legs + " legs.");

Lab 7-22 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 3)

}
2. Create the Spider class.
a. Create the Spider class with the following characteristics:
Class Name: Spider
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Project: InterfaceProject
Location: Source Packages
Package: default package
Add code so that Spider extends the Animal class.
a. The Spider class extends the Animal class.
public class Spider extends Animal {
// more code here
s a
}
) h a
b. o m
Define a no-arg constructor that calls the superclass constructor to
c
specify that all spiders have eight legs. ฺ
ail eฺ
g m id
public Spider() { @ G u
super(8);
0 2 11 ent
}
n t 9 2
S t ud
sai this
c. Implement the eat method.
(
public void eat() {
R AN use
T eeats
System.out.println("TheLspider
E to a fly.");
} B en s
O
N the
3. ECreate lic class.
l e Cat
M OR fa.eraCreate
b
the Cat class with the following characteristics:
O n s
N AR n-tra Class Name: Cat
GE n o Project: InterfaceProject
Location: Source Packages
Package: default package
Add code so that Cat extends the Animal class and implements the
Pet interface.
b. This class must include a String instance variable to store the name
of the pet.
private String name;
c. Define a constructor that takes one String parameter that specifies
the cat’s name. This constructor must also call the superclass
constructor to specify that all cats have four legs.
public Cat(String n) {

Advanced Class Features Lab 7-23


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 3)

super(4);
name = n;
}
d. Define another constructor that takes no parameters. Have this
constructor call the previous constructor (using the this keyword)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

and pass an empty string as the argument.


public Cat() {
this("");
}
e. Implement the Pet interface methods.
public String getName() {
return name;
}
public void setName(String n) { s a
name = n; ) h a
} c o m
public void play() {

ail eฺ
g m id
System.out.println(name + " likes to play with string.");
@ G u
}
0 2 11 ent
f. Implement the eat method. t92
n S t ud
public void eat() { ( sai this
System.out.println("Cats like to
R A u se and mice.");
Neat spiders
}
E LT se to
4. Create the B e
Fish class. n
O l i c
N lethe Fish class with the following characteristics:
Ra.E Create
M rabName: Fish
O feClass
A RO -trans Project: InterfaceProject
N on
GE n Location: Source Packages
Package: default package
Add code so that Fish extends the Animal class and implements the
Pet interface.
b. This class must include a String instance variable to store the name
of the pet.
private String name;
c. Define a no-arg constructor that calls the superclass constructor to
specify that fish do not have legs.
public Fish() {
super(0); // this line must be here
}

Lab 7-24 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 3)

d. Implement the Pet interface methods.


public void setName(String name) {
this.name = name;
}
public String getName() {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

return name;
}
public void play() {
System.out.println("Fish swim in their tanks all day.");
}
e. Override the walk method. This method should call the super method
and they print a message that fish do not walk
public void walk() {
super.walk();
s a
System.out.println("Fish, of course, can’t walk; they swim.");
) h a
}
c o m
f. Implement the eat method.

ail eฺ
g m id
public void eat() { @ G u
System.out.println("Fish eat pond scum."); 211 n t
2 0 ud e
}
n t 9 S t
( sai this
Task 3 – CreatingTthe R AN u se
TestAnimals Class
L t o
B E nse
N Othe following
Complete l i ce steps:
O REIn rthis
1. a le you create the TestAnimals class with the following
btask,
O e
M sfcharacteristics:
n
AR n-tra Class Name: TestAnimals
E N
G no Project: InterfaceProject
Location: Source Packages
Package: default package
2. Add the main method to create and manipulate instances of the classes you
created previously.
Here is a sample test program:
public class TestAnimals {
public static void main(String[] args) {
Fish f = new Fish();
Cat c = new Cat("Fluffy");
Animal a = new Fish();
Animal e = new Spider();

Advanced Class Features Lab 7-25


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Working With Interfaces and Abstract Classes (Level 3)

Pet p = new Cat();

// Demonstrate different implementations of an interface


f.play();
c.play();
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

// Demonstract virtual method invocation


e.eat();
e.walk();

// Demonstrate calling super methods


a.walk();
}
}

s a
) h a
Task 4 – Compiling the TestAnimals Class o m
ฺ c
m ail eฺ
In this task, you compile the TestAnimals class.
@ g u id
11 ent G
0 2
Task 5 – Running the TestAnimals n t 9 S t ud
2 Program
( sai this
e
AN usprogram.
R
In this task, you run the TestAnimals
LT se to
E
B en
O
N le lic
E
M OR ferab
A RO -trans
G EN non

Lab 7-26 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

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

Advanced Class Features Lab 7-27


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 8
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Exceptions and Assertions

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)

Exercise: Creating Your Own Exception (Level 1)


In this exercise, you create an OverdraftException that is thrown by the
withdraw method in the Account class. In the previous design, the deposit
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

and withdraw methods return a Boolean flag to indicate whether the operation
was successful or not. This design has several flaws, one of which is that a false
return value does not give the calling client any indication of why the operation
was not successful. In the new design, you will use exceptions to indicate
operation failure.

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 m
ฺ c o
m ail eฺ
Account
«exception»g
@ u id
#balance : double 1 nt
1java.lang}
Exception G
2 0 2
{from
de
«constructors»
t 9 S t u
#Account(initBalance:double)
s a in«constructors»
i s
h
N ( use+Exception(msg:String)
t
«methods»
A
+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

Figure 8-1 The withdraw Method Throws the OverdraftException

This exercise contains the following sections:


● “Task 1 – Creating the OverdraftException Class”
● “Task 2 – Modifying the Account Class”

Lab 8-2 Java™ Programming Language


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)

● “Task 3 – Modifying the CheckingAccount Class”


● “Task 4 – Deleting the Current TestBanking Class”
● “Task 5 – Copying the TestBanking Class”
“Task 6 – Compiling the TestBanking Class”
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

● “Task 7 – Running the TestBanking Program”

Preparation
There is no preparation required for this exercise.

Tool Reference – Tool references used in this exercise:


s a
● Java Development: Java Classes: Creating Java Classes
) h a
c o m
● Java Development: Other Files: Deleting Files ฺ
ailCopying
g m
Java Development: Java Classes: Modifying Java Classes:

i d eฺ Java
Classes
1 1 @ t Gu
02 Java d n Compiling Java
eClasses:
2
Java Development: Java Classes: Modifying
9 u
nt is St

Classes a i
N (s eModifying
th
Java Development: Java

R A u s
Classes: Java Classes: Executing Java
Programs
E LT se to
O B en
N le lyou
For this
E exercise, ic work in the BankPrj project in the
O R rab
d:\labs\student\projects directory.

O M sfe
A R -tran
GEN non

Exceptions and Assertions Lab 8-3


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)

Task 1 – Creating the OverdraftException Class


In this task, you create the OverdraftException class in the
com.mybank.domain source package of the BankPrj project with the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

following characteristics:
Class Name: OverdraftException
Project: BankPrj
Location: Source Packages
Package: com.mybank.domain
Add code so that OverdraftException extends the Exception class.

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 file
0 2 11in theent
com.mybank.domain source package of the 2
t 9 t d This class must
BankPrjuproject.
a i
satisfy the UML diagram in Figure 8-1 on n page s
L8-2.
i S In particular, the deposit
s h
and withdraw methods should not( return a boolean
A N use t flag.

L TR e to
Task 3 – Modifying O BE the e n sCheckingAccount Class
E N le lic
InO
R ryou a bmodify 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 must

G EN non-satisfy the UML diagram in Figure 8-1 on page L8-2.


Task 4 – Deleting the Current TestBanking Class
In this task, you delete the current TestBanking class in the
com.mybank.test source package of the BankPrj project.

Task 5 – Copying the TestBanking Class


In this task, you copy the TestBanking.java file from the
d:\labs\student\resources\08_except directory to the
com.mybank.test source package of the BankPrj project.

Lab 8-4 Java™ Programming Language


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)

Task 6 – Compiling the TestBanking Class


In this task, you compile the TestBanking class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 7 – Running the TestBanking Program


In this task, you run the TestBanking program. The output should be similar
to the following:
Customer [Simms, Jane] has a checking balance of 200.0 with a 500.00
overdraft protection.
Checking Acct [Jane Simms] : withdraw 150.00
Checking Acct [Jane Simms] : deposit 22.50
s a
Checking Acct [Jane Simms] : withdraw 147.62
Checking Acct [Jane Simms] : withdraw 470.00 ) h a
c o m
Exception: Insufficient funds for overdraft protection
Customer [Simms, Jane] has a checking balance of 0.0

Deficit: 470.0
ail eฺ
g m id
@ G u
0 2 11 ent
Customer [Bryant, Owen] has a savings balance of 200.0
Savings Acct [Owen Bryant] : withdraw 100.00 2
n t 9 S t ud
ai
Savings Acct [Owen Bryant] : deposit 25.00
Savings Acct [Owen Bryant] : withdraw(s175.00th
is
Exception: Insufficient funds RA N us50.0
Deficit:
e
Customer [Bryant, Owen] hasLa
E e tobalance of 125.0
T savings
B en s
O
N le lic
E
M OR ferab
A RO -trans
GEN non

Exceptions and Assertions Lab 8-5


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 2)

Exercise: Creating Your Own Exception (Level 2)


In this exercise, you create an OverdraftException that is thrown by the
withdraw method in the Account class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Creating the OverdraftException Class”
● “Task 2 – Modifying the Account Class”
● “Task 3 – Modifying the CheckingAccount Class”
● “Task 4 – Deleting the Current TestBanking Class”
● “Task 5 – Copying the TestBanking Class”
s a
● “Task 6 – Compiling the TestBanking Class”
) h a
● “Task 7 – Running the TestBanking Program”
c o m

ail eฺ
g m id
Preparation @ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
There is no preparation required for this exercise.

Tool Reference – ToolT R AN usedusinethis exercise:


E L se to
references
B eJava
Java Development:
O n Classes: Creating Java Classes

l i c
R ENDevelopment:
Java

b le Other Files: Deleting Files
O
M Java f r a
eDevelopment:
R O a n

s Java Classes: Modifying Java Classes: Copying Java
A tr Classes
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


d:\labs\student\projects directory.

Lab 8-6 Java™ Programming Language


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 2)

Task 1 – Creating the OverdraftException Class


Complete the following steps:
1. Create the OverdraftException class in the com.mybank.domain
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

source package of the BankPrj project with the following characteristics:


Class Name: OverdraftException
Project: BankPrj
Location: Source Packages
Package: com.mybank.domain
Add code so that OverdraftException extends the Exception class.
2. Add a private instance variable called deficit that holds a double.
s a
3. Add a public constructor that takes two arguments: message and deficit. ) h a
The
o m
ilฺc ฺ
message parameter should be passed to the superclass constructor. The
a
deficit parameter initializes the deficit instance variable.
4. Add a public accessor called getDeficit. @
gm uide
2 1 1 nt G
t 9 20 tude
Task 2 – Modifying the Account a in Class i s S
s h
A N ( use t
L TR theeAccount
In this task, you modify to class source file in the
E s
B en package of the BankPrj project.
com.mybank.domain source
O
N le lic
E
R ratheb following steps:
M OComplete
e
fModify
O n s
R -tra void). This
1. the deposit method so that it does not return a value (that is,
A
GEN non operation should never fail, so it does not need to throw any
exceptions.
2. 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 a new exception that specifies Insufficient
funds and the deficit (the amount requested subtracted by the current
balance).

Exceptions and Assertions Lab 8-7


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 2)

Task 3 – Modifying the CheckingAccount Class


In this task, you modify the CheckingAccount class source file in the
com.mybank.domain source package of the BankPrj project. Modify the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.

Task 4 – Deleting the Current TestBanking Class


In this task, you delete the current TestBanking class in the
s a
com.mybank.test source package of the BankPrj project.
) h a
c o m
il ฺ
Task 5 – Copying the TestBanking Class gma ideฺ
1 1 @ t Gu
In this task, you copy the TestBanking.java 2 0file2 from
u d en
the
d:\labs\student\resources\08_except i 9 St to the
nt idirectory
com.mybank.test source package a th s
(sof theeBankPrj project.
A N us
T R t o
Task 6 – Compiling B EL the n e
sTestBanking Class
O l i c e
R EN ble
MInO
f e a compile the TestBanking class.
this task, ryou

A RO -trans
G EN Task
non 7 – Running the TestBanking Program
In this task, you run the TestBanking program.

The output should be similar to the output listed on page L8-5.

Lab 8-8 Java™ Programming Language


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 3)

Exercise: Creating Your Own Exception (Level 3)


In this exercise, you create an OverdraftException that is thrown by the
withdraw method in the Account class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Creating the OverdraftException Class”
● “Task 2 – Modifying the Account Class”
● “Task 3 – Modifying the CheckingAccount Class”
● “Task 4 – Deleting the Current TestBanking Class”
● “Task 5 – Copying the TestBanking Class”
s a
● “Task 6 – Compiling the TestBanking Class”
) h a
● “Task 7 – Running the TestBanking Program”
c o m

ail eฺ
g m id
Preparation @ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
There is no preparation required for this exercise.

Tool Reference – Tool R AN uused sein this exercise:


E LT se to
references
B en Java Classes: Creating Java Classes
Java Development:
O lic Other Files: Deleting Files

E N Development:
l e
OR fJava b
Java

M e raDevelopment:
R O rans Classes
● Java Classes: Modifying Java Classes: Copying Java
A t
GEN 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


d:\labs\student\projects directory.

Exceptions and Assertions Lab 8-9


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 3)

Task 1 – Creating the OverdraftException Class


Complete the following steps:
1. Create the OverdraftException class in the com.mybank.domain
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

source package of the BankPrj project with the following characteristics:


Class Name: OverdraftException
Project: BankPrj
Location: Source Packages
Package: com.mybank.domain
Add code so that OverdraftException extends the Exception class.

s a
package com.mybank.domain;
) h a
public class OverdraftException extends Exception {
c o m
// insert code here ฺ
ail eฺ
} g m id
@ G u
2. Add a private instance variable called deficit
0 2 11 thate n t a double.
holds
private final double deficit;
n t 9 2
S t ud
i twoisarguments: message and deficit. The
satakes
3. Add a public constructor(that
N e th
message parameterAshould be
T R t o uthespassed to the superclass constructor. The
E L se
deficit parameter initializes deficit instance variable.
O B en msg, double deficit) {
lic
public OverdraftException(String
super(msg); EN l e
OR f=edeficit;
this.deficit
M rab
}
A RO -trans
G EN non 4. Add a public accessor called getDeficit.
public double getDeficit() {
return deficit;
}

Lab 8-10 Java™ Programming Language


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 3)

Task 2 – Modifying the Account Class


In this task, you modify the Account class source file in the
com.mybank.domain source package of the BankPrj project.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Complete the following steps:


1. Modify the deposit method so that it does not return a value (that is,
void). This operation should never fail, so it does not need to throw any
exceptions.
public void deposit(double amt) {
balance = balance + amt;
}
2. Modify the withdraw method so that it does not return a value (that is,
s a
void). Declare that this method throws the OverdraftException.
) h a
o m
Modify the code to throw a new exception that specifies Insufficient
c

ail eฺ
funds and the deficit (the amount requested subtracted by the current
balance). g m id
@ G u
0 2 11 ent {
public void withdraw(double amt) throws OverdraftException
if ( amt <= balance ) {
n t 9 2
S t ud
sai this
balance = balance - amt;
} else { (
R AN use
throw new OverdraftException("Insufficient funds", amt - balance);
T t o
}
B EL nse
}
N O lice
O RE rable
O M 3s–feModifying the CheckingAccount Class
Task
A R -tran
GEN non Using a text editor, modify the CheckingAccount class source file in the
src\com\mybank\domain\ directory. This class must satisfy the UML diagram
in Figure 8-1 on page L8-2.

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.

Exceptions and Assertions Lab 8-11


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 3)

public void withdraw(double amount) throws OverdraftException {


if ( balance < amount ) {
double overdraftNeeded = amount - balance;
if ( overdraftAmount < overdraftNeeded ) {
throw new OverdraftException("Insufficient funds for overdraft
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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 Class
m id
@
1 nt G u
2 1class
In this task, you delete the current TestBanking
t 9 2 0
t u dinethe
com.mybank.test source package of
a inthe BankPrj
i s S project.
s h
A N ( use t
Task 5 – Copying the L TRTestBanking
e to Class
E
B en s
O
Nyou copy c TestBanking.java file from the
lithe
E
In this task, l e
M OR ferab
d:\labs\student\resources\08_except directory to the
R O rans
com.mybank.test source package of the BankPrj project.
A t
G EN non-
Task 6 – Compiling the TestBanking Class
In this task, you compile the TestBanking class.

Task 7 – Running the TestBanking Program


In this task, you run the TestBanking program.

The output should be similar to the output listed on page L8-5.

Lab 8-12 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

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

Exceptions and Assertions Lab 8-13


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 9
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Collections and Generics Framework

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)

Exercise 1: Using Collections to Represent Association


(Level 1)
In this exercise, you use generic collections to represent class associations in the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Bank project domain model.

In your previous design, arrays were used to implement multiplicity in the


relationships between the bank and its customers, and between customers and
their accounts. This design has several significant limitations; the most significant
is that the array, after it is created, has a fixed size. The Collections API was
created to solve this and other limitations.

Figure 9-1 shows the domain model of the Bank project with the class
associations: a bank serves many customers, and a customer has many accounts. s a
Figure 9-1 also shows the detailed design for Bank and Customer classes that ) h a
use a generic List to maintain these links. c o m

ail eฺ
g m id
@ G u
com.mybank.domain
0 2 11 ent
92 Stud
has-aint0..*
sa thisAccount
serves 0..*
Bank Customer
(
R AN use
E LT se to
O B en
E N le lic SavingsAccount CheckingAccount
O R rab
O M sfe
A n
R -traBank
N on Customer
GE-customers
n : 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

Lab 9-2 Java™ Programming Language


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)

This exercise contains the following sections:


● “Task 1 – Modifying the Bank Class”
● “Task 2 – Modifying the Customer Class”
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

● “Task 3 – Compiling the TestReport Class”


● “Task 4 – Running the TestReport Program”

Preparation
There is no preparation for this exercise.

Tool Reference – Tool references used in this exercise:


s a
Java Development: Java Classes: Modifying Java Classes: Compiling

) h a
Java
Classes o m
a ฺc ฺ
ilExecuting

g m ide Java
Java Development: Java Classes: Modifying Java Classes:
Programs
1 1 @ t Gu
2 2 den
0project
t
For this exercise, you work in the BankPrj
i n 9 S tuin the
d:\labs\student\projects
( sa directory.
t h is
R AN use
Task 1 – Modifying E LT the e to Class
Bank
B en s
O
N le lic
E
Rthis task, byou modify the Bank class source file in the com.mybank.domain
M Osource
In
f e r a
O n s package of the BankPrj project. This class must satisfy the UML

N AR n-tradiagram in Figure 9-1 on page L9-2.


GE no
Task 2 – Modifying the Customer Class
In this task, you modify the Customer class source file in the
com.mybank.domain source package of the BankPrj project. This class must
satisfy the UML diagram in Figure 9-1 on page L9-2.

Task 3 – Compiling the TestReport Class


Copy the TestReport.java file from the
d:\labs\student\resources\09_collections directory into the
com.mybank.test source package of the BankPrj project. Compile the
TestReport class.

Collections and Generics Framework Lab 9-3


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)

Task 4 – Running the TestReport Program


In this task, you run the TestReport program. The output should be similar to
the following:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

CUSTOMERS REPORT
================

Customer: Simms, Jane


Savings Account: current balance is 500.0
Checking Account: current balance is 200.0

Customer: Bryant, Owen


Checking Account: current balance is 200.0
s a
Customer: Soley, Tim
) h a
Savings Account: current balance is 1500.0
c o m

ail eฺ
Checking Account: current balance is 200.0
g m id
@ G u
Customer: Soley, Maria
Savings Account: current balance 0 2
is11150.0ent
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

Lab 9-4 Java™ Programming Language


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 2)

Exercise 1: Using Collections to Represent Association


(Level 2)
In this exercise, you use generic collections to represent class associations in the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Bank project domain model.

This exercise contains the following sections:


● “Task 1 – Modifying the Bank Class”
● “Task 2 – Modifying the Customer Class”
● “Task 3 – Compiling the TestReport Class”
● “Task 4 – Running the TestReport Program”
s a
) h a
Preparation c o m

ail eฺ
g m id
@ G u
There is no preparation for this exercise.

0 2 11 ent
Tool Reference – Tool references used in this exercise:
9 2
Java Development: Java Classes: tModifying
n S t ud Classes: Compiling Java
Java
sai this

Classes (
Java Development:R u seModifying Java Classes: Executing Java
N Classes:
AJava ●
Programs LT
E e to
B en s
ForE
O
Nexercise, ic work in the BankPrj project in the
lyou
this
R rab l e
M Od:\labs\student\projects
f e directory.

A RO -trans
GEN noTask
n 1 – Modifying the Bank Class
In this task, you modify the Bank class source file in the com.mybank.domain
source package of the BankPrj project.

Complete the following steps:


1. Modify the declaration for the customers instance variable to be of type
List<Customer>, and drop the numberOfCustomers instance variable.
2. Modify the static block to initialize the customers instance variable to be
a new ArrayList object.
3. Modify the addCustomer method to use the add method.
4. Modify the getCustomer method to use the get method.

Collections and Generics Framework Lab 9-5


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 2)

5. Modify the getNumOfCustomers method to use the size method.

Task 2 – Modifying the Customer Class


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

In this task, you modify the Customer class source file in the
com.mybank.domain source package of the BankPrj project.

Complete the following steps:


1. Modify the declaration for the accounts instance variable to be of type
List<Account>, and drop the numberOfAccounts instance variable.
2. Modify the constructor to initialize the accounts instance variable to be a
new ArrayList object.
s a
3. Modify the addAccount method to use the add method.
) h a
4. c o m
Modify the getAccount method to use the get method.

ail method.
5. Modify the getNumOfAccounts method to use them
g size
i d eฺ
1 1 @ t Gu
2 02 Class
u d en
Task 3 – Compiling the TestReport
i 9
nt is St
a
(s e th
N s the
A fileufrom
Copy the TestReport.java
L seT R t o
d:\labs\student\resources\09_collections directory into the
E
B esource
com.mybank.test n package of the BankPrj project. Compile the
O l i c
EN ble
TestReport
R
class.

M O fera
A ROTask
t r a n4s– Running the TestReport Program
G EN non-
In this task, you run the TestReport program. The output should be similar to
the following:
CUSTOMERS REPORT
================

Customer: Simms, Jane


Savings Account: current balance is 500.0
Checking Account: current balance is 200.0

Customer: Bryant, Owen


Checking Account: current balance is 200.0

Customer: Soley, Tim


Savings Account: current balance is 1500.0

Lab 9-6 Java™ Programming Language


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 2)

Checking Account: current balance is 200.0

Customer: Soley, Maria


Savings Account: current balance is 150.0
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

Collections and Generics Framework Lab 9-7


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 3)

Exercise 1: Using Collections to Represent Association


(Level 3)
In this exercise, you use generic collections to represent class associations in the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Bank project domain model.

This exercise contains the following sections:


● “Task 1 – Modifying the Bank Class”
● “Task 2 – Modifying the Customer Class”
● “Task 3 – Compiling the TestReport Class”
● “Task 4 – Running the TestReport Program”
s a
) h a
Preparation c o m

ail eฺ
g m id
There is no preparation for this exercise. @ G u
0 2 11 ent
9
Tool Reference – Tool references used in tthis 2exercise:tud
a i n i s S
s
( Modifying
Java Development: Java Classes: h
t Java Classes: Compiling Java

A N s e
Classes
L TR e to u
BE eJava
Java Development:

O n sClasses: Modifying Java Classes: Executing Java
N le lic
Programs
E
M OR ferab you work in the BankPrj project in the
For this exercise,
A t ans
RO -d:\labs\student\projects
r directory.

G EN non

Lab 9-8 Java™ Programming Language


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 3)

Task 1 – Modifying the Bank Class


In this task, you modify the Bank class source file in the com.mybank.domain
source package of the BankPrj project.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Complete the following steps:


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;
2. Modify the declaration for the customers instance variable to be of type
List<Customer>, and drop the numberOfCustomers instance variable.
private static List<Customer> customers; s a
) h a
3. m
Modify the static block to initialize the customers instance variable to be
c o
a new ArrayList object. ฺ
ail eฺ
static { g m id
@ G u
customers = new ArrayList<Customer>(10);
0 2 11 ent
}
t 9 2 t d
uadd
a
4. Modify the addCustomer methodi n to use
i s S
the method.
s h
public static void addCustomer(String
A N ( uf, s
t
eString l) {
customers.add(new Customer(f,
L TR e to
l));
}
O BE ens
N lthe
5. Modify
E e ic
lgetCustomer method to use the get method.
ORCustomer
public static
M e r a b getCustomer(int customer_index) {
R O
return sf
customers.get(customer_index);
a n
}A tr
GEN non- 6. Modify the getNumOfCustomers method to use the size method.
public static int getNumOfCustomers() {
return customers.size();
}

Task 2 – Modifying the Customer Class


In this task, you modify the Customer class source file in the
com.mybank.domain source package of the BankPrj project.

Complete the following steps:

Collections and Generics Framework Lab 9-9


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 3)

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ฺ

2. Modify the declaration for the accounts instance variable to be of type


List<Account>, and drop the numberOfAccounts instance variable.
private List<Account> accounts;
3. Modify the constructor to initialize the accounts instance variable to be a
new ArrayList object.
public Customer(String f, String l) {
firstName = f;
lastName = l;
// initialize accounts instance variable
s a
accounts = new ArrayList<Account>(10);
) h a
}
c o m
4. Modify the addAccount method to use the add method. ail ฺ
g m ideฺ
public void addAccount(Account acct) {
1 1 @ t Gu
02 uden
accounts.add(acct);
}
9 2
a i Stmethod.
ntuse theisget
N (s e th
5. Modify the getAccount method to
A
public Account getAccount(int account_index)
R u s {
LT se to
return accounts.get(account_index);
E
}
O B en
E
6. Modify e lic
N the lgetNumOfAccounts method to use the size method.
public int M
R
O fera b
getNumOfAccounts() {
O
R -tran
return s
accounts.size();
} NA
GE non
Task 3 – Compiling the TestReport Class
Copy the TestReport.java file from the
d:\labs\student\resources\09_collections directory into the
com.mybank.test source package of the BankPrj project. Compile the
TestReport class.

Lab 9-10 Java™ Programming Language


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 3)

Task 4 – Running the TestReport Program


In this task, you run the TestReport program. The output should be similar to
the following:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

CUSTOMERS REPORT
================

Customer: Simms, Jane


Savings Account: current balance is 500.0
Checking Account: current balance is 200.0

Customer: Bryant, Owen


Checking Account: current balance is 200.0
s a
Customer: Soley, Tim
) h a
Savings Account: current balance is 1500.0
c o m

ail eฺ
Checking Account: current balance is 200.0
g m id
@ G u
Customer: Soley, Maria
Checking Account: current02 11 eis
balance n t 200.0
n t
Savings Account: current9 S t ud is 150.0
2 balance
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non

Collections and Generics Framework Lab 9-11


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

9 2 t ud
_____________________________________________________________
n t S
( sai this
_____________________________________________________________
Applications RA

N use
E LT se to
B en
_____________________________________________________________
O
E N e lic
_____________________________________________________________
l
M OR fe_____________________________________________________________
rab
A RO -trans
G EN non

Lab 9-12 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Lab 10
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

I/O Fundamentals

There are no exercises for this module.

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Console I/O and File I/O

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)

Exercise 1: Reading a Data File (Level 1)


In this exercise, you create a class that reads customer and account data from a
flat file.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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 File
R -Figure
G EN non
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-1 Data File Format


<number-of-customers>

<first-name> <last-name> <number-of-accounts>


<account-type-code> <datum1> <datum2>

Lab 11-2 Java™ Programming Language


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)

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 overdraft protection of 400.00.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Code 11-2 Example Test Data File


4

Jane Simms 2
S 500.00 0.05
C 200.00 400.00

Owen Bryant 1
s a
C 200.00 0.00
) h a
c o m
Tim Soley 2 ฺ
ail eฺ
S 1500.00 0.05
g m id
C 200.00 0.00 @ G u
0 2 11 ent
Maria Soley 1
n t 9 2
S t ud
S 150.00 0.05
( sai this
This exercise containsR Afollowing e
N ussections:
LT se to
the
E
“Task 1B– Creating n a data Directory”

O l i c e
N 2l–eCopying the Resource File”
R E“Task
rab3 – Creating the DataSource Class”

M O f“Taske
RO -trans “Task 4 – Deleting Unnecessary Classes”

A
EN non

G ● “Task 5 – Copying the TestReport Class”


● “Task 6 – Compiling the TestReport Class”
● “Task 7 – Running the BankPrj Project”

Console I/O and File I/O Lab 11-3


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)

Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Tool references used in this exercise


● Java Development: Other Files: Creating Folders
● Java Development: Java Classes: Modifying Java Classes: Copying Java
Classes
● Java Development: Java Packages: Creating Java Packages
● Java Development: Java Classes: Creating Java Classes
● Java Development: Other Files: Deleting Files
s a
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
) h a
Classes
c o m
Java Development: Java Application Projects: Setting Arguments


ail eฺ
m id
gthe MainuClass
● @
Java Development: Java Application Projects: Setting
1 nt
1Running G
0 2
Java Development: Java Application Projects:

2 deProjects
t 9
n is S t u
sai tproject
For this exercise, you work in the (BankPrj h in the
d:\labs\student\projects N us
A directory. e
T R t o
B EL nse
N
Task 1 – CreatingO laicdata e Directory
E l e
M OR ferab
RO -Tool s
anReference
A t r – Java Development: Other Files: Creating Folders
G EN non
In this project, you create a data directory in the BankPrj project.

Task 2 – Copying the Resource File


In this task, you copy the test.dat file from the
d:\labs\student\resources\11_fileio directory into the data directory.

Lab 11-4 Java™ Programming Language


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)

Task 3 – Creating the DataSource Class


In this task, you create the DataSource class in the com.mybank.data
source package of the BankPrj project with the following characteristics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Class Name: DataSource


Project: BankPrj
Location: Source Packages
Package: com.mybank.data

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. Furthermore,
s a
the Customer class has the addAccount method to add the accounts from the
data file. ) h a
c o m

ail eฺ
g m id
Task 4 – Deleting Unnecessary Classes @ G u
0 2 11 ent
t 9
In this task, you delete the following Java
n S t udare no longer used:
2classes that
( sai this
TestReport
TestAccount RA
N use
E
TestAccount2 LT se to
O B en
TestBatch
E N le lic
TestBanking
M OR ferab
A ROTask
t r a n5s– Copying the TestReport Class
GEN non-
In this task, you copy the TestReport class from the
d:\labs\student\resources\11_fileio directory to the
com.mybank.test source package of the BankPrj project.

Task 6 – Compiling the TestReport Class


In this task, you compile the TestReport class. If there are compilation errors,
make necessary changes to the class and recompile it.

Console I/O and File I/O Lab 11-5


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)

Task 7 – Running the BankPrj Project


In this task, you set the TestReport class as the main class of the BankPrj
project, and run the BankPrj project with an argument data\test.dat.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Java Development: Java Application Projects: Setting


Arguments
1. Set the argument of the BankPrj project to data\test.dat.

Tool Reference – Java Development: Java Application Projects: Setting the Main
Class
2. Set the main class of the BankPrj project to
com.mybank.test.TestReport. s a
) h a
o m
Tool Reference – Java Development: Java Application Projects: Running
c
Projects

ail eฺ
m id following:
gsimilar touthe
@
11 ent
3. Run the BankPrj project. The output should be G
0 2
Reading data file: ..\data\test.dat
CUSTOMERS REPORTint9
2
S tud
(
================sa this
R AN use
Customer: Simms, Jane
E LT se to
B ebalance
Savings Account: current
O n is 500.0
N le
Checking Account: l
currenti c balance is 200.0
E
Customer: M
OR feOwen
rab
ns
Bryant,
A RO -traAccount:
Checking current balance is 200.0
E N n
G no
Customer: Soley, Tim
Savings Account: current balance is 1500.0
Checking Account: current balance is 200.0

Customer: Soley, Maria


Savings Account: current balance is 150.0

Lab 11-6 Java™ Programming Language


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 2)

Exercise 1: Reading a Data File (Level 2)


In this exercise, you create a class that reads customer and account data from a
flat file.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Creating a data Directory”
● “Task 2 – Copying the Resource File”
● “Task 3 – Creating the DataSource Class”
● “Task 4 – Deleting Unnecessary Classes”
● “Task 5 – Copying the TestReport Class”
s a
● “Task 6 – Compiling the TestReport Class”
) h a
● “Task 7 – Running the BankPrj Project”
c o m

ail eฺ
g m id
Preparation @ G u
0 2 11 ent
n t 9 2
S t ud
sai this
There is no preparation for this exercise.
(
Tool Reference – Tool R AN uused sein this exercise:
E LT se to
references
B en Other Files: Creating Folders
Java Development:
O lic Java Classes: Modifying Java Classes: Copying Java

E N Development:
l e
OR fClasses
rab
Java

M e
A RO -trans Java Development: Java Packages: Creating Java Packages

GEN non Java Development: Java Classes: Creating Java Classes


● Java Development: Other Files: Deleting Files


● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Application Projects: Setting Arguments
● Java Development: Java Application Projects: Setting the Main Class
● Java Development: Java Application Projects: Running Projects

For this exercise, you work in the BankPrj project in the


d:\labs\student\projects directory.

Console I/O and File I/O Lab 11-7


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 2)

Task 1 – Creating a data Directory


In this project, you create a data directory in the BankPrj project.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 2 – Copying the Resource File


In this task, you copy the test.dat file from the
d:\labs\student\resources\11_fileio directory into the data
directory.

Task 3 – Creating the DataSource Class


s a
Complete the following steps: ) h a
c o m
1. ฺ
ail eฺ
Create the DataSource class in the com.mybank.data source
g m id
package of the BankPrj project with the following characteristics:
@ G u
Class Name: DataSource
0 2 11 ent
Project: BankPrj
n t 9 2
S t ud
Location: Source Packages ( sai this
R AN use
Package: com.mybank.data
E LT instance
e to
s
B en variable to the DataSource class.
2. Add the dataFile
O lic
Na publicleconstructor
3. Add
R E b that takes a string argument dataFilePath and
M f e ra the dataFile instance variable.
O initializes
s a public method, loadData, that populates the Bank customer objects
RO -t4.ranAdd
A
G EN non and each customer’s account objects. Here is the pseudo-code for this
method:
read <number-of-customers>
for each customer record
read <first-name> and <last-name>
add customer to Bank
read <number-of-accounts>
for each account
read <account-type-code>
switch on <account-type-code>
Savings:
read <initial-balance> and <interest-rate)
create account and add account to customer
Checking:
read <initial-balance> and <overdraft-amount)

Lab 11-8 Java™ Programming Language


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 2)

create account and add account to customer

Task 4 – Deleting Unnecessary Classes


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

In this task, you delete the following Java classes that are no longer used:
TestReport
TestAccount
TestAccount2
TestBatch
TestBanking

Task 5 – Copying the TestReport Class a


h a s
m )
In this task, you copy the TestReport class from the
ฺ c o
d:\labs\student\resources\11_fileio directory to the
m ail eฺ
g
com.mybank.test source package of the BankPrj project.
@ u id
11 ent G
0 2
Task 6 – Compiling the TestReport n t 9 2 Class
S t ud
( sai this
R
In this task, you compile u se class. If there are compilation errors,
AtheNTestReport
LT stoethetoclass and recompile it.
make necessaryEchanges
O B en
E N le lic
M OR
Task a
7 – eRunning
f r b the BankPrj Project
A RO -trans
GEN non In this task, you set the TestReport class as the main class of the BankPrj
project, and run the BankPrj project with an argument data\test.dat.

Tool Reference – Java Development: Java Application Projects: Setting


Arguments
1. Set the argument of the BankPrj project to data\test.dat.

Tool Reference – Java Development: Java Application Projects: Setting the Main
Class
2. Set the main class of the BankPrj project to
com.mybank.test.TestReport.

Console I/O and File I/O Lab 11-9


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 2)

Tool Reference – Java Development: Java Application Projects: Running


Projects
3. Run the BankPrj project. The output should be similar to the following:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Reading data file: ..\data\test.dat


CUSTOMERS REPORT
================

Customer: Simms, Jane


Savings Account: current balance is 500.0
Checking Account: current balance is 200.0

Customer: Bryant, Owen


Checking Account: current balance is 200.0
s a
Customer: Soley, Tim ) h a
c o m
Savings Account: current balance is 1500.0 ฺ
ail eฺ
Checking Account: current balance is 200.0
g m id
@ G u
Customer: Soley, Maria
0 2 11 ent
Savings Account: current balance is 150.0 92
n t 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
N on
GE n

Lab 11-10 Java™ Programming Language


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 3)

Exercise 1: Reading a Data File (Level 3)


In this exercise, you create a class that reads customer and account data from a
flat file.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Creating a data Directory”
● “Task 2 – Copying the Resource File”
● “Task 3 – Creating the DataSource Class”
● “Task 4 – Deleting Unnecessary Classes”
● “Task 5 – Copying the TestReport Class”
s a
● “Task 6 – Compiling the TestReport Class”
) h a
● “Task 7 – Running the BankPrj Project”
c o m

ail eฺ
g m id
Preparation @ G u
0 2 11 ent
n t 9 2
S t ud
sai this
There is no preparation for this exercise.
(
Tool Reference – Tool R AN uused sein this exercise:
E LT se to
references
B en Other Files: Creating Folders
Java Development:
O lic Java Classes: Modifying Java Classes: Copying Java

E N Development:
l e
OR fClasses
rab
Java

M e
A RO -trans Java Development: Java Packages: Creating Java Packages

GEN non Java Development: Java Classes: Creating Java Classes


● Java Development: Other Files: Deleting Files


● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Application Projects: Setting Arguments
● Java Development: Java Application Projects: Setting the Main Class
● Java Development: Java Application Projects: Running Projects

For this exercise, you work in the BankPrj project in the


d:\labs\student\projects directory.

Console I/O and File I/O Lab 11-11


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 3)

Task 1 – Creating a data Directory


Create a data directory in the BankPrj project.
1. With the BankPrj project open, click the Files tab.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2. Right-click BankPrj in the file tree.


3. Select New -> Other.
4. Select Other in the Categories pane.
5. Select Folder in the File Types pane.
6. Click Next.
7. Enter data for the folder name.
8. Click Finish. s a
) h a
c o m
Task 2 – Copying the Resource File ฺ
ail eฺ
g m id
@ G u
11 ent
In this task, you copy the test.dat file from2the
0
d:\labs\student\resources\11_fileio
n t 9 S t ud into the data directory.
2 directory
( sai this
Task 3 – Creating the
R se
ANDataSource
u Class
L T e to
O BE ens
Complete
E lic steps:
N thelefollowing
M OR e r
1. Createa bthe DataSource class in the com.mybank.data source
R O ransf package of the BankPrj project with the following characteristics:
A t
G EN non- Class Name: DataSource
Project: BankPrj
Location: Source Packages
Package: com.mybank.data
package com.mybank.data;
// insert import statements here
public class DataSource {
// insert code here
}
2. Add an import statement to import necessary class names:
import com.mybank.domain.*;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

Lab 11-12 Java™ Programming Language


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 3)

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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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

Console I/O and File I/O Lab 11-13


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 3)

5. Add a public method, loadData, that populates the Bank customer objects
and each customer’s account objects, shown as follows:
public void loadData() throws IOException {
// Data source variables
Scanner input = new Scanner(dataFile);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

// 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’: {

G EN non float initBalance = input.nextFloat();


float overdraftProtection = input.nextFloat();
customer.addAccount(new CheckingAccount(initBalance,
overdraftProtection));
break;
}
} // END of switch
} // END of create accounts loop
} // END of create customers loop
}

Lab 11-14 Java™ Programming Language


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 3)

Task 4 – Deleting Unnecessary Classes


In this task, you delete the following Java classes that are no longer used:
TestReport
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

TestAccount
TestAccount2
TestBatch
TestBanking

Task 5 – Copying the TestReport Class


In this task, you copy the TestReport class from the
s a
d:\labs\student\resources\11_fileio directory to the
com.mybank.test source package of the BankPrj project. ) h a
c o m

ail eฺ
Task 6 – Compiling the TestReport Class g m id
@ G u
0 2 11 ent
In this task, you compile the TestReportt 9 d are compilation errors,
2 class. Iftuthere
n S
sai and trecompile
make necessary changes to the class
( h is it.
R AN use
Task 7 – Running E to
LTtheseBankPrj Project
B e n
E NO le lic
Rthis task,
Oproject,
In
r a byou set the TestReport class as the main class of the BankPrj
O M s f e and run the BankPrj project with an argument data\test.dat.
AR n-tra n
E N
G no Tool Reference – Java Development: Java Application Projects: Setting
Arguments
1. Set the argument of the BankPrj project to data\test.dat.

Tool Reference – Java Development: Java Application Projects: Setting the Main
Class
2. Set the main class of the BankPrj project to
com.mybank.test.TestReport.

Tool Reference – Java Development: Java Application Projects: Running


Projects
3. Run the BankPrj project. The output should be similar to the following:
Reading data file: ..\data\test.dat

Console I/O and File I/O Lab 11-15


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 3)

CUSTOMERS REPORT
================

Customer: Simms, Jane


Savings Account: current balance is 500.0
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Checking Account: current balance is 200.0

Customer: Bryant, Owen


Checking Account: current balance is 200.0

Customer: Soley, Tim


Savings Account: current balance is 1500.0
Checking Account: current balance is 200.0

Customer: Soley, Maria


s a
Savings Account: current balance is 150.0
) 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

Lab 11-16 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

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

Console I/O and File I/O Lab 11-17


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 12
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Building Java GUIs Using the Swing API

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)

Exercise 1: Creating the ChatClient GUI Part 1 (Level 1)


In this exercise, you create a GUI for a chat room application. You use a complex
layout to position properly several GUI components in a frame.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Figure 12-1 shows the GUI design that you will attempt to achieve.

The JTextArea Component Send Button Component

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.

This exercise contains the following sections:


● “Task 1 – Creating the ChatClient Class”
● “Task 2 – Compiling the ChatClient Class”
● “Task 3 – Running the ChatClient Program”
● “Task 4 – Terminating the Running ChatClient Program”

Lab 12-2 Java™ Programming Language


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)

Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Tool references used in this exercise:


● Java Development: Java Application Projects: Creating Projects
● Java Development: Java Classes: Creating Java Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs
Java Development: Java Classes: Terminating a Running Process s a

) h a
c o m

For this exercise, you first create the ChatRoomPrj project in the
ail eฺ
d:\labs\student\projects directory, and then work in this project for all
g m id
@ u
the following exercises that are part of the ChatRoomPrj project.
G
0 2 11 ent
n t 9 2
S t ud
Task 1 – Creating the ChatClient
( sai this Class
R AN u se class in the source package of the
E LT implement
In this task, you create the to the GUI design in Figure 12-1 on page 12-2.
ChatClient
e
ChatRoomPrj
B enproject s
O lic steps:
N thelfollowing
E e
M OR ferab
Complete

R O ra1.ns Create the ChatRoomPrj Java Application Project with the following
A t
EN non-
characteristics:
G Project Name: ChatRoomPrj
Project Location: d:\labs\student\projects
Project Folder: d:\labs\student\projects\ChatRoomPrj
Set as Main Project: No
Create Main Class: No
2. Create the ChatClient class in the source package of the
ChatRoomPrj project with the following characteristics:
Class Name: ChatClient
Project: ChatRoomPrj
Location: Source Packages
Package: default package

Building Java GUIs Using the Swing API Lab 12-3


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)

The ChatClient class must implement the GUI design in Figure 12-1 on
page 12-2.

Task 2 – Compiling the ChatClient Class


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

In this task, you compile the ChatClient class.

Task 3 – Running the ChatClient Program


In this task, you run the ChatClient program. You should see the GUI shown in
Figure 12-1 on page 12-2. If your GUI does not look exactly like the figure, then
edit the code to tweak the design to match this figure.
s a
) h a
Task 4 – Terminating the Running ChatClient ilฺco
m
a ฺ
Program gm ide @ t Gu
1 1
Terminate the running ChatClient program.
9 2 02 uden
a i nt is St
1. Close the ChatClient program.
N (s e th
T t o usChatClient window to stop the process
2. Press the stop buttonRinAthe output
running.
B EL nse
N O lice
O RE rable
O M sfe
A R -tran
N on
GE n

Lab 12-4 Java™ Programming Language


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 2)

Exercise 1: Creating the ChatClient GUI Part 1 (Level 2)


In this exercise, you create a GUI for a chat room application. You use a complex
layout to properly position several GUI components in a frame.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Creating the ChatClient Class”
● “Task 2 – Compiling the ChatClient Class”
● “Task 3 – Running the ChatClient Program”
● “Task 4 – Terminating the Running ChatClient Program”

s a
Preparation
) h a
c o m
There is no preparation for this exercise. ฺ
ail eฺ
g m id
@ G u
11 ent
Tool Reference – Tool references used in this2exercise:
0
t 9 d Projects
2Projects:tuCreating
n
Java Development: Java Application S
sai Creating

( t h is Java Classes

N use
Java Development: Java Classes:
AJava
Java Development:

L R
T e tClasses:o Modifying Java Classes: Compiling Java
ClassesBE n s
O e
lic Java Classes: Modifying Java Classes: Executing Java
N Development:
E Java

l e
M OR fPrograms
e rab
A RO -trans Java Development: Java Classes: Terminating a Running Process

GEN non For this exercise, you first create the ChatRoomPrj project in the
d:\labs\student\projects directory, and then work in this project for all
the following exercises that are part of the ChatRoomPrj project.

Task 1 – Creating the ChatClient Class


In this task, you create the ChatClient class in the source package of the
ChatRoomPrj project implement the GUI design in Figure 12-1 on page 12-2.

Complete the following steps:


1. Create the ChatRoomPrj Java Application Project with the following
characteristics:

Building Java GUIs Using the Swing API Lab 12-5


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 2)

Project Name: ChatRoomPrj


Project Location: d:\labs\student\projects
Project Folder: d:\labs\student\projects\ChatRoomPrj
Set as Main Project: No
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Create Main Class: No


2. Create the ChatClient class with the following characteristics:
Class Name: ChatClient
Project: ChatRoomPrj
Location: Source Packages
Package: default package
3. Add four instance variables to the ChatClient class to hold the GUI s a
components. ) h a
c o m
4. ฺ
ail eฺ
Add a public constructor that initializes each of the four GUI component
g m id
instance variables: The text area should be 10 rows tall and 50 columns
@ G u
0 2 11 ent
wide, the text field should be 50 columns wide, the send button should have
the word Send in the display, and the quit button should display a similar
label.
n t 9 2
S t ud
i
sathat is the layout of the
5. Create a launchFrame method ( t h
constructs
N usepanels and any layout managers that
R
components. Feel free A
to use nested
will help you construct
E to in the GUI design shown above.
LT sthee layout
6. Create O
B en This method instantiates a new ChatClient
c
the mainlimethod.
Nand then
E
R rab
object l e calls the launchFrame method.
O
M sfe
O
RTask-t2ra–nCompiling the ChatClient Class
A
G EN non
In this task, you compile the ChatClient class.

Task 3 – Running the ChatClient Program


In this task, you run the ChatClient program. You should see the GUI shown in
Figure 12-1 on page 12-2. If your GUI does not look exactly like the figure, then
edit the code to tweak the design to match this figure.

Lab 12-6 Java™ Programming Language


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 2)

Task 4 – Terminating the Running ChatClient


Program
Terminate the running ChatClient program.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1. Close the ChatClient program.


2. Press the stop button in the output ChatClient window to stop the process
running.

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

Building Java GUIs Using the Swing API Lab 12-7


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 3)

Exercise 1: Creating the ChatClient GUI Part 1 (Level 3)


In this exercise, you create a GUI for a chat room application. You use a complex
layout to properly position several GUI components in a frame.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Creating the ChatClient Class”
● “Task 2 – Compiling the ChatClient Class”
● “Task 3 – Running the ChatClient Program”
● “Task 4 – Terminating the Running ChatClient Program”

s a
Preparation
) 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 exercise:
0 2 11 ent
Java Development: Java Application n t 9 2 Creating
Projects: S t ud Projects

i
saCreating s Classes
iJava
(
N use
Java Development: Java Classes:
● t h
R AClasses:
Java Development:

L T e to Modifying Java Classes: Compiling Java
Java
Classes BE n s
O e
lic Java Classes: Modifying Java Classes: Executing Java
NDevelopment:
E
Java

l e
M ORPrograms
e r a b
R sf Development: Java Classes: Terminating a Running Process
O ranJava●
A t
G EN non- For this exercise, you first create the ChatRoomPrj project in the
d:\labs\student\projects directory, and then work in this project for all
the following exercises that are part of the ChatRoomPrj project.

Task 1 – Creating the ChatClient Class


In this task, you create the ChatClient class in the source package of the
ChatRoomPrj project implement the GUI design in Figure 12-1 on page 12-2.

Complete the following steps:


1. Create the ChatRoomPrj Java Application Project with the following
characteristics:

Lab 12-8 Java™ Programming Language


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 3)

Project Name: ChatRoomPrj


Project Location: d:\labs\student\projects
Project Folder: d:\labs\student\projects\ChatRoomPrj
Set as Main Project: No
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Create Main Class: No


2. Create the ChatClient class with the following characteristics:
Class Name: ChatClient
Project: ChatRoomPrj
Location: Source Packages
Package: default package
3. Import the java.awt and javax.swing packages. s a
) h a
import java.awt.*;
c o m
import javax.swing.*; ฺ
ail eฺ
public class ChatClient {
g m id
// insert code here @ G u
}
0 2 11 ent
n
4. Add four instance variables to the t 9 2
S t udclass to hold the GUI
sai this
ChatClient
components. (
N use
private JTextArea output; RA
private JTextField input;LT
E e to
B en
private JButton sendButton; s
O
N le lic
private JButtonEquitButton;

M O5.R fAdd
e raabpublic constructor that initializes each of the four GUI component
A RO -trans instance variables: The text area should be 10 rows tall and 50 columns

GEN non wide, the text field should be 50 columns wide, the send button should have
the word Send in the display, and the quit button should display a similar
label.
public ChatClient() {
output = new JTextArea(10,50);
input = new JTextField(50);
sendButton = new JButton("Send");
quitButton = new JButton("Quit");
}
6. Create a launchFrame method, which constructs the layout of the
components. Feel free to use nested panels and any layout managers that
will help you construct the layout in the GUI design shown above.
public void launchFrame() {
JFrame frame = new JFrame("Chat Room");

// Use the Border Layout for the frame


frame.setLayout(new BorderLayout());

Building Java GUIs Using the Swing API Lab 12-9


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 3)

frame.add(output, BorderLayout.WEST);
frame.add(input, BorderLayout.SOUTH);

// Create the button panel


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

JPanel p1 = new JPanel();


p1.setLayout(new GridLayout(2,1));
p1.add(sendButton);
p1.add(quitButton);

// Add the button panel to the center


frame.add(p1, BorderLayout.CENTER);

frame.pack();
frame.setVisible(true);
s a
}
) h a
7. o m
Create the main method. This method instantiates a new ChatClient
c

ail eฺ
object and then calls the launchFrame method.
g m id
public static void main(String[] args) { @ G u
ChatClient c = new ChatClient();
0 2 11 ent
c.launchFrame();
n t 9 2
S t ud
}
( sai this
R AN use
Task 2 – Compiling E e to
LTthesChatClient Class
B
O lice n
N
E youbcompile
le the ChatClient class.
O Rtask,
In this
a
O M sfer
A RTask-t3ra–nRunning the ChatClient Program
N on
GE n
In this task, you run the ChatClient program. You should see the GUI shown in
Figure 12-1 on page 12-2. If your GUI does not look exactly like the figure, then
edit the code to tweak the design to match this figure.

Lab 12-10 Java™ Programming Language


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 3)

Task 4 – Terminating the Running ChatClient


Program
Terminate the running ChatClient program.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1. Close the ChatClient program.


2. Press the stop button in the output ChatClient window to stop the process
running.

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

Building Java GUIs Using the Swing API Lab 12-11


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating the Bank ATM GUI Part 1 (Advanced)

Exercise 2: Creating the Bank ATM GUI Part 1


(Advanced)
In this exercise, you create an automated teller machine (ATM) GUI for the Bank
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

project. You use a complex layout to properly position several GUI components
in a frame.

Note – This is an advanced exercise. It is optional and should only be attempted


if you have already completed the previous exercise for this module.

Figure 12-2 shows the GUI design that you will attempt to achieve.

Action Button Panel s a


Output JTextArea Component
) 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
R O raData
n s Entry JTextField Component
A Paneln-t
NPad
E
Key
G no
Message JTextField Component

Figure 12-2 GUI Layout for the Bank Project

This exercise contains the following sections:


● “Task 1 – Copying the ATMClient Class”
● “Task 2 – Modifying the ATMClient Class”
● “Task 3 – Compiling the ATMClient Class”
● “Task 4 – Running the ATMClient Program”

Lab 12-12 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating the Bank ATM GUI Part 1 (Advanced)

Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Tool references used in this exercise:


● Java Development: Java Packages: Creating Java Packages
● Java Development: Java Classes: Modifying Java Classes: Copying Java
Classes
● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Application Projects: Setting the Main Class
Java Development: Java Application Projects: Running Projects s a

) h a
c o m
For this exercise, you work in the BankPrj project in the
d:\labs\student\projects directory.

ail eฺ
g m id
@ G u
0 2 11 ent
Task 1 – Copying the ATMClient
n t 9 2 Class
S t ud
( s ai this
AN use
Complete the following steps:
R
LT se to source package in the BankPrj project.
1. Create the com.mybank.gui
E
O B en
2. Copy
E N e l ic
the ATMClient.java template file from the

O r a bl
R d:\labs\student\resources\12_gui directory into the

O M sfe com.mybank.gui source package of the BankPrj project. This template

A R -tran code provides the main method, which initializes a set of bank customers
GEN non and then launches the ATM GUI.

Building Java GUIs Using the Swing API Lab 12-13


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating the Bank ATM GUI Part 1 (Advanced)

Task 2 – Modifying the ATMClient Class


In this task, you modify the ATMClient to implement the ATM GUI screen,
shown in Figure 12-2 on page 12-12. The GUI components must have the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

following characteristics:
● The Message text field must have a width of 75 characters (called columns
in the API documentation) and it must be read-only, meaning the user
cannot type into the field.
● The Data Entry text field must have a width of 10 characters and it must be
read-only. The user will use the key pad buttons to enter data which will be
displayed in the Data Entry field. This action will be coded in the next
module.
● The Output text area must have a width of 75 characters and a height (called
s a
rows in the API) of 10 characters and it must be read-only.
) h a
c o m

ail screen.
Note – In this exercise, you will only be creating the layoutgofmthe ATM i d eฺ
1 @ totuser
You will not be creating the code to make the buttons respond G uactions; you
will do that in the next module.
1
02 uden
9 2
a i nt is St
N (s e th
Task 3 – Compiling Tthe R t o us
AATMClient Class
L
E nse
B
N
In this task, O l i
you compile cethe 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.

Lab 12-14 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating the Bank ATM GUI Part 1 (Advanced)

Hints
These hints might help you to solve this exercise.
● Use the setEnabled(false) method to make a component read-only.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

● 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

Building Java GUIs Using the Swing API Lab 12-15


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

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 12-16 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Lab 13
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Handling GUI-Generated Events

Objectives
Upon completion of this lab, you should be able to:
● Create the GUI event handlers for the ChatRoom project s a
(Optional) Create the GUI event handlers 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 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)

Exercise 1: Creating the ChatClient GUI Part 2 (Level 1)


In this exercise, you implement the basic event handlers for the chat room
application. At this stage in the development of the ChatClient GUI, you need
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

to create the following event listeners:


● Create an ActionListener that copies the text from the input text field
into the output text area when the send button is pressed.
● Create an ActionListener that copies the text from the input text field
into the output text area when the Enter key is pressed in the input text
field.
● Create an ActionListener that will quit the program when the Quit
button is pressed. (Hint – Use System.exit(0).)
s a
● Create a WindowListener that will quit the program when the close
) h a
widget is pressed on the frame.
c o m

ail eฺ
This exercise contains the following sections:
g m id
@ G u
“Task 1 – Modifying the ChatClient Class” 11 n t

0 2 e
“Task 2 – Compiling the ChatClient

n t 9 2
Class”
S t ud
“Task 3 – Running the ChatClient
● ( sai Program”
t h is
R AN use
E LT se to
Preparation B e n
O l i c
R EN ble
MThere a
O is fnoerpreparation for this exercise.

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


d:\labs\student\projects directory.

Lab 13-2 Java™ Programming Language


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)

Task 1 – Modifying the ChatClient Class


In this task, you modify the ChatClient class in the source package of the
ChatRoomPrj project. This class must implement event listeners listed in the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

introduction to this exercise.

Task 2 – Compiling the ChatClient Class


In this task, you compile the ChatClient class.

Task 3 – Running the ChatClient Program


a
In this task, you run the ChatClient program. Test the behavior of the )event has
listeners you added. c o m

ail eฺ
g m id
@ G u
Hints
0 2 11 ent
n t 9 2
S t ud
s i this
Use the following hints during thisaexercise:
(
AN classes)
Have the listeners (inner

R u seaccess the instance variables of their
LT to refer
containing class
E e ttoothe components like the output text area and the
input text n s
B field.eRemember that you made the components instance
O l i c
N lein the previous lab.
R Evariables
M O fRemember
e
● rab to import the java.awt.event package.
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.

Handling GUI-Generated Events Lab 13-3


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 2)

Exercise 1: Creating the ChatClient GUI Part 2 (Level 2)


In this exercise, you implement the basic event handlers for the chat room
application. At this stage in the development of the ChatClient GUI, you need
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

to create the event listeners listed in ‘‘Exercise 1: Creating the ChatClient GUI
Part 2 (Level 1)’’ on page L13-2.

This exercise contains the following sections:


● “Task 1 – Modifying the ChatClient Class”
● “Task 2 – Compiling the ChatClient Class”
● “Task 3 – Running the ChatClient Program”

s a
Preparation ) h a
c o m

ail eฺ
There is no preparation for this exercise.
g m id
@ G u
0
Tool Reference – Tool references used in this exercise: 2 11 ent
n t 9 2
S t ud

s i
Java Development: Java Classes:aModifying i sJava Classes: Compiling Java
( t h
AN use
Classes
R to Modifying Java Classes: Executing Java
LTJavasClasses:
Java Development:

Programs BE n e
O
N le l i c e
R Eexercise,
M O ferab you work in the ChatRoomPrj
For this project in the

RO -trans
d:\labs\student\projects directory.
A
G EN non
Task 1 – Modifying the ChatClient Class
In this task, you modify the ChatClient class in the source package of the
ChatRoomPrj project. This class must implement event listeners listed in the
introduction to ‘‘Exercise 1: Creating the ChatClient GUI Part 2 (Level 1)’’ on
page L13-2.

Lab 13-4 Java™ Programming Language


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 2)

Complete the following steps:


1. Import the java.awt.event package.
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

class for this listener.


3. Add the ActionListener for the text field. Can you use the same listener
in Step 2?
4. Add the WindowListener to the GUI frame. This listener must exit the
ChatClient program. Use an inner class for this listener.
5. Add the ActionListener for the Quit button. This listener must exit the
ChatClient program. Use an anonymous inner class for this listener.

s a
Task 2 – Compiling the ChatClient Class ) h a
c o m

ail eฺ
In this task, you compile the ChatClient class.
g m id
@ G u
0 2 11 ent
Task 3 – Running the ChatClient
n t 9 S t ud
2 Program
( sai this
In this task, you run the A N useprogram. Test the behavior of the event
ChatClient
R
LT se to
listeners you added.
E
B en
O
N le lic
E
M OR ferab
A RO -trans
GEN non

Handling GUI-Generated Events Lab 13-5


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 3)

Exercise 1: Creating the ChatClient GUI Part 2 (Level 3)


In this exercise, you implement the basic event handlers for the chat room
application. At this stage in the development of the ChatClient GUI, you need
to create the event listeners listed in ‘‘Exercise 1: Creating the ChatClient GUI
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Part 2 (Level 1)’’ on page L13-2.

This exercise contains the following sections:


● “Task 1 – Modifying the ChatClient Class”
● “Task 2 – Compiling the ChatClient Class”
● “Task 3 – Running the ChatClient Program”

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:
Java Development: Java Classes:t9
n
2
S
Modifying t ud Classes: Compiling Java
Java
sai this

Classes (
R
Java Development:

N Classes:
AJava u seModifying Java Classes: Executing Java
Programs LT
E e to
B en s
O
N exercise,
ForEthis
c work in the ChatRoomPrj project in the
liyou
R rab l e
M Od:\labs\student\projects
f e directory.

A RO -trans
G EN noTask
n 1 – Modifying the ChatClient Class
In this task, you modify the ChatClient class in the source package of the
ChatRoomPrj project. This class must implement event listeners listed in the
introduction to ‘‘Exercise 1: Creating the ChatClient GUI Part 2 (Level 1)’’ on
page L13-2.
1. Import the java.awt.event package.
import java.awt.event.*;
public class ChatClient {
// your code here
}
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() {

Lab 13-6 Java™ Programming Language


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 3)

// GUI component initalization code here


sendButton.addActionListener(new SendHandler());
// more code
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

private class SendHandler implements ActionListener {


public void actionPerformed(ActionEvent e) {
String text = input.getText();
output.setText(output.getText()+text+"\n");
input.setText("");
}
}
3. Add the ActionListener for the text field. Can you use the same listener
in Step 2?
s a
private void launchFrame() {
) h a
// GUI component initalization code here
c o m
input.addActionListener(new SendHandler()); ฺ
ail eฺ
// more code
g m id
} @ G u
In this solution, the SendHandler inner 0 2 11 wasereused
class n t to reduce
redundant code. n t 9 2
S t ud
4. Add the WindowListener ( satoithe GUI
t h isframe. This listener must exit the
e class for this listener.
ANUse uansinner
R
ChatClient program.
LT{ se to
private void launchFrame()E
B en code here
// GUI componentO
E N le lic
initalization

O R
frame.addWindowListener(new
a b CloseHandler());
Mcodesfer
// more
O
}
A R -tran
GENprivate
nonclass CloseHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}

Handling GUI-Generated Events Lab 13-7


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 3)

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
quitButton.addActionListener(new ActionListener() {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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. How could
you have satisfied both listener interfaces using the CloseHandler class?
s a
) h a
Task 2 – Compiling the ChatClient Class c o m

ail eฺ
g m id
@ G u
In this task, you compile the ChatClient class.
0 2 11 ent
n t 9 2
S t ud
Task 3 – Running the ChatClient ( sai thProgram
is
R AN use
E
In this task, you run the e to program. Test the behavior of the event
LTChatClient
B en
listeners you added. s
O
N le lic
E
M OR ferab
A RO -trans
G EN non

Lab 13-8 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating the Bank ATM GUI Part 2 (Advanced)

Exercise 2: Creating the Bank ATM GUI Part 2


(Advanced)
In this exercise, you modify the ATMClient class in the BankPrj project by
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

adding necessary event handling capabilities.

Note – This is an advanced exercise. It is optional and should only be attempted


if you have already completed the previous exercise for this module.

The simulated ATM must behave in this manner:


1. The ATM screen is displayed.
s a
At this stage, the Action buttons must be disabled and the following text
) h a
c o m
must be displayed in the Output text area: Enter your customer ID
into the key pad and press the ENTER button.
a il ฺ ฺ
2. The user enters the ID using the key pad buttons. Each g m number i disedisplayed
in the Data Entry text field. 1 1 @ t Gu
2 2 den
0application
When the ENTER button is selected,
n t 9 the
S t u retrieves the specified
customer object and displaysathe
s i following
i s text in the Output text area:
Welcome FIRST-NAME (
N text
LAST-NAME t h
e if theCustomer
customer was found;
A
R to
otherwise, the following u s
is displayed: ID was not
L T
E ifnthe
found. Finally,
B e secustomer was found, then the Action buttons are
E NO le lic
enabled.

M O3.R fThe
e
b selects one of the Action buttons.
rauser
A RO -trans Ifthetheamount.
action is either deposit or withdraw, then the user is prompted to enter

EN non
The user can then enter the amount by clicking the key pad
G buttons which (again) places digits in the Data Entry text field. When the
ENTER button is selected, the program executes the action with the amount
entered in the Data Entry text field. Finally, the result of the operation must
be displayed in the Output text area. At the end of the operation, the GUI
should begin again at the top of the ATM operation cycle.

This exercise contains the following sections:


● “Task 1 – Modifying the ATMClient Class”
● “Task 2 – Compiling the ATMClient Class”
● “Task 3 – Running the BankPrj Project”

Handling GUI-Generated Events Lab 13-9


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating the Bank ATM GUI Part 2 (Advanced)

Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Tool references used in this exercise


● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Development: Java Application Projects: Running Projects

For this exercise, you work in the BankPrj project in the


d:\labs\student\projects directory.

s a
Task 1 – Modifying the ATMClient Class ) h a
c o m

ail of theeฺ
In this task, you modify the ATMClient class in the source package
g m toid
@
BankPrj project. This class must rely on necessary event listeners
G u
implemented the required behavior.
0 2 11 ent
n t 9 2
S t ud
Task 2 – Compiling the ATMClient ( sai thiClasss
R AN use
T e to class.
In this task, you B EL thensATMClient
compile
N O lice
R E ble
O
TaskM3 – Running
f e ra the BankPrj Project
O
R -tran s
A
G EN non In this task, you run the BankPrj project.

Lab 13-10 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 2: Creating the Bank ATM GUI Part 2 (Advanced)

The following is an example ATM transaction for Owen Bryant:


Enter your customer ID into the key pad and press the ENTER button.
Welcome Owen Bryant
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Your account balance is: 200.0


Enter the amount to deposit into the key pad and press the ENTER button.
Your deposit of 100.0 was successful.
Your account balance is: 300.0
Enter the amount to withdraw into the key pad and press the ENTER button.
Your withdrawal of 250.0 was successful.
Your account balance is: 50.0

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

Handling GUI-Generated Events Lab 13-11


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

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-12 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Lab 14
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

GUI-Based Applications

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)

Exercise: Creating the ChatClient GUI, Part 3 (Level 1)


In this exercise, you enhance the GUI for a chat room application. You complete
the GUI for the ChatClient by adding a JComboBox component, a
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

JScrollPane component, and two menus.

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
Figure 14-1 GUI Layout for the ChatClient Application @ G u
0 2 11 ent
n t 9 2
S t ud
( s ai this
You need to add four features to the existing GUI:
Add the user name JComboBox

A s e under the Send and Quit
N ucomponent
R enables
Tyou
buttons. This component
L t o you to select a name that is posted with
B that e
E ns You must alter the Send button and
every chat line enter.
O listeners
JTextField
N l i ce to write the username to the output JTextArea
E blAdd
Rcomponent. e several user name options including your full name and a
O
M few f r a
enicknames, such as 1337dud3 or Java Geek.
O s
R -tranPut the JTextArea component into a JScrollPane component. Add a
A ●

G EN non 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.

This exercise contains the following sections:


● “Task 1 – Modifying the ChatClient Class”
● “Task 2 – Compiling the ChatClient Class”
● “Task 3 – Running the ChatClient Program”

Lab 14-2 Java™ Programming Language


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)

Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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


d:\labs\student\projects directory.
s a
) h a
Task 1 – Modifying the ChatClient Class c o m

ail eฺ
m
g package id of the
@
In this task, you modify the ChatClient class in the source
G u
ChatRoomPrj project. This class must implement
0 2 11 theeGUI
n t design in
Figure 14-1 on page L14-2.
n t 9 2
S t ud
( sai this
Task 2 – CompilingRthe u se
AN ChatClient Class
L T e to
O BE ensthe ChatClient class.
E N le lic
In this task, you compile

M OR ferab
A ROTask
t r a n3s– Running the ChatClient Program
GEN non-
In this task, you run the ChatClient program. You should see the GUI shown in
Figure 14-1 on page L14-2. If your GUI does not look exactly like the figure,
then edit the code to tweak the design to match this figure.

GUI-Based Applications Lab 14-3


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 2)

Exercise: Creating the ChatClient GUI, Part 3 (Level 2)


In this exercise, you enhance the GUI for a chat room application. You complete
the GUI for the ChatClient by adding a JComboBox component and two
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

menus.

This exercise contains the following sections:


● “Task 1 – Modifying the ChatClient Class”
● “Task 2 – Compiling the ChatClient Class”
● “Task 3 – Running the ChatClient Program”

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:

9
Java Development: Java Classes: Modifying

t d Compiling Java
2 JavatuClasses:
n S
Classes
( sai this
Java Development: Java

R se
N uModifying
AClasses: Java Classes: Executing Java
Programs
E LT se to
O B en
N lyou
For this exercise, c in the ChatRoomPrj project in the
liwork
E e
M OR ferab
d:\labs\student\projects directory.

A RO -trans
G EN Task
non 1 – Modifying the ChatClient Class
In this task, you modify the ChatClient class in the source package of the
ChatRoomPrj project. This class must implement the GUI design in
Figure 14-1 on page L14-2.

Complete the following steps:


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.
2. Enhance the listeners for the Send button and JTextField to write the
user name to the output JTextArea component.

Lab 14-4 Java™ Programming Language


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 2)

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

terminates the program when selected.


5. 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.

Task 2 – Compiling the ChatClient Class


In this task, you compile the ChatClient class.
s a
) h a
Task 3 – Running the ChatClient Program c o m

ail eฺ
g m idGUI, shown
In this task, you run the ChatClient program. You@ G
should see u
the
in Figure 14-1 on page L14-2. If your GUI does
0 2 1not1 lookenexactly
t like the figure,
d
2 thistufigure.
then edit the code to tweak the design tto9match
n S
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non

GUI-Based Applications Lab 14-5


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 3)

Exercise: Creating the ChatClient GUI, Part 3 (Level 3)


In this exercise, you enhance the GUI for a chat room application. You complete
the GUI for the ChatClient by adding a JComboBox component and two
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

menus.

This exercise contains the following sections:


● “Task 1 – Modifying the ChatClient Class”
● “Task 2 – Compiling the ChatClient Class”
● “Task 3 – Running the ChatClient Program”

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:

9
Java Development: Java Classes: Modifying

t d Compiling Java
2 JavatuClasses:
n S
Classes
( sai this
Java Development: Java

R se
N uModifying
AClasses: Java Classes: Executing Java
Programs
E LT se to
O B en
N lyou
For this exercise, c in the ChatRoomPrj project in the
liwork
E e
M OR ferab
d:\labs\student\projects directory.

A RO -trans
G EN Task
non 1 – Modifying the ChatClient Class
In this task, you modify the ChatClient class in the source package of the
ChatRoomPrj project. This class must implement the GUI design in
Figure 14-1 on page L14-2.

Complete the following steps:


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.
public class ChatClient {
// existing code here
private JComboBox usernames;

Lab 14-6 Java™ Programming Language


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 3)

// existing code here


public ChatClient() {
// more GUI components initialized
usernames = new JComboBox();
usernames.addItem("Jane Doe");
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

usernames.addItem("1337dud3");
usernames.addItem("Java Geek");
}
// existing code here
}
2. Add the aboutDialog instance variable of type
javax.swing.JDialog to the ChatClient class.
3. Add the frame instance variable of type javax.swing.JFrame to the
ChatClient class.
s a
)
4. Modify the declaration and initialization of the frame variable in the h a
launchFrame method to the following: o m
a ilฺc ฺ
frame = new JFrame("Chat Room");
g m ide
@
5. Enhance the listeners for the Send button and1JTextFieldG uto write the
1 t
9 2 02 uden
user name to the output JTextArea component.
i nt is St {
private class SendHandler implements ActionListener
a
public void actionPerformed(ActionEvent
N (s e te)h {
String text = input.getText();
T R A
t o us
L se
output.append(usernames.getSelectedItem()
E + ": " + text + "\n");
input.setText("");
O B en
}
E N le lic
}
M OR ferab
A RO -tra6.ns Add a JScrollPane component to the project and add the JTextArea

E N on component to the a JScrollPane. Add a vertical scroll bar but no


G n horizontal scroll bar.
// Add declaration
private JScrollPane textPane;
// existing code here

// Put JTextArea into JScrollPane and define scroll bars


textPane = new JScrollPane(output,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// existing code here

// Add JScrollPane to Layout


frame.add(textPane, BorderLayout.WEST);

GUI-Based Applications Lab 14-7


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 3)

7. Auto scroll the text to the bottom of the JTextArea as the user adds text to
the text chat window.
// Add to SendHandler to enable AutoScroll
output.setCaretPosition(output.getDocument().getLength()-1);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

8. Add the File menu. This menu must include a Quit menu item that
terminates the program when selected.
public void launchFrame() {
// existing code here
// Create menu bar and File menu
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem quitMenuItem = new JMenuItem("Quit");
quitMenuItem.addActionListener(new ActionListener() {
s a
public void actionPerformed(ActionEvent e) {
) h a
System.exit(0);
c o m
} ฺ
ail eฺ
}); g m id
@ G u
file.add(quitMenuItem);
mb.add(file); 0 2 11 ent
frame.setJMenuBar(mb);
n t 9 2
S t ud
// existing code here
( sai this
}
R AN use
9. Add the Help menu.
E LT Thissemenuto must include an About menu item that pops
up a simpleBdialog e n that displays a comment about the program and
box,
O l i c
R ENyou,bthe
about
l e developer.
O fera {
public void launchFrame()
M
A R//O Add
// existing
t r a ns bar
menu code here

E N JMenuo n - Help menu to menu bar


G n help = new JMenu("Help");
JMenuItem aboutMenuItem = new JMenuItem("About");
aboutMenuItem.addActionListener(new AboutHandler());
help.add(aboutMenuItem);
mb.add(help);
// existing code here
}

private class AboutHandler implements ActionListener {


public void actionPerformed(ActionEvent e) {
// Create the aboutDialog when it is requested
if ( aboutDialog == null ) {
aboutDialog = new AboutDialog(frame, "About", true);
}

Lab 14-8 Java™ Programming Language


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 3)

aboutDialog.setVisible(true);
}
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

private class AboutDialog extends JDialog implements ActionListener


{
public AboutDialog(Frame parent, String title, boolean modal) {
super(parent,title,modal);
add(new JLabel("The ChatClient is a neat tool that allows you
to talk " +
"to other ChatClients via a
ChatServer"),BorderLayout.NORTH);
JButton b = new JButton("OK");
add(b,BorderLayout.SOUTH);
s a
b.addActionListener(this);
) h a
pack();
c o m
} ฺ
ail eฺ
// Hide the dialog box when the OK button is pushed
g m id
@ G u
11 ent
public void actionPerformed(ActionEvent e) {
setVisible(false);
0 2
}
n t 9 2
S t ud
}
( sai this
R AN use
LT the e o
tChatClient
Task 2 – Compiling B E n s Class
NO le lic e
E
M OInRthisfetask,
rabyou compile the ChatClient class.
A RO -trans
GEN noTask
n 3 – Running the ChatClient Program
In this task, you run the ChatClient program. You should see the GUI shown in
Figure 14-1 on page L14-2. If your GUI does not look exactly like the figure,
then edit the code to tweak the design to match this figure.

GUI-Based Applications Lab 14-9


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

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-10 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ

Lab 15
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Threads

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)

Exercise: Using Multithreaded Programming (Level 1)


In this exercise, you become familiar with the concepts of multithreading by
writing a multithreaded program.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.

This exercise contains the following sections:


● “Task 1 – Creating the PrintMe Class”
● “Task 2 – Creating the TestThreeThreads Class”
s a
● “Task 3 – Compiling the TestThreeThreads Class” ) h a
c o m
● “Task 4 – Running the TestThreeThreads Program” ฺ
ail eฺ
g m id
@ G u
Preparation 0 2 11 ent
n t 9 2
S t ud
(
There is no preparation required for ai exercise.
sthis t h is
R AN use
Tool Reference – E LTreferences
Tool e toused in this exercise:
s
JavaN O B liceJava
Development:
n
Application Projects: Opening Projects

E l e
M ORJavafeDevelopment:
● rab Java Classes: Creating Java Classes
s Development: Java Classes: Modifying Java Classes: Compiling Java
RO -tranJava
A ●

G EN non Classes
● Java Development: Java Classes: Modifying Java Classes: Executing Java
Programs

For this exercise, you work in the ThreadProject project in the


d:\labs\student\exercises\15_threads directory.

Lab 15-2 Java™ Programming Language


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)

Task 1 – Creating the PrintMe Class


Complete the following steps:
1. Open the ThreadProject project in the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

d:\labs\student\exercises\15_threads directory.
2. Create a PrintMe class in the source package of the ThreadProject
with the following characteristics:
Class Name: PrintMe
Project: ThreadProject
Location: Source Packages
Package: default package
s a
Add code so that PrintMe implements Runnable.
) h a
c o m
a ฺ
The class implements the Runnable interface. The run methodil of the class
ฺ and
performs the following actions 10 times: Print the name g ofm i d
the current ethread
then sleep for 2 seconds.
1 1 @ t Gu
9 2 02 uden
Task 2 – Creating the TestThreeThreads a i nt is St Class
( s t h
R AN use
In this task, you create
E to
LT a TestThreeThreads
e class in the source package of the
B n s
O lice
ThreadProject
N
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.

Task 3 – Compiling the TestThreeThreads Class


In this task, you compile the TestThreeThreads class.

Threads Lab 15-3


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)

Task 4 – Running the TestThreeThreads Program


In this task, you run the TestThreeThreads program. You should see output
similar to this:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
T1
-
-
Curly
Larry 0 2 11 ent
T3 - Moe n t 9 2
S t ud
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.

Discussion – Can you explain the behavior of your program?


!
?

Lab 15-4 Java™ Programming Language


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 2)

Exercise: Using Multithreaded Programming (Level 2)


In this exercise, you become familiar with the concepts of multithreading by
writing a multithreaded program.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Creating the PrintMe Class”
● “Task 2 – Creating the TestThreeThreads Class”
● “Task 3 – Compiling the TestThreeThreads Class”
● “Task 4 – Running the TestThreeThreads Program”

s a
Preparation
) h a
c o m
There is no preparation required for this exercise. ฺ
ail eฺ
g m id
@ G u
11 ent
Tool Reference – Tool references used in this2exercise:
0
t 9 d Projects
2Projects:tuOpening
n
Java Development: Java Application S
sai Creating

( t h is Java Classes

N use
Java Development: Java Classes:
AJava
Java Development:

L R o
T e tClasses: Modifying Java Classes: Compiling Java
ClassesBE n s
O e
lic Java Classes: Modifying Java Classes: Executing Java
N Development:
EJava

l e
M OR fPrograms
e rab
A nsthis exercise, you work in the ThreadProject project in the
RO -traFor
GEN non d:\labs\student\exercises\15_threads directory.

Threads Lab 15-5


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 2)

Task 1 – Creating the PrintMe Class


Complete the following steps:
1. Open the ThreadProject project in the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

d:\labs\student\exercises\15_threads directory.
2. Create the PrintMe class with the following characteristics:
Class Name: PrintMe
Project: ThreadProject
Location: Source Packages
Package: default package
Add code so that PrintMe implements Runnable. a
3. Create the run method to loop the following 10 times: Print the name of)the has
current thread and then sleep for 2 seconds.
c o m

ail eฺ
g m id
@ G u
Task 2 – Creating the TestThreeThreads
0 2 11 Class
e n t
n t 9 2
S t ud
ai thclass
In this task, you create a TestThreeThreads
( s is in the source package of the
ThreadProject project. N
R A u se
E
Complete the following LTsteps:se to
O B en
E
1. Create
l e lic
N the TestThreeThreads class with the following characteristics:
R
O Class b
ra TestThreeThreads
M f eName:
s ThreadProject
A RO -tranProject:
N on
GE n 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.

Task 3 – Compiling the TestThreeThreads Class


In this task, you compile the TestThreeThreads class.

Lab 15-6 Java™ Programming Language


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 2)

Task 4 – Running the TestThreeThreads Program


In this task, you run the TestThreeThreads program. You should see output
similar to that shown in ‘‘Task 4 – Running the TestThreeThreads Program’’
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

on page L15-4.

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

Threads Lab 15-7


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 3)

Exercise: Using Multithreaded Programming (Level 3)


In this exercise, you become familiar with the concepts of multithreading by
writing a multithreaded program.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Creating the PrintMe Class”
● “Task 2 – Creating the TestThreeThreads Class”
● “Task 3 – Compiling the TestThreeThreads Class”
● “Task 4 – Running the TestThreeThreads Program”

s a
Preparation
) 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 exercise:
0 2 11 ent
Java Development: Java Application n t 9 2 Opening
Projects: S t ud Projects

i
saCreating s Classes
iJava
(
N use
Java Development: Java Classes:
● t h
R AClasses:
Java Development:

L T e to Modifying Java Classes: Compiling Java
Java
Classes BE n s
O e
lic Java Classes: Modifying Java Classes: Executing Java
NDevelopment:
E
Java

l e
M ORPrograms
e r a b
R O ransf
A t this exercise, you work in the ThreadProject project in the
EN non-d:\labs\student\exercises\15_threads directory.
For
G
Task 1 – Creating the PrintMe Class
Complete the following steps:
1. Open the ThreadProject project in the
d:\labs\student\exercises\15_threads directory.

Lab 15-8 Java™ Programming Language


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 3)

2. Create the PrintMe class with the following characteristics:


Class Name: PrintMe
Project: ThreadProject
Location: Source Packages
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Package: default package


Add code so that PrintMe implements Runnable.
class PrintMe implements Runnable {
// more code here
}
3. Create the run method to loop the following 10 times: Print the name of the
current thread and then sleep for 2 seconds.
public void run() { s a
for(int x = 0; x < 10; x++) { ) h a
System.out.println(Thread.currentThread().getName());
c o m
try { ฺ
ail eฺ
Thread.sleep(2000); g m id
@ G u
} catch(Exception e) {}
0 2 11 ent
}
n t 9 2
S t ud
sai this
}
(
R AN use
Task 2 – Creating
E to
LTtheseTestThreeThreads Class
O B en
E
In thisNtask, you
l e lic a TestThreeThreads class in the source package of the
create
R rab
OThreadProject project.
M f e
A ns
RO -traComplete
EN non
the following steps:
G 1. Create the TestThreeThreads class with the following characteristics:
Class Name: TestThreeThreads
Project: ThreadProject
Location: Source Packages
Package: default package
public class TestThreeThreads {
// more code here
}

Threads Lab 15-9


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 3)

2. Create the main method.


a. Create three Thread objects and pass an instance of the PrintMe
class to each constructor.
public static void main(String[] args) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Runnable prog = new PrintMe();


Thread t1 = new Thread(prog);
Thread t2 = new Thread(prog);
Thread t3 = new Thread(prog);

// more code here


}
b. Give each thread a unique name using the setName method.
t1.setName("T1 - Larry");
t2.setName("T2 - Curly"); s a
t3.setName("T3 - Moe"); ) h a
c o m
c. Start each thread.
a il ฺ
t1.start(); g m i d eฺ
t2.start();
1 1 @ t Gu
t3.start();
9 2 02 uden
a i nt is St
s
N ( use th
Task 3 – Compiling theATestThreeThreads Class
R
LT se to
In this task, you B
E n TestThreeThreads class.
compileethe
O l i c
R EN ble
M O fera
Task
O ra–nRunning
4 s the TestThreeThreads Program
A R t
G EN non-In this task, you run the TestThreeThreads program. You should see output
similar to that shown in ‘‘Task 4 – Running the TestThreeThreads Program’’
on page L15-4.

Lab 15-10 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

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

Threads Lab 15-11


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 16
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Networking

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 Protocol/Internet Protocol
s a
(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)

Exercise: Creating a Socket Client (Level 1)


In this exercise, you write the code to connect the chat room client with the chat
server.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
client: PC/Win95
c o m
1 “Simon: This is cool!”

ail eฺ
g m id
@ G u
11 ent
ChatClient
3 “Simon: This is cool!”
0 2
2 ud
Simon
n t 9
server
S t
( sai this
R AN use
client: SparcSol9
E LT se to ChatServer
B e n
E
ChatClientNO le2 l“Simon:
ic This is cool!”
Debbie
M OR ferab
A RO -trans
N on
GE n
client: PC/WinXP

4 “Simon: This is cool!”


ChatClient
Asok

Figure 16-1 The Chat Server Sends Any Message to All Attached Clients

Lab 16-2 Java™ Programming Language


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 client (your application) must be modified to perform two behaviors: It
must send the user’s messages to the server, and it must display the messages it
receives from the server to the output JTextArea component. Figure 16-2 shows
a detailed design for the elements of the ChatClient application. You will add
the doConnect method to the ChatClient class to initiate the socket
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

connection to the chat server.

«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

O BDetailed
cenDesign of the ChatClient Application
instance variable in the ChatClient.

FigureN16-2 l i
O RE rable
O e contains the following sections:
M Thissfexercise
n
AR n-tra “Task 1 – Modifying the ChatClient Class”
E N
no

G ● “Task 2 – Compiling the ChatClient Class”
● “Task 3 – Running the ChatRoomPrj Project”

Networking Lab 16-3


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)

Preparation
There is no preparation for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Tool Reference – Tool references used in this exercise:


● Java Development: Java Classes: Modifying Java Classes: Compiling Java
Classes
● Java Application Projects: Setting the Main Class
● Java Development: Java Application Projects: Setting VM Options
● Java Development: Java Application Projects: Running Projects

For this exercise, you work in the ChatRoomPrj project in the projects
s a
directory.
) h a
c o m
il ฺ
Task 1 – Modifying the ChatClient Class gma ideฺ
1 1 @ t Gu
In this task, you modify the ChatClient class2 u enpackage of the
0in2the source
d
9 t
nt is Scommunication
ChatRoomPrj project. Implement the iclient-server based on the
s a h
N ( uL16-3.
detailed design in Figure 16-2 on page
A s et
L TR e to
Task 2 – CompilingO BE the e n sChatClient Class
E N le lic
InO
R ryou a bcompile the ChatClient class.
M e
this task,
O ransf
R
A n-t
G EN Task
no 3 – Running the ChatRoomPrj Project
Complete the following steps:
1. Set the main class of the ChatRoomPrj project to ChatClient.

Tool Reference – Java Development: Java Application Projects: Setting VM


Options
2. Set the following system properties to the ChatRoomPrj project:
-DserverIP=<server-host>
-DserverPort=2000

Lab 16-4 Java™ Programming Language


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)

Note – Ask your instructor for the value of the server-host.

3. Run the ChatRoomPrj project.


If your program connects to the server successfully, then the output text area
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.

Good luck and have fun!

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

Networking Lab 16-5


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 2)

Exercise: Creating a Socket Client (Level 2)


In this exercise, you write the code to connect the chat room client with the chat
server.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Modifying the ChatClient Class”
● “Task 2 – Compiling the ChatClient Class”
● “Task 3 – Running the ChatRoomPrj Project”

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 g m id
@ G u
Java Development: Java Classes: Modifying2Java

0 11Classes:
e n tCompiling Java
Classes
n t 9 2
S t ud
( saithe Main
Java Application Projects: Setting

t h isClass
N useProjects: Setting VM Options
AApplication
● R
Java Development: Java
to
LTJavasApplication
E
B en
Java Development:
● e Projects: Running Projects
O
N le lic
For thisE
R rab you work in the ChatRoomPrj project in the projects
exercise,
O fe
Mdirectory.
O n s
N AR n-tra
G E no Task 1 – Modifying the ChatClient Class
In this task, you modify the ChatClient class in the source package of the
ChatRoomPrj project. Implement the client-server communication based on the
detailed design in Figure 16-2 on page L16-3.

Complete the following steps:


1. Import the java.net and java.io packages.
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.

Lab 16-6 Java™ Programming Language


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 2)

3. Add the doConnect method to initiate the TCP/IP socket connection 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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.
4. Modify the launchFrame method to call the doConnect method.
5. Modify the SendHandler nested class to send the message text (and the
s a
user name) to the socket output stream. Delete the code that displayed the
) h a
message to the output text area.
c o m
6. Create the RemoteReader nested class that implements the ฺ
ailtheRunnable
g
interface. The run method must read a line at a time m
from i d eฺ input
socket
stream in an infinite loop.
1 1 @ t Gu
9 2 02 uden
a i n t
i s St
Task 2 – Compiling the ChatClient
N (s e th Class
T R A
t o us
L sthee ChatClient class.
In this task, youEcompile
O B e n
l i c
R EN ble
Task
M ra
O 3 –feRunning the ChatRoomPrj Project
A ns
RO -traComplete
GEN non the following steps:
1. Set the main class of the ChatRoomPrj project to ChatClient.

Tool Reference – Java Development: Java Application Projects: Setting VM


Options
2. Set the following system properties to the ChatRoomPrj project:
-DserverIP=<server-host>
-DserverPort=2000

Networking Lab 16-7


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 2)

Note – Ask your instructor for the value of the server-host.

3. Run the ChatRoomPrj project.


If your program connects to the server successfully, then the output text area
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.

Good luck and have fun!

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

Lab 16-8 Java™ Programming Language


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 3)

Exercise: Creating a Socket Client (Level 3)


In this exercise, you will write the code to connect the chat room client with the
chat server.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

This exercise contains the following sections:


● “Task 1 – Modifying the ChatClient Class”
● “Task 2 – Compiling the ChatClient Class”
● “Task 3 – Running the ChatRoomPrj Project”

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
●Java Application Projects:(s ai the
Setting t h is Class
Main
R
Java Development: u se Projects: Setting VM Options
N Application
AJava
LT sJava to

● E e
B en Application Projects: Running Projects
Java Development:
O
N le lic
For E
R rexercise,
this b you work in the ChatRoomPrj project in the projects
O fe
M directory. a
O n s
N AR n-tra
GE no Task 1 – Modifying the ChatClient Class
In this task, you modify the ChatClient class in the source package of the
ChatRoomPrj project. Implement the client-server communication based on the
detailed design in Figure 16-2 on page L16-3.

Networking Lab 16-9


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 3)

Complete the following steps:


1. Import the java.net and java.io packages.
import java.net.*;
import java.io.*;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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 to the
g m id
server. Ask your instructor for the hostname (or IP address) and port
@ G u
number of the server application.
0 2 11 ent
private void doConnect() {
n t 9 2
S t ud
a.
( s i this
Initialize server IP and portainformation.
// 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 e r a b have hard coded the server IP address and port number in the
R O Socket
a n sfconstructor call below. The code for this step demonstrates how to make
could

tr values dynamic at runtime. The system properties, serverIP and


NA on-these
G E n serverPort, can be assigned on the java command using the -D option, as
follows:

java -DserverIP=myhost.example.com
-DserverPort=47 ChatClient

b. Create the connection to the chat server.


try {
connection = new Socket(serverIP, Integer.parseInt(serverPort));
c. Prepare the input stream and store it in an instance variable.
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
serverIn = new BufferedReader(isr);
d. Prepare the output stream and store it in an instance variable.

Lab 16-10 Java™ Programming Language


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 3)

serverOut = new PrintStream(connection.getOutputStream());


e. Launch the reader thread.
Thread t = new Thread(new RemoteReader());
t.start();
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

f. Use a catch clause to capture any exceptions.


} catch (Exception e) {
System.err.println("Unable to connect to server!");
e.printStackTrace();
} // END of try-catch block
} // END of doConnect method
4. Modify the launchFrame method to call the doConnect method.
private void launchFrame() {
// existing code here
s a
doConnect();
) h a
}
c o m
5. Modify the SendHandler nested class to send the message

ail texte(and
ฺ the
g m i d
user name) to the socket output stream. Delete the code thatudisplayed the
1 1 @ tG
02 ud{en
message to the output text area.
9 2
a i nt e) is{ St
private class SendHandler implements ActionListener
public void actionPerformed(ActionEvent
String text = input.getText(); N (s e th
T R A
text = usernames.getSelectedItem()
t o us+ ": " + text + "\n";
serverOut.print(text);
B EL nse
O lice
input.setText("");
N
R E ble
} // END of actionPerformed method
} // ENDM O er a
of SendHandler
f nested class
O s
R -tra6.n Create the RemoteReader nested class that implements the Runnable
A
GEN non interface. The run method must read a line at a time from the socket input
stream in an infinite loop.
private class RemoteReader implements Runnable {
public void run() {
try {
while ( true ) {
String nextLine = serverIn.readLine();
output.append(nextLine + "\n");
output.setCaretPosition(output.getDocument().getLength()-1);
}
} catch (Exception e) {
System.err.println("Error while reading from server.");
e.printStackTrace();
}
} // END of run method

Networking Lab 16-11


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 3)

} // END of RemoteReader nested class


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

Lab 16-12 Java™ Programming Language


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 3)

Task 2 – Compiling the ChatClient Class


In this task, you compile the ChatClient class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 3 – Running the ChatRoomPrj Project


Complete the following steps:
1. Set the main class of the ChatRoomPrj project to ChatClient.

Tool Reference – Java Development: Java Application Projects: Setting VM


Options
2. Set the following system properties to the ChatRoomPrj project: s a
-DserverIP=<server-host> ) h a
c o m
-DserverPort=2000 ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
Note – Ask your instructor for the value of the server-host.

n t 9 2
S t ud
3. Run the ChatRoomPrj project.
( sai this
ANfrom
If your program connects e successfully, then the output text area
to thesserver
u
will display a T
L R
message t o server with a secret passphrase. When you
the
BE
send that
n
pass phrase e
s to the server, you then trigger an event on the server
N
thatOplays a l ic e
gong. This event will indicate that your application is working
E
R correctly.bl e
O
M sfe r a
O n luck and have fun!
R -traGood
A
GEN non

Networking Lab 16-13


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise Summary

Exercise Summary

Discussion – Take a few minutes to discuss what experiences, issues, or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

discoveries you had during the lab exercise.


!
?
● Experiences
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
● Interpretations
_____________________________________________________________
s a
_____________________________________________________________
) h a
o m
_____________________________________________________________
c

ail eฺ
Conclusions

g m id
@ G u
0 2 11 ent
_____________________________________________________________

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 16-14 Java™ Programming Language


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2

Вам также может понравиться