Download as pdf or txt
Download as pdf or txt
You are on page 1of 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 1
NActivityusGuide
L TR e to
O BE ens SL-275-SE6 G.2
E N le lic
M OR ferab
A RO -trans
GEN non

D61748GC11
Edition 1.1
June 2010
D67982
7i Business Solutions, SฺAฺ de CฺVฺ

Copyright © 2009, 2010, Oracle and/or its affiliates. All rights reserved.

Disclaimer

This document contains proprietary information, is provided under a license agreement containing restrictions on use and
disclosure, and is protected by copyright and other intellectual property laws. You may copy and print this document solely for
your own use in an Oracle training course. The document may not be modified or altered in any way. Except as expressly
permitted in your license agreement or allowed by law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express
authorization of Oracle.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

The information contained in this document is subject to change without notice. If you find any problems in the document,
please report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This
document is not warranted to be error-free.

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 in Program i s S Errors ................................ 1-2
s
( et h
Preparation................................................................................. 1-2
N s
RA toa Test
Task – Correcting
ExerciseL2:TCreating
uCompilation and Runtime Errors........... 1-2
Program (Level 1) ............................... 1-4
B E nse
Preparation................................................................................. 1-4
O
N le l
Task i c1
e– Copying the Account Class ..................................... 1-5
E
M OR ferab Task 2 – Creating the TestAccount Class............................. 1-5
Task 3 – Compiling the TestAccount Class ......................... 1-6
A RO -trans Task 4 – Running the TestAccount Program ...................... 1-6
E N n
G no Exercise 2: Creating a Test Program (Level 2) ............................... 1-7
Preparation................................................................................. 1-7
Task 1 – Copying the Account Class ..................................... 1-8
Task 2 – Creating the TestAccount Class............................. 1-8
Task 3 – Compiling the TestAccount Class ......................... 1-9
Task 4 – Running the TestAccount Program ...................... 1-9
Exercise 2: Creating a Test Program (Level 3) ............................. 1-10
Preparation............................................................................... 1-10
Task 1 – Copying the Account Class ................................... 1-11
Task 2 – Creating the TestAccount Class........................... 1-11
Task 3 – Compiling the TestAccount Class ....................... 1-12
Task 4 – Running the TestAccount Program .................... 1-12
Exercise Summary............................................................................ 1-13

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

Object-Oriented Programming ....................................................... 2-1


Objectives ........................................................................................... 2-1
Exercise 1: Using the Java API Documentation............................. 2-2
Preparation................................................................................. 2-2
Task – Using the Java API Documentation ........................... 2-2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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


Preparation................................................................................. 2-4
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
s a
Task 2 – Creating the Account Class ..................................... 2-7
) h a
c o m
Task 3 – Creating the TestAccount2 Class .......................... 2-7

ail eฺ
Task 4 – Compiling the TestAccount2 Class....................... 2-8
g m
Task 5 – Running the TestAccount2 Program .................... 2-8
id
@ G u
Exercise 2: Exploring Encapsulation, Version 1 (Level 3) ............ 2-9
2 11 ent
Preparation................................................................................. 2-9
0
n t 9 2 t ud
Task 1 – Deleting the Account Class.................................... 2-10
S
sai this
Task 2 – Creating the Account Class ................................... 2-10
(
AN use
Task 3 – Creating the TestAccount2 Class ........................ 2-10
R
LT se to
Task 4 – Compiling the TestAccount2 Class..................... 2-11
E
B en Task 5 – Running the TestAccount2 Program .................. 2-11
O
N le lic
Exercise 3: Exploring Encapsulation, Version 2 (Level 1) .......... 2-12
E Preparation............................................................................... 2-12
M OR ferab Task 1 – Modifying the Account Class ................................ 2-13

A RO -trans Task 2 – Modifying the TestAccount Class ....................... 2-13

EN non
Task 3 – Compiling the TestAccount Class ....................... 2-13
G Task 4 – Running the TestAccount Program .................... 2-13
Exercise 3: Exploring Encapsulation, Version 2 (Level 2) .......... 2-14
Preparation............................................................................... 2-14
Task 1 – Modifying the Account Class ................................ 2-14
Task 2 – Modifying the TestAccount Class ....................... 2-15
Task 3 – Compiling the TestAccount Class ....................... 2-15
Task 4 – Running the TestAccount Program .................... 2-15
Exercise 3: Exploring Encapsulation, Version 2 (Level 3) .......... 2-16
Preparation............................................................................... 2-16
Task 1 – Modifying the Account Class ................................ 2-16
Task 2 – Modifying the TestAccount Class ....................... 2-17
Task 3 – Compiling the TestAccount Class ....................... 2-17
Task 4 – Running the TestAccount Program .................... 2-17
Exercise 4: Creating Java Packages................................................ 2-18
Preparation............................................................................... 2-19

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 1 – Creating the Java Packages .................................... 2-19


Task 2 – Moving and Modifying the Account Class ......... 2-19
Task 3 – Moving the TestAccount Class ............................ 2-20
Task 4 – Compiling the TestAccount Class ....................... 2-20
Task 5 – Running the TestAccount Program .................... 2-20
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Exercise Summary............................................................................ 2-21


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
s
Preparation................................................................................. 3-6 a
Task 1 – Creating the Customer Class ................................... 3-6 ) h a
c o m
Task 2 – Copying the TestBanking Class............................. 3-6

ail eฺ
Task 3 – Compiling the TestBanking Class ......................... 3-7
g m id
@ G u
Task 4 – Running the TestBanking Program ...................... 3-7

0 2 11 ent
Exercise 2: Creating Customer Accounts (Level 2) ....................... 3-8

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

M OR ferab Task 1 – Creating the Customer Class ................................. 3-12

RO -trans
Task 2 – Copying the TestBanking Class........................... 3-13
A Task 3 – Compiling the TestBanking Class ....................... 3-13
GEN non Task 4 – Running the TestBanking Program .................... 3-13
Exercise Summary............................................................................ 3-14
Expressions and Flow Control........................................................4-1
Objectives ........................................................................................... 4-1
Exercise 1: Using Loops and Branching Statements ..................... 4-2
Preparation................................................................................. 4-3
Task 1 – Creating the FooBarBaz Class ................................. 4-3
Task 2 – Compiling the FooBarBaz Class ............................. 4-4
Task 3 – Running the FooBarBaz Program........................... 4-4
Hints............................................................................................ 4-4
Exercise 2: Using Conditional Statements in the Account Class
(Level 1) ............................................................................................ 4-5
Preparation................................................................................. 4-5
Task 1 – Modifying the Account Class .................................. 4-6
Task 2 – Deleting the Current TestBanking Class ................ 4-6

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

Task 3 – Copying the TestBanking Class............................. 4-6


Task 4 – Compiling the TestBanking Class ......................... 4-6
Task 5 – Running the TestBanking Program ...................... 4-7
Exercise 2: Using Conditional Statements in the Account Class
(Level 2) ............................................................................................ 4-8
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Preparation................................................................................. 4-8
Task 1 – Modifying the Account Class .................................. 4-9
Task 2 – Deleting the Current TestBanking Class ................ 4-9
Task 3 – Copying the TestBanking Class............................. 4-9
Task 4 – Compiling the TestBanking Class ......................... 4-9
Task 5 – Running the TestBanking Program ...................... 4-9
Exercise 2: Using Conditional Statements in the Account Class
(Level 3) .......................................................................................... 4-10
Preparation............................................................................... 4-10
Task 1 – Modifying the Account Class ................................ 4-11
s a
Task 2 – Deleting the Current TestBanking Class .............. 4-11
) h a
Task 3 – Copying the TestBanking Class........................... 4-11
c o m
ail eฺ
Task 4 – Compiling the TestBanking Class ....................... 4-11 ฺ
g m
Task 5 – Running the TestBanking Program .................... 4-12
id
@ G u
Exercise 3: Using Nested Loops (Advanced) ............................... 4-13
2 11 ent
Preparation............................................................................... 4-13
0
n t 9 2 t ud
Task 1 – Writing the isSubString Method........................ 4-14
S
sai this
Task 2 – Compiling the TestIsSubString Class .............. 4-14
(
AN use
Task 3 – Running the TestIsSubString Program............ 4-14
R
LT se to
Hints......................................................................................... 4-15
B enE Exercise Summary............................................................................ 4-16
O
N le lic
Arrays................................................................................................ 5-1
R E b
M e ra 1 – Using Primitive Arrays (Level 2) ............................... 5-1
O fExercise
Objectives ...........................................................................................

R O rans Preparation................................................................................. 5-2 5-2


A t
G EN non- Task 1 – Creating the TestArrays Class............................... 5-2
Task 2 – Compiling the TestArrays Class ........................... 5-3
Task 3 – Running the TestArrays Program......................... 5-3
Hint ............................................................................................ 5-4
Exercise 1 – Using Primitive Arrays (Level 3) ............................... 5-5
Preparation................................................................................. 5-5
Task 1 – Creating the TestArrays Class............................... 5-5
Task 2 – Compiling the TestArrays Class ........................... 5-7
Task 3 – Running the TestArrays Program......................... 5-7
Exercise 2 – Using Arrays to Represent One-to-Many Associations
(Level 1) ............................................................................................ 5-8
Preparation................................................................................. 5-9
Task 1 – Creating the Bank Class ............................................ 5-9
Task 2 – Deleting the Current TestBanking Class............. 5-9
Task 3 – Copying the TestBanking Class........................... 5-10

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 4 – Compiling the TestBanking Class ....................... 5-10


Task 5 – Running the TestBanking Program .................... 5-10
Exercise 2 – Using Arrays to Represent One-to-Many Associations
(Level 2) .......................................................................................... 5-11
Task 1 – Creating the Bank Class .......................................... 5-12
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 2 – Deleting the Current TestBanking Class........... 5-12


Task 3 – Copying the TestBanking Class........................... 5-12
Task 4 – Compiling the TestBanking Class ....................... 5-12
Task 5 – Running the TestBanking Program .................... 5-13
Exercise 2 – Using Arrays to Represent One-to-Many Associations
(Level 3) .......................................................................................... 5-14
Task 1 – Creating the Bank Class .......................................... 5-15
Task 2 – Deleting the Current TestBanking Class........... 5-16
Task 3 – Copying the TestBanking Class........................... 5-16
Task 4 – Compiling the TestBanking Class ....................... 5-16
s a
Task 5 – Running the TestBanking Program .................... 5-16
) h a
c o m
Exercise Summary............................................................................ 5-17
ail eฺฺ
Class Design .....................................................................................6-1
g m id
1 @ G u
Objectives ........................................................................................... 6-1
Exercise 1: Creating Bank Account Subclasses
2 1 en t
(Level 1).............. 6-2
2 0 ud .................................. 6-3
Preparation.................................................................................
Task 1 – Modifyingithe n t9Account S tClass 6-4
s a h i s
A N ( uthe
Task 2 – Creating
Task 3 – Creating thes
t
eSavingsAccount Class ...................... 6-4
CheckingAccount Class.................... 6-4
L
Task T4R– Deleting
e to the Current TestBanking Class .............. 6-5
E s
BTask 5e–nCopying the TestBanking Class............................. 6-5
O
N leTask lic6 – Compiling the TestBanking Class ......................... 6-5
E
M OR ferExercise
ab Task1:7Creating
– Running the TestBanking Program ...................... 6-5

R O rans Bank Account Subclasses (Level 2).............. 6-7

N A n-t Preparation................................................................................. 6-7


GE no Task 1 – Modifying the Account Class .................................. 6-8
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-13
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
Task 6 – Compiling the TestBanking Class ....................... 6-16
Task 7 – Running the TestBanking Program .................... 6-16

ix
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)......................................................................... 6-18
Preparation............................................................................... 6-19
Task 1 – Modifying the Customer Class.............................. 6-19
Task 2 – Copying and Completing the CustomerReport
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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-22
Task 2 – Copying and Completing the CustomerReport
Class ....................................................................................... 6-22
Task 3 – Copying the TestReport Class............................. 6-23
s a
Task 4 – Compiling the TestReport Class ......................... 6-23
) h a
c o m
Task 5 – Running the TestReport Program....................... 6-23

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

LT se to
Task 5 – Running the TestReport Program....................... 6-27
E Exercise 3: Creating a Batch Program (Advanced) ..................... 6-28
B en
O
N le lic Preparation............................................................................... 6-29
E Task 1 – Modifying the SavingsAccount Class................. 6-29
M OR ferab Task 2 – Creating the AccumulateSavingsBatch

A RO -trans Class ....................................................................................... 6-29

EN non
Task 3 – Copying the TestBatch Class ............................... 6-30
G Task 4 – Compiling the TestBatch Class ........................... 6-30
Task 5 – Running the TestBatch Program......................... 6-30
Exercise Summary............................................................................ 6-32
Advanced Class Features ............................................................... 7-1
Objectives ........................................................................................... 7-1
Exercise 1: Applying Static Members to a Design (Level 1) ........ 7-2
Preparation................................................................................. 7-3
Task 1 – Modifying the Bank Class......................................... 7-3
Task 2 – Modifying the CustomerReport Class................... 7-3
Task 3 – Deleting the Current TestReport Class ................ 7-4
Task 4 – Copying the TestReport Class............................... 7-4
Task 5 – Compiling the TestReport Class ........................... 7-4
Task 6 – Running the TestReport Program......................... 7-4
Exercise 1: Applying Static Members to a Design (Level 2) ........ 7-5

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 1 – Modifying the Bank Class......................................... 7-6


Task 2 – Modifying the CustomerReport Class................... 7-6
Task 3 – Deleting the Current TestReport Class ................ 7-7
Task 4 – Copying the TestReport Class............................... 7-7
Task 5 – Compiling the TestReport Class ........................... 7-7
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
Exercise 2: Working With Interfaces and Abstract Classes
(Level 1) .......................................................................................... 7-12
s a
h a
Preparation............................................................................... 7-13
)
c o m
Task 1 – Creating the Pet Interface ....................................... 7-13

ail eฺ
Task 2 – Creating the Animal Classes .................................. 7-14
g m
Task 3 – Creating the TestAnimals Class........................... 7-14
id
@ G u
Task 4 – Compiling the TestAnimals Class ....................... 7-15
2 11 ent
Task 5 – Running the TestAnimals Program .................... 7-15
0
n t 9 2 t ud
Exercise 2: Working With Interfaces and Abstract Classes
S
sai this
(Level 2) .......................................................................................... 7-16
(
R AN use
Preparation............................................................................... 7-16

LT se to
Task 1 – Creating the Pet Interface ....................................... 7-17
E
B en Task 2 – Creating the Animal Classes .................................. 7-17
O
N le lic Task 3 – Creating the TestAnimals Class........................... 7-19
E Task 4 – Compiling the TestAnimals Class ....................... 7-20
M OR ferab Task 5 – Running the TestAnimals Program .................... 7-20

A RO -trans Exercise 2: Working With Interfaces and Abstract Classes

EN non
(Level 3) .......................................................................................... 7-21
G Preparation............................................................................... 7-21
Task 1 – Creating the Pet Interface ....................................... 7-22
Task 2 – Creating the Animal Classes .................................. 7-22
Task 3 – Creating the TestAnimals Class........................... 7-25
Task 4 – Compiling the TestAnimals Class ....................... 7-26
Task 5 – Running the TestAnimals Program .................... 7-26
Exercise Summary............................................................................ 7-27
Exceptions and Assertions .............................................................8-1
Objectives ........................................................................................... 8-1
Exercise: Creating Your Own Exception (Level 1) ........................ 8-2
Task 1 – Creating the OverdraftException Class ............. 8-4
Task 2 – Modifying the Account Class .................................. 8-4
Task 3 – Modifying the CheckingAccount Class ................ 8-4
Task 4 – Deleting the Current TestBanking Class .............. 8-4

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

Task 5 – Copying the TestBanking Class............................. 8-4


Task 6 – Compiling the TestBanking Class ......................... 8-5
Task 7 – Running the TestBanking Program ...................... 8-5
Exercise: Creating Your Own Exception (Level 2) ........................ 8-6
Task 1 – Creating the OverdraftException Class ............. 8-7
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
Task 2 – Modifying the Account Class ................................ 8-11
Task 3 – Modifying the CheckingAccount Class .............. 8-11
s a
Task 4 – Deleting the Current TestBanking Class ............ 8-12
) h a
Task 5 – Copying the TestBanking Class........................... 8-12
c o m
ail eฺฺ
Task 6 – Compiling the TestBanking Class ....................... 8-12
g m
Task 7 – Running the TestBanking Program .................... 8-12
id
@ G u
Exercise Summary............................................................................ 8-13
0 2 11 ent
n t 9 2
S t ud
Collections and Generics Framework............................................ 9-1

s a i
Objectives ...........................................................................................
i s 9-1
N ( ustoeRepresent
Exercise 1: Using Collections t h Association
R A
(Level 1) ............................................................................................ 9-2
T t o
B
TaskE1L– Modifying
Preparation.................................................................................
n s e the Bank Class......................................... 9-3 9-3
O l i c e
R EN Task b l e 23 –– Modifying the Customer Class................................ 9-3

M O feraTask 4 – Running thetheTestReport


Task Compiling TestReport Class ........................... 9-4

R O rans Exercise 1: Using Collections to RepresentProgram ....................... 9-4


A t Association
G EN non- (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
Exercise Summary............................................................................ 9-12

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ฺ

I/O Fundamentals ...........................................................................10-1


Console I/O and File I/O .................................................................11-1
Objectives ......................................................................................... 11-1
Exercise 1: Reading a Data File (Level 1) ...................................... 11-2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Preparation............................................................................... 11-4
Task 1 – Creating a data Directory ...................................... 11-4
Task 2 – Copying the Resource File...................................... 11-4
Task 3 – Creating the DataSource Class............................. 11-5
Task 4 – Deleting Unnecessary Classes ............................... 11-5
Task 5 – Copying the TestReport Class............................. 11-5
Task 6 – Compiling the TestReport Class ......................... 11-5
Task 7 – Running the BankPrj Project................................. 11-6
Exercise 1: Reading a Data File (Level 2) ...................................... 11-7
Preparation............................................................................... 11-7
Task 1 – Creating a data Directory ...................................... 11-8 s a
Task 2 – Copying the Resource File...................................... 11-8 ) h a
c o m
Task 3 – Creating the DataSource Class............................. 11-8

ail eฺ
Task 4 – Deleting Unnecessary Classes ............................... 11-9
g m id
@ G u
Task 5 – Copying the TestReport Class............................. 11-9

0 2 11 ent
Task 6 – Compiling the TestReport Class ......................... 11-9

n t 2
S t ud
Task 7 – Running the BankPrj Project................................. 11-9
9
sai this
Exercise 1: Reading a Data File (Level 3) .................................... 11-11
(
Preparation............................................................................. 11-11
R AN use
Task 1 – Creating a data Directory .................................... 11-12
E LT se to
Task 2 – Copying the Resource File.................................... 11-12
O B en Task 3 – Creating the DataSource Class........................... 11-12
E N le lic Task 4 – Deleting Unnecessary Classes ............................. 11-15

M OR ferab Task 5 – Copying the TestReport Class........................... 11-15

RO -trans
Task 6 – Compiling the TestReport Class ....................... 11-15
A Task 7 – Running the BankPrj Project............................... 11-15
GEN non Exercise Summary.......................................................................... 11-17
Building Java GUIs Using the Swing API.....................................12-1
Objectives ......................................................................................... 12-1
Exercise 1: Creating the ChatClient GUI Part 1 (Level 1)........ 12-2
Preparation............................................................................... 12-3
Task 1 – Creating the ChatClient Class............................. 12-3
Task 2 – Compiling the ChatClient Class ......................... 12-4
Task 3 – Running the ChatClient Program....................... 12-4
Task 4 – Terminating the Running ChatClient Program 12-4
Exercise 1: Creating the ChatClient GUI Part 1 (Level 2)........ 12-5
Preparation............................................................................... 12-5
Task 1 – Creating the ChatClient Class............................. 12-6
Task 2 – Compiling the ChatClient Class ......................... 12-6
Task 3 – Running the ChatClient Program....................... 12-7
Task 4 – Terminating the Running ChatClient Program 12-7

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

Exercise 1: Creating the ChatClient GUI Part 1 (Level 3)........... 12-8


Preparation............................................................................... 12-8
Task 1 – Creating the ChatClient Class............................. 12-9
Task 2 – Compiling the ChatClient Class ....................... 12-10
Task 3 – Running the ChatClient Program..................... 12-11
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
Hints........................................................................................ 12-15
s a
Exercise Summary.......................................................................... 12-16
) h a
o m
Handling GUI-Generated Events .................................................. 13-1
c

ail eฺ
Objectives ......................................................................................... 13-1
g m id
@ G u
Exercise 1: Creating the ChatClient GUI Part 2 (Level 1)........ 13-2

0 2 11 ent
Preparation............................................................................... 13-2

n t 2
S t ud
Task 1 – Modifying the ChatClient Class ......................... 13-3
9
sai this
Task 2 – Compiling the ChatClient Class ......................... 13-3
(
Task 3 – Running the ChatClient Program....................... 13-3
AN use
Hints.......................................................................................... 13-3
R
LT se to
Exercise 1: Creating the ChatClient GUI Part 2 (Level 2)........ 13-4
E
O B en Preparation............................................................................... 13-4
E N le licTask 1 – Modifying the ChatClient Class ......................... 13-4

M OR ferab Task 2 – Compiling the ChatClient Class ......................... 13-5

RO -trans
Task 3 – Running the ChatClient Program....................... 13-5
A Exercise 1: Creating the ChatClient GUI Part 2 (Level 3)........ 13-6
G EN non Preparation............................................................................... 13-6
Task 1 – Modifying the ChatClient Class ......................... 13-6
Task 2 – Compiling the ChatClient Class ......................... 13-8
Task 3 – Running the ChatClient Program....................... 13-8
Exercise 2: Creating the Bank ATM GUI Part 2
(Advanced)..................................................................................... 13-9
Preparation............................................................................. 13-10
Task 1 – Modifying the ATMClient Class.......................... 13-10
Task 2 – Compiling the ATMClient Class ......................... 13-10
Task 3 – Running the BankPrj Project............................... 13-10
Exercise Summary.......................................................................... 13-12
GUI-Based Applications ................................................................ 14-1
Objectives ......................................................................................... 14-1
Exercise: Creating the ChatClient GUI, Part 3 (Level 1).......... 14-2
Preparation............................................................................... 14-3

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ฺ

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

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-10
Exercise Summary.......................................................................... 14-11
Threads............................................................................................15-1s a
) h a
Objectives ......................................................................................... 15-1
c o m
Exercise: Using Multithreaded Programming (Level 1)............. 15-2

ail eฺ
Preparation............................................................................... 15-2
g m id
@ G u
Task 1 – Creating the PrintMe Class ................................... 15-3

0 2 11 ent
Task 2 – Creating the TestThreeThreads Class................ 15-3

n t 2
S t ud
Task 3 – Compiling the TestThreeThreads Class ............ 15-3
9
sai this
Task 4 – Running the TestThreeThreads Program ......... 15-4
(
Exercise: Using Multithreaded Programming (Level 2)............. 15-5
R AN use
Preparation............................................................................... 15-5
E LT se to
Task 1 – Creating the PrintMe Class ................................... 15-6
O B en Task 2 – Creating the TestThreeThreads Class................ 15-6
E N le lic Task 3 – Compiling the TestThreeThreads Class ............ 15-7

M OR ferab Task 4 – Running the TestThreeThreads Program ......... 15-7

RO -trans
Exercise: Using Multithreaded Programming (Level 3)............. 15-8
A Preparation............................................................................... 15-8
GEN non Task 1 – Creating the PrintMe Class ................................... 15-8
Task 2 – Creating the TestThreeThreads Class................ 15-9
Task 3 – Compiling the TestThreeThreads Class .......... 15-10
Task 4 – Running the TestThreeThreads Program ....... 15-10
Exercise Summary.......................................................................... 15-11
Networking ......................................................................................16-1
Objectives ......................................................................................... 16-1
Exercise: Creating a Socket Client (Level 1) ................................. 16-2
Preparation............................................................................... 16-4
Task 1 – Modifying the ChatClient Class ......................... 16-4
Task 2 – Compiling the ChatClient Class ......................... 16-4
Task 3 – Running the ChatRoomPrj Project........................ 16-4
Exercise: Creating a Socket Client (Level 2) ................................. 16-6
Preparation............................................................................... 16-6
Task 1 – Modifying the ChatClient Class ......................... 16-6

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

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
Task 1 – Modifying the ChatClient Class ......................... 16-9
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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


Task 3 – Running the ChatRoomPrj Project...................... 16-12
Exercise Summary.......................................................................... 16-13

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ฺ

LabPreface
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:
s a
Write a Java™ technology program using the fundamental language
● ) h a
o m
ilฺc statements
elements: primitive types, reference types, arithmetic operators,
a
m ideฺ
relational operators, conditional statements, and iterative
g u
@object-oriented
Write a Java technology program using good

1 1 t G
programming concepts and principles:
2 u d en inheritance,
02 encapsulation,
interfaces, polymorphism, object
i n t 9 S t
association, and multiplicity in
associations
( sa this
Write a robust Java

R AN u seprogram using exception handling,
technology
LT seandtoconcurrency control
generic collections,
E
O
Write
B Java
a richic e ntechnology program using the graphical user

Einterface l
N le(GUI) application programming interfaces (APIs),
R rab
O finput/output
O M s e (I/O) APIs, and networking APIs

A R -tran
N on This workbook presents the lab exercises for each module of the Student
GE n Guide.

Lab Preface-xvii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Performing the Exercises

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

ail eฺ
labs are intended for more advanced students who complete the primary
g m id
labs easily.
@ 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 ls -al to list all files.
system% You have mail.

s a
Courier is also used to indicate programming constructs, such as class
) h a
names, methods, and keywords; for example:
c o m
il ฺ
The getServletInfo method is used to get authorainformation.
The java.awt.Dialog class contains Dialog g m i d eฺ
1 1 @ t Gu
constructor.

02numbersd n
ethat
Courier bold is used for characters9and
t 2 t u you type; for
n S
example:
( sai this
To list the files inA
R
this
u se type:
N directory,
# ls
E LT se to
O B en
Courier
E N le islicalso used for each line of programming code that is
bold
R rabin a textual description; for example:
Oreferenced
O M
n s f1e import java.io.*;
N AR n-tra 2 import javax.servlet.*;
GE no 3 import javax.servlet.http.*;
Notice the javax.servlet interface is imported to allow access to its life cycle
methods (Line 2).

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.
s a
“The doIt() method...” refers to a method called doIt that takes ) h a
o m
ilฺc ฺ
no arguments.
Line breaks occur only where there are separationsm a e

@ g (commas),
u idcode
1 1
conjunctions (operators), or white space in the code.
t G
Broken is
indented four spaces under the starting
9 2 02code.uden

a i
If a command used in the Solaris™
i s St System (Solaris OS) is
nt Operating
s in the
different from a command(used th Microsoft Windows platform,
both commands are A N
shown; for e
usexample:
T R
L Solaris t o
If working in
B Ethe
e n se OS
$ cd
E NO lic
$SERVER_ROOT/bin
l e
M ORIf working
e r a b in Microsoft Windows
R sf cd %SERVER_ROOT%\bin
O ranC:\>
E NA on-t
G n

Lab 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

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

Objectives
Upon completion of this lab, you should be able to:
● Diagnose simple compilation and runtime errors s a
Create a test program for an existing class ) h a

c o m

ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non

Lab 1-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Exploring Java™ Program Errors

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ฺ
g m
Java Development: Java Classes: Modifying Java Classes: id
Compiling

@ G u
Java Classes
0 2 11 ent

n t 9 2
Java Development: Java Classes: Modifying
S t ud Classes: Executing
Java
Java Programs
( sai this
R u se
AinNthe TestProject
For this exercise, youT
L work
e t o project in the
BE ens
exercises/01_intro/exercise1
O
directory.

E N le lic
M OR ferab – The demonstration
Demonstration for this exercise can be found in the

ns
1 demos/01_intro/exercise1 directory.
2 RO r a
A t
G EN3 non-
Task – Correcting Compilation and Runtime Errors
In this task, you are presented with four Java programs that contain
errors. The errors can be either compilation or runtime errors. Your job is
to diagnose and fix those errors so the programs will execute.

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
) h a
c o m
Classes: Executing Java Programs

Tool Reference – Java Development: Java Classes: Modifying Java
ail eฺ
g m id
@ G u
5. Execute the Java program.
0 2 11 ent
n t 9
6. If a runtime error occurs, identify 2the source
S t udof the error and fix it.
ai there
7. Repeat step 5 and step (6suntil
t h isare no more errors.
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-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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

provide 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
c o m
+deposit(amt:double):void
+withdraw(amt:double):void ฺ
ail eฺ
g m id
@ G u
Figure 1-1 Banking Account Class
0 2 11 ent
t 9 2 t u d
n S
( sai sections:
This exercise contains the following
t h is
“Task 1 – Copying

R AN se Class”
the Account
u
“Task 2 E
● LT sethetoTestAccount Class”
– Creating
O B3 – Compiling
e n the TestAccount Class”
“Task l i c
EN

R a b le– Running the TestAccount Program”


O
M sfer
“Task ●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: Copying Existing Resources
● 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)

Demonstration – The demonstration for this exercise can be found in the


1 demos/01_intro/exercise2 directory.
2
3
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 1 – Copying the Account Class


In this task, you create the BankPrj project, and copy the pre-provided
Account class to the project.

Tool Reference – Java Development: Java Application Projects: Creating


Projects
s a
1. Create the BankPrj Java Application Project with the followingha
m )
characteristics: o
Project Name: BankPrj a ilฺc ฺ
@ gm uide
Project Location: projects
2 1 1 nt G
Project Folder: projects/BankPrj
t 9 20 tude
Set as Main Project: No sain i s S
N ( et h
Create Main Class:
T R A No
t o us
B EL– JavansDevelopment:
e
Tool Reference
O l i c e Java Classes: Modifying Java

R EN Copying
Classes:
b l e Java Classes
M O2. fCopy
e ra the pre-provided Account.java source file from the
A RO -trans resources/01_intro/exercise2 directory to the source
GEN non package of the BankPrj project.

Task 2 – Creating the TestAccount Class


In this task, you complete the following steps to create a new
TestAccount 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
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)

2. Edit the source file for the TestAccount class to add a main
method. The main method of the TestAccount class creates an
Account object with an initial balance of 100. It deposits 50 to and
then withdraws 147 from the Account object. Finally, it must print
out the balance of the Account object to the standard output stream.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
Run the TestAccount program. If there are runtime errors, make

ail eฺ
necessary changes to the TestAccount class, recompile it, and run the
program again.
g m id
@ G u
0
The output of the TestAccount program should2 11be similar
e n t to the
following:
n t 9 2
S t ud
( sai this
Final account balance
R ANis:u3.0se
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

hints.

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
2 2 den
in0this exercise:
Tool Reference – Tool references used
i n t 9 S tu
a thisProjects: Creating Projects
Java Development: Java(sApplication


R
Java Development:AN u se Copying Existing Resources
Java Classes:
E LT seJavatoClasses: Creating Java Classes

O B en
Java Development:

E Java

l e lic
N Development: Java Classes: Modifying Java Classes: Compiling
R
O fera Java b
Classes
M
A RO -trans Java
● Development: Java Classes: Modifying Java Classes: Executing

GEN non Java Programs

Demonstration – The demonstration for this exercise can be found in the


1 demos/01_intro/exercise2 directory.
2
3

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: projects
Project Folder: projects/BankPrj
s a
Set as Main Project: No ) h a
c o m
Create Main Class: No ฺ
ail eฺ
g m id
@ G u
Tool Reference – Java Development: Java Classes:
Classes: Copying Java Classes 0 2 11 ent
Modifying Java

t 9 2 t u d
n S
( sai thdirectory
2. Copy the pre-provided Account.java
issource file from the
to the source
ANproject. se
resources/01_intro/exercise2
R
package of the BankPrj u
E LT se to
O B en
N le lthe
Task 2 – Creating
E ic TestAccount Class
M OR ferab
A nstask, you complete the following steps to create a new
RO -Intrathis
G EN non TestAccount Java class.
Tool Reference – Java Development: Java Classes: Creating Java Classes
1. Create a Java class with the following characteristics:
Class Name: TestAccount
Project: BankPrj
Location: Source Packages
Package: default package
2. Add the main method.
3. Declare a variable in the main method. The variable has a type of
Account and a name of acct. Initialize the variable by creating an
instance of the Account class with an initial balance of 100.

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

standard 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
g m
necessary changes to the TestAccount class, recompile it and run the
id
program again. @ G u
0 2 11 ent
t
The output of the TestAccount program9 2 shouldtubed similar to the
a i n i s S
following: s h
A N ( use t
R to is: 3.0
Final accountTbalance
L
B E nse
N O lice
O RE rable
O M sfe
A R -tran
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

hints with code 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 2 02exercise:
this u d en
i n t 9 S t
a i s
(s e thProjects: Creating Projects
Java Development: Java Application

N us Copying Existing Resources
A Classes:
Java Development:RJava

T t o
B EL nJava
Java Development:
● seClasses: Creating Java Classes
e
O lic Java Classes: Modifying Java Classes: Compiling
NDevelopment:
E
Java

RJava Classes
b le
O
M sfer a
O
R -tranJava● Development: Java Classes: Modifying Java Classes: Executing
A
G EN non Java Programs

Demonstration – The demonstration for this exercise can be found in the


1 demos/01_intro/exercise2 directory.
2
3

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: projects
Project Folder: projects/BankPrj
s a
Set as Main Project: No ) h a
c o m
Create Main Class: No ฺ
ail eฺ
m
gModifying idJava
@ G u
Classes: Copying Java Classes 0 2 11 ent
Tool Reference – Java Development: Java Classes:

t 9 2 t u d
n S
( sai this directory
2. Copy the pre-provided Account.java source file from the
to the source
package of the R A N
resources/01_intro/exercise2
u s e
project.
L T BankPrjt o
B E nse
Task 2 E–N
O licethe TestAccount Class
Creating
O R rable
O M sfe
A R -traInnthis task, you complete the following steps to create a new
GEN non TestAccount Java class.
Tool Reference – Java Development: Java Classes: Creating Java Classes
1. Create a Java class with the following characteristics:
Class Name: TestAccount
Project: BankPrj
Location: Source Packages
Package: default package
2. Add the main method to the TestAccount class:
public class TestAccount {
public static void main(String[] args) {
// code here
}
}

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

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


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
) h a
Task 3 – Compiling the TestAccount Class c o m

ail eฺ
m
gchangesutoidcorrect
Compile the TestAccount class, and make necessary
1 @
1 nt G
compilation errors. 2
20 tude
t 9
in is S
s a
( e th Program
Task 4 – Running the TestAccount N
T R A
t o us
B
Run the TestAccountEL program.
n se If there are runtime errors, make
e
O tolicthe TestAccount class, recompile it and run the
necessaryNchanges
E
R again. b le
program
O
M sfer a
O
R -Ther anoutput of the TestAccount program should be similar to the
A t
G EN non following:
Final account balance is: 3.0

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

Object-Oriented Programming
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Objectives
Upon completion of this lab, you should be able to:
● Use the Java API documentation to research a class s a
Explore information hiding and encapsulation ) h a

c o m
Use packages to organize your classes
● ฺ
ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non

Lab 2-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Using the Java API Documentation

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
n t G
116 APIeSpecification
1. Open the Java™ Platform, Standard Edition
2 0 2 d
Web
page in the browser.
i n t9 Stu
( sa this
R se Platform SE 6 can be found at
AN foruJava
LT se to
Note – The API documentation
E
http://java.sun.com/javase/6/docs/api.
B en
O lic package in the package list in the upper-left
N the java.text
E
2. Select l e
M ORcorner
e r a b
panel of the API frameset.
R sf the NumberFormat class in the class list in the lower-left panel.
O 3.ranSelect
A t
G EN non- 4. Read about the class in the top part of the documentation window
on the right panel of the frameset. Review the format and parse
methods.

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

this version, you create an Account class with public data members. You
will then create a test program that demonstrates the danger of using the
public data directly.

Figure 2-1 shows the UML class diagram of the Account class that you
will create in this exercise. This class will have one public data member
(or instance variable), called balance, that maintains the monetary value
of the customer’s bank account.

Account
s a
+balance : double ) h a
c o m
«constructors» ฺ
ail eฺ
+Account(initBalance:double)
g m id
@ G u
Figure 2-1 UML Class Diagram of Account
0 2 11WitheNo
n t Hiding
n t 9 2
S t ud
i applies
sathat is to the Account class: The
(
There is only one business rule t h
A
balance of the bank account
R u sego below zero. In this exercise, you will
Nmust never
LT se class
discover that the Account
E to cannot ensure this business rule.
O B en
N lecontains
This exercise
E lic the following sections:
M OR f“Task
e
● rab1 – Deleting the Account Class”
A RO -trans “Task 2 – Creating the Account Class”

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 projectsha
m )
directory. o
a ilฺc ฺ
gmcan be e in the
idfound
Demonstration – The demonstration for this exercise
@ G u
demos/02_OOP/exercise2 directory. 11 n t
1
2
20 tude
2
3 t 9
in is S
s a
( e th
A N us
Task 1 – Deleting T
L seR
the t o
Account Class
E
B en
O
N le lic
E
R Referenceb – Java Development: Other Files: Deleting Files
M OTool e r a
R O ransf
A t In this task, you delete the Account class copied in Lab 1.
G EN non-
Task 2 – Creating the Account Class
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
s a
standard output stream.
) h a
c o m
Task 4 – Compiling the TestAccount2 Class

ail eฺ
g m id
@ G u
0
In this task, you compile the TestAccount2 2 11class,eand
n t make necessary
n t 9
changes to correct compilation errors. 2
S t ud
( sai this
Task 5 – Running the
R AN u se Program
L T e toTestAccount2
O BE ens
Ntask, lyou
In this c the TestAccount2 program.
lirun
E e
M OR ferab
R O raThen soutput should be similar to the following:
A t
GEN non- Final account balance is -3.0

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 tin
n S t ud
2this exercise:
( sai Deleting
Java Development: Other Files: t h isFiles
ANClasses:seCreating Java Classes

R u

E LT se to
Java Development: Java

O B enJava Classes: Modifying Java Classes: Compiling
Java Development:
E
JavaNClassesle lic
M ORJavafeDevelopment:
● rab Java Classes: Modifying Java Classes: Executing
O s
R -tranJava Programs
A
G EN non For this exercise, you work in the BankPrj project in the projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/02_OOP/exercise2 directory.
2
3

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
a i nt is St
2. Add the balance instance variable.
s the balance
3. Add a constructor that(sets th instance variable to the
A N s e
TR e to u
initial balance argument passed to the constructor.
L
O BE ens
Task 3 E–N Creatingl e lic the TestAccount2 Class
M OR ferab
RO -traIn s task, you complete the following steps to create a Java class named
nthis
A
GEN non TestAccount2:
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.

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)

c. Use the subtraction operator to subtract 150 from the account


object’s balance.
d. Use the System.out.println method to display the balance to
the standard output stream.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 4 – Compiling the TestAccount2 Class


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


s a
In this task, you run the TestAccount2 program. ) h a
c o m
The output should be similar to the following:

ail eฺ
g m id
@ G u
Final account balance is -3.0
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

code snippets.

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
c o m
Preparation ฺ
ail eฺ
g m id
@ G u
No preparation is needed for this exercise.211 n t
2 0 ud e
n t 9 S t
sai usedthinisthis exercise:
Tool Reference – Tool references
(

R
Java Development:ANOther u se Deleting Files
Files:
E LT seJavatoClasses: Creating Java Classes

O B en
Java Development:

E ●Java
l e lic
N Development: Java Classes: Modifying Java Classes: Compiling
R
O fera Java b
Classes
M
A RO -trans Java
● Development: Java Classes: Modifying Java Classes: Executing

GEN non Java Programs

For this exercise, you work in the BankPrj project in the projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/02_OOP/exercise2 directory.
2
3

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
a i nt is St
2. Add the balance instance variable.
public double balance;
N (s e th
3. Add a constructorR A sets theusbalance to the initial balance
E
T that
L to thee to
argument passed
B en s constructor.
public Account(double O
N le lic
initBalance) {
E
} M OR ferab
balance = initBalance;

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
c o m
6. ฺ
ail eฺ
Use the System.out.println method to display the balance to the
standard output stream. g m id
@ G u
System.out.println(“Final account balance is ”
0 2 11+ acct.balance);
e n t
n t 9 2
S t ud
Task 4 – Compiling the TestAccount2 ( sai this Class
A N us e
T R t o
Lcompilesethe TestAccount2 class and the Account class,
B E
In this task, you
n
and make
N O necessary
l i c e changes to correct compilation errors.

O RE rable
O M 5s–feRunning the TestAccount2 Program
Task
A R -tran
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

methods to manipulate the balance. You then use the test program that
you created in Lab 1 to test that the business rule (balance must not fall
below zero) is satisfied.

Figure 2-2 shows the UML class diagram of the Account class that you
create. This design for the Account class hides the instance variable,
balance, and supplies public methods to manipulate the account balance.
The deposit method adds money to the account. The withdraw method
removes money from the account. The getBalance method returns the
current value of the balance instance variable.
s a
) h a
Account
c o m
-balance : double

ail eฺ
g m id
@ G u
11 ent
«constructors»
+Account(initBalance:double)
0 2
«methods»
n t 9 2
S t ud
+getBalance():double
( s ai this
+deposit(amt:double):void N
R A u se
LT se to
+withdraw(amt:double):void

E
B Class nDiagram of Account With Information Hiding
Figure 2-2 UML
O l i c e
R EN ble
M O ferathere is still one business rule that must be maintained: The
Remember,

A t r nsof the bank account must never go below zero. This business rule
RO -balance
a
G EN non should be enforced in the withdraw method.
This exercise contains the following sections:
● “Task 1 – Modifying the Account Class”
● “Task 2 – Modifying the TestAccount Class”
● “Task 3 – Compiling the TestAccount Class”
● “Task 4 – Running the TestAccount Program”

Preparation
There is no preparation for this exercise.

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 projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/02_OOP/exercise3 directory.
2
3 s a
) h a
c o m
Task 1 – Modifying the Account Class ฺ
ail eฺ
g m id
@ G u
11 file.
In this task, you modify the Account class2source
0 e n tThis class must
9
satisfy the UML diagram in Figure 2-2.
n t 2
S t ud
( sai this
Task 2 – Modifying Rthe u se
ANTestAccount Class
L T e to
E ns
O Byoulimodify
In thisNtask, ce the TestAccount class to deposit 47 to and
O RE rab150lefrom the Account object.
withdraw

O M sfe
A R -tran
GEN noTask
n 3 – Compiling the TestAccount Class
In this task, you compile the TestAccount class and the Account class.

Task 4 – Running the TestAccount Program


In this task, you run the TestAccount program. The output should be
similar to the following:
Final account balance is 147.0

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”

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

Java Classes (
ANClasses:
Java Development:RJava u seModifying Java Classes: Executing
LT se to

Java Programs E
B en
O
N leyou licwork in the BankPrj project in the projects
E
For this exercise,
M OR ferab
directory.

A RO -trans
G EN non Demonstration – The demonstration for this exercise can be found in the
1 demos/02_OOP/exercise3 directory.
2
3

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

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)

3. Add the withdraw method that takes an amount (of type double)
and subtracts that amount from the balance. Save the new balance in
the instance variable.
This operation might set the balance to a value below zero if the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

amount to withdraw is larger than the current balance. You must use
a conditional statement to verify that the amount is not greater than
the balance before doing the subtraction. The conditional statement
looks like the following:
if ( <boolean_test> ) {
<statement_when_true>*
} else {
<statement_when_false>*
}
4. Add the getBalance method to return the balance instance s a
variable. ) h a
c o m

ail eฺ
Task 2 – Modifying the TestAccount Class g m id
@ G u
0 2 11 ent
9
In this task, you complete the following
t d the TestAccount
2 steps totumodify
n S
class:
( sai this
1. Change the amount
R seto the deposit method to 47.0.
ANin theucall
T eintothe call to the withdraw method to 150.0.
Lamount
2. Change the E
B ens
O
N le lic
E
M OR
Task
f r a b
3 – eCompiling the TestAccount Class
A RO -trans
GEN non In this task, you compile the TestAccount class and the Account class.
Task 4 – Running the TestAccount Program
In this task, you run the TestAccount program. The output should be
similar to the following:
Final account balance is 147.0

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

code snippets.

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
h a
Preparation m )
ฺ c o
a il
There is no preparation for this exercise. g m i d eฺ
1 1 @ t Gu
Tool Reference – Tool references used 2in u en
02this exercise:
d
i n t 9 S t
Java Development: Java
● a
(sClasses: i s
thModifying Java Classes: Compiling
Java Classes A N us e
T R t o
L seJava Classes: Modifying Java Classes: Executing

B E
Java Development:
n
O
Java Programs
l i c e
R EN ble
M e raexercise, you work in the BankPrj project in the projects
OFor fthis
A ns
RO -tradirectory.
G EN non Demonstration – The demonstration for this exercise can be found in the
1 demos/02_OOP/exercise3 directory.
2
3

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

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)

2. Add the deposit method that takes an amount (of type double) and
adds that amount to the balance. Save the new balance in the
balance instance variable.
public void deposit(double amt) {
balance = balance + amt;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

}
3. Add the withdraw method that takes an amount (of type double)
and subtracts that amount from the balance. Save the new balance in
the balance instance variable.
public void withdraw(double amt) {
if ( amt <= balance ) {
balance = balance - amt;
}
} a
4. Add the getBalance method to return the balance instance ) h
as
variable. c o m

ail eฺ
public double getBalance() {
g m id
return balance; @ G u
}
0 2 11 ent
n t 9 2
S t ud
( s ai this
Task 2 – Modifying theNTestAccount s e Class
A u
L TR e to
In this task,B E complete
you n s the following steps to modify the TestAccount
class: N O lic e
E l e
M O1.R fChange
e rab the amount in the call to the deposit method to 47.0.
A RO -trans
acct.deposit(47.0);

GEN non 2. Change the amount in the call to the withdraw method to 150.0.
acct.withdraw(150.0);

Task 3 – Compiling the TestAccount Class


In this task, you compile the TestAccount class and the Account class.

Task 4 – Running the TestAccount Program


In this task, you run the TestAccount program. The output should be
similar to the following:
Final account balance is 147.0

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

ail eฺ
Account
-balance : double m
@ g u id
+main(args:String[])
11 ent
«constructors» G
0 2
n t 2
S t ud
+Account(initBalance:double)
9
( sai +getBalance():double
t h is
«methods»

R AN use+deposit(amt:double):void
E LT se to +withdraw(amt:double):void
O B en
E N le lic
M OR 2-3
Figure
e r a b Package Structure of the Banking Project
The
R O ransf
A t
G EN non-This exercise contains the following sections:
● “Task 1 – Creating the Java Packages”
● “Task 2 – Moving and Modifying the Account Class”
● “Task 3 – Moving the TestAccount Class”
● “Task 4 – Compiling the TestAccount Class”
● “Task 5 – Running the TestAccount Program”

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
) h a
o m
For this exercise, you work in the BankPrj project in the projects
c
directory. ฺ
ail eฺ
g m id
@
1 ncan G u
Demonstration – The demonstration for this1exercise
2 e t be found in the
demos/02_OOP/exercise4 directory.
9 2 0 ud
1
n t S t
sai this
2
3 (
R AN use
E LT se to
Task 1 – Creating
O B ethe n Java Packages
l i c
R EN ble
M O fera
R O raTool
n s Reference – Java Development: Java Packages: Creating Java
A t Packages
GEN non-
In this task, you create two Java Source Packages in the BankPrj project
with the following names:
com.mybank.domain
com.mybank.test

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)

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

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

package com.mybank.domain;

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:
1. Move the TestAccount class source file to the com.mybank.test
package.
s a
2. Add the following package statement at the top of the
) h a
TestAccount class:
c o m
package com.mybank.test;

ail eฺ
m id in
g statement
@ G u
the TestAccount class: 0 2 11 ent
3. Add the following import statement under the package

n t 9 2
S t ud
sai this
import com.mybank.domain.Account;
(
R AN use
Task 4 – Compiling LTthesTestAccount
e to Class
E
B en
In this E
O lic the TestAccount class and the Account class.
N youlecompile
task,
M OR ferab
O rans
RTask
A t5 – Running the TestAccount Program
G EN non-
In this task, you run the TestAccount program. The code has not
changed, so the output should be similar to the following:
Final account balance is 147.0

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

Identifiers, Keywords, and Types


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

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
s a
+y : int

) h a
+toString() : String
c o m
il ฺ
Figure 3-1 UML Class Diagram for the MyPointgClass ma ideฺ
1 1 @ t Gu
02explores
d n references.
eobject
9 2
Your task is to create a test program that
u
a i nt is St
(s e sections:
This exercise contains the following
N th
T
“Task 1 – CreatingR t o us
A the TestMyPoint Class”

L e
E ns the TestMyPoint Class”
“TaskB
N

O l i ce
2 – Compiling

O RE “Task

a b 3le– Running the TestMyPoint Program”

O M sfer
A - t an
R Preparation
r
G EN non
No preparation is needed for this exercise.

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


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

Demonstration – The demonstration for this exercise can be found in the


1 demos/03_types/exercise1 directory.
2
3
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 1 – Creating the TestMyPoint Class

Tool Reference – Java Development: Java Application Projects: Opening


Projects

Complete the following steps:


s a
1. Open the PointProject project in the
) h a
exercises/03_types/exercise1 directory.
c o m

ail eฺ
2. Create the TestMyPoint class with the following characteristics:
g m id
Class Name: TestMyPoint @ G u
Project: PointProject 0 2 11 ent
n t 9 2
S t ud
Location: Source Packages
( s ai this
Package: default N packagee
R A s
ucomplete
3. Create a main T
L semethod,t o
and the following steps in the main
B en
method: E
O
N Declare lictwo variables of type MyPoint and called start and
Ea. l e
M OR feraend.
b Assign both of these variables a new MyPoint object.
A RO -trans b. Set the x and y values of start to 10. Set the x value of end to
GEN non 20 and the y value to 30.
c. Print out both point variables. Use code similar to:
System.out.println("Start point is " + start);
d. To make sure that you are using the MyPoint class correctly,
you might want to compile and run TestMyPoint now (see
“Task 2 – 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.

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

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

Task 2 – Compiling the TestMyPoint Class


In this task, you compile the TestMyPoint class.

Task 3 – Running the TestMyPoint Program


In this task, you run the TestMyPoint program.
s a
The output should look similar to the following: ) h a
c o m
Start point is [10,10] ฺ
ail eฺ
End point is [20,30] g m id
@ G u
Stray point is [20,30] 0 2 11 ent
End point is [20,30]
n t 9 2
S t ud
( s ai this
Stray point is [47,50] N
R A u se
End point is [47,50]
LT se to
Start point isE[10,10]
O B en
The R EN reported
l e licby end reflect the change made in stray, indicating
rab refer to the same MyPoint object. However, start has
values
M O bothfevariables
that
A RO -not
t r a ns
changed, which indicates that it is independent of the other two

G EN non variables.

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 s a
-lastName : String
-balance : double

) h a
-account : Account
c o m
«constructors»

ail eฺ
+Account(initBalance:double)
«constructors»
«methods»
g m id
+Customer(f:String, l:String)
@ G u
11 ent
+getBalance():double
«methods»
0 2
+deposit(amt:double):void
+getFirstName():String
n t 9 2 t ud
+withdraw(amt:double):void
S
sai this
+getLastName():String
+getAccount():Account (
+setAccount(acct:Account):void
R AN use
E LT se to
O
Figure 3-2 BUML eClass
n Diagram for the Customer Class
l i c
R EN ble
M e ra contains the following sections:
OThis fexercise
A RO -trans “Task 1 – Creating the Customer Class”
EN non

G ● “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: Copying Existing Resources
● 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 projects ha
m )
directory. o
a ilฺc ฺ
Demonstration – The demonstration for this exercise can
@ u idein the
gmbe found
1 demos/03_types/exercise2 directory.
2 1 1 nt G
2
t 9 20 tude
3
s a in is S
N ( e th
R A
o us
Task 1 – Creating E the
T
L se t
Customer Class
O B en
In this E
task, lic the Customer class to satisfy the UML diagram in
N youlecreate
M OR 3-2.
Figure
e r a
The
bclass has the following characteristics:
R sf Name: Customer
O ranClass
A t
G EN non- Project: BankPrj
Location: Source Packages
Package: com.mybank.domain

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

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

Preparation s a
) h a
c o m
No preparation is needed for this exercise. ฺ
ail eฺ
g m id
@ G u
Tool Reference – Tool references used in this2
0 11 ent
exercise:
t 9 2 Java
Java Development: Java Classes:nCreating S t udClasses
sai Copying

(
Java Development: Java Classes: t h is Existing Resources
ANClasses: seModifying Java Classes: Compiling

R u

E LT se to
Java Development: Java
B en
Java Classes
O
E
Java

l e lic Java Classes: Modifying Java Classes: Executing
NDevelopment:
M ORJavafePrograms
rab
A RO -For
t r ns exercise, you work in the BankPrj project in the projects
athis
G EN non directory.
Demonstration – The demonstration for this exercise can be found in the
1 demos/03_types/exercise2 directory.
2
3

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 id the
g variables;
4. Declare two public accessors for the object instance
@ G u
methods getFirstName and getLastName
0 2 11 return
e n t the appropriate
instance variable.
n t 9 2
S t ud
ai thtoisretrieve the account instance
5. Declare the getAccountsmethod
(
variable.
R AN use
T e tomethod to assign the account instance
6. Declare theLsetAccount
E
B ens
variable.
O
N le lic
E
M OR ferab
R OTask a
2 s– Copying the TestBanking Class
n
A tr
GEN non- In this task, you copy the TestBanking.java file from the
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

additional hints with code 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
2 2 den
in0this exercise:
Tool Reference – Tool references used
i n t 9 S tu
a tCreating
Java Development: Java(sClasses:
● h is Java Classes

R AN
Java Development: u se Copying Existing Resources
Java Classes:
E LT seJavatoClasses: Modifying Java Classes: Compiling

O B en
Java Development:

E N le lic
Java Classes

M OR fJava

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

R O rans Java Programs


A t
GEN non- For this exercise, you work in the BankPrj project in the projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/03_types/exercise2 directory.
2
3

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
3. Declare a public constructor that takes1 @
1 nt
two G u
parameters (f 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
O two
4. Declare
N l i e accessors for the object instance variables; the
cpublic
O RE methods
r a b le getFirstName and getLastName return the appropriate
O M sfeinstance 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
resources/03_types/exercise2 directory into the com.mybank.test
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
m )
ฺ c o
ail should
In this task, you run the TestBanking program. The output
m eฺ be
similar to the following: g
@ t Gu i d
1 1
Creating the customer Jane Smith.02
2 u d en
Creating her account with a 500.00
i 9
nt is St
balance.
Withdraw 150.00 a
(s e th
Deposit 22.50
A N us
Withdraw 47.62 TR o
EL nJane] t
B
Customer [Smith,
e se has a balance of 324.88
E NO le lic
M OR ferab
A RO -trans
GEN non

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

Expressions and Flow Control


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

Objectives
Upon completion of this lab, you should be able to:
● Use a simple for loop s a
Using conditional statements in business logic ) h a

c o m

ail operation
(Optional) Use nested loops to implement a string search
eฺ

g m i d
1 1 @ t Gu
9 2 02 uden
a i nt is St
N (s e th
T R A
t o us
B EL nse
N O lice
O RE rable
O M sfe
A R -tran
GEN non

Lab 4-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Using Loops and Branching Statements

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
( sai this
AN use
12 foo
13 R
LT se to
14 baz
E
B en
O
15 foo bar
N le lic
16E
M OR ferab
A RO -and
t r ansoson.
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
exercises/04_stmts/exercise1 directory.
c o m

ail eฺ
m d in the
g can beuifound
Demonstration – The demonstration for this exercise
demos/04_stmts/exercise1 directory. 11
@ t G
1
0 2 e n
2
n t 9 2
S t ud
sai this
3
(
R AN use
Task 1 – CreatingE to
LTtheseFooBarBaz Class
O B en
E
Complete lic steps:
N thelefollowing
M O1.R fOpen
e rabthe LoopProject project in the
A RO -trans exercises/04_stmts/exercise1 directory.
GEN non 2. Create the FooBarBaz class with the following characteristics:
Class Name: FooBarBaz
Project: LoopProject
Location: Source Packages
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.

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 2 – Compiling the FooBarBaz Class


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

Task 3 – Running the FooBarBaz Program


In this task, you run the FooBarBaz program.

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

Hints
s a
These hints might help you to solve this exercise: ) h a
c o m

a l print
Use the System.out.print method to print a string or ivalue
eฺ

without printing a new line character. You can use g m
multiplei d
methods to print a single line of text. You can1 @ G uprintln
use a single
method, with no arguments, to print a0new
1 en t
2 linedcharacter.
9 2 u

a i
The % operator calculates an integer
i s St
nt remainder.
N (s e th
T R A
t o us
B EL nse
N O lice
O RE rable
O M sfe
A R -tran
G EN non

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

value to 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
has-a 1
) h a
Customer
c o mAccount
-firstName : String -balance : double ฺ
ail eฺ
-lastName : String
g m id
«constructors»
@ G u
11 ent
-account : Account
+Account(initBalance:double)
0 2
«constructors»
n t 9 2
«methods»
S t ud
sai +deposit(amt:double):boolean
+Customer(f:String, l:String)
«methods» ( t is
+getBalance():double
h
A N use+withdraw(amt:double):boolean
+getFirstName():String
+getLastName():String R
LT se to
+getAccount():Account E
B en
O
N le lic
+setAccount(acct:Account):void
E
R rab
M OFigurefe4-1 UML Class Diagram of Banking Project
O n s
N AR n-tra
GE no This exercise contains the following sections:
● “Task 1 – Modifying the Account Class”
● “Task 2 – Deleting the Current TestBanking Class”
● “Task 3 – Copying the TestBanking Class”
● “Task 4 – Compiling the TestBanking Class”
● “Task 5 – Running the TestBanking Program”

Preparation
There is no preparation required for this exercise.

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

● 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 projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/04_stmts/exercise2 directory. s a
2 ) h a
3
c o m

ail eฺ
g m id
Task 1 – Modifying the Account Class @ G u
0 2 11 ent
t 9 2 t u d
n S
i class source
is file. This class must
satisfy the UML diagram in Figure( sa4-1.
In this task, you modify the Account
Inth
particular, the deposit and
withdraw methods must R return se value as described previously
AN a boolean
u
in this exercise. ELT e to
B en s
O
N le lic
E
Task 2O–RDeleting
r a b the Current TestBanking Class
M
O ransf e
A R t this task, you delete the current TestBanking class in the
G EN non-In
com.mybank.test package of the BankPrj project.

Task 3 – Copying the TestBanking Class


In this task, you copy the new version of the TestBanking.java file from
the 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.

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)

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
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
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 2
There is no preparation required for this exercise.
n t 9 2
S t ud
(
Tool Reference – Tool references
ai intthis
sused h isexercise:
AN Files:u e
sDeleting

L R
T e to
Java Development: Other Files
BE enJava
Java Development:

O
s Classes: Copying Existing Resources
E l e lic Java Classes: Modifying Java Classes: Compiling
NDevelopment:
ORJavafeClasses
Java
rab

M s Development: Java Classes: Modifying Java Classes: Executing


A RO -tranJava

G EN non Java Programs

For this exercise, you work in the BankPrj project in the projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/04_stmts/exercise2 directory.
2
3

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

1. Modify the deposit method. Because an account has no upper limit,


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


a
m )
inilthe
In this task, you delete the current TestBanking class a
o
ฺc ฺ
com.mybank.test package of the BankPrj project.
@ gm uide
2 1 1 nt G
Task 3 – Copying the TestBanking t 9 20 Class
t u de
s a in is S
N ( e th
T R
In this task, you copy the
t o us of the TestBanking.java file from
A new version
B ELproject.
the resources/04_stmts/
n s e directory into the com.mybank.test package
O lice
of the BankPrj
N
O RE rable
O M 4s–feCompiling the TestBanking Class
Task
A R -tran
N on
GE n 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:
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

boolean 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 2
There is no preparation required for this exercise.
n t 9 2
S t ud
(
Tool Reference – Tool references
ai intthis
sused h isexercise:
AN Files:u e
sDeleting

L R
T e to
Java Development: Other Files
BE enJava
Java Development:

O
s Classes: Copying Existing Resources
E l e lic Java Classes: Modifying Java Classes: Compiling
NDevelopment:
ORJavafeClasses
Java
rab

M s Development: Java Classes: Modifying Java Classes: Executing


A RO -tranJava

G EN non Java Programs

For this exercise, you work in the BankPrj project in the projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/04_stmts/exercise2 directory.
2
3

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

1. Modify the deposit method. Because an account has no upper limit,


this 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
s a
the withdraw operation is successful and must return true;
) h a
c o m
otherwise the operation fails and the method must return false.
public boolean withdraw(double amt) { ฺ
ail eฺ
g m id
boolean result = false; // assume operation failure
@ G u
if ( amt <= balance ) {
0 2 11 ent
balance = balance - amt;
n t 9 2
S t ud
sai this
result = true; // operation succeeds
} (
return result;
R AN use
}
E LT se to
O B en
E N le lic
TaskOR2 – Deleting
a b the Current TestBanking Class
M e r
R O ransf
A t In this task, you delete the current TestBanking class in the
GEN non- com.mybank.test package of the BankPrj project.

Task 3 – Copying the TestBanking Class


In this task, you copy the new version of the TestBanking.java file from
the 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 s a
previous exercises for this module. ) h a
c o m

ail eฺ
g m id
Preparation @ G u
0 2 11 ent
n
There is no preparation requiredifor S tud
2 exercise.
t9this
( sa this
N usused
Areferences e in this exercise:
Tool Reference – ToolR
LT se to
E
B en Java Application Projects: Opening Projects
Java Development:

O lic
N Development:
E Java
R Java

b l e Java Classes: Modifying Java Classes: Compiling
O
M sfer aClasses
O
R -tran Java Development: Java Classes: Modifying Java Classes: Executing
A ●

GEN non Java Programs

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


exercises/04_stmts/exercise3 directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/04_stmts/exercise3 directory.
2
3

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)

Task 1 – Writing the isSubString Method


In this task, you open the AdvancedLoopProject project in the
exercises/04_stmts/exercise3 directory, open the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.

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

s a
) h a
c o m
There is an easy way to do this by using the indexOf method of the

ail eฺ
String class. You can determine if a String s is a substring of some
g m
String x by evaluating the expression x.indexOf(s) != -1. However,
id
@ G u
the purpose of this exercise is to practice using loops, so you should solve
2 11 ent
the problem by using only the charAt method and nested loops.
0
n t 9 2
S t ud
( s ai this
Task 2 – Compiling the TestIsSubString
N use Class
A
L TR e to
E nthe
Bcompile
In this task, you s TestIsSubString class.
O
N le lic e
E
R rab
TaskM3O– Running
s fe the TestIsSubString Program
O n
N AR n-tra
G E no In this task, you run the TestIsSubString program. The output of the
program should be similar to the example shown in ‘‘Task 1 – Writing the
isSubString Method’’ on page L4-14.

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

a specific character from a string; the index starts with zero. For
example. "cat".charAt(0) is ‘c’, "cat".charAt(1) is ‘a’, and
"cat".charAt(2) is ‘t’.
● The length method returns the number of characters in the string;
for example, "cat".length() is 3.

s a
) h a
c o m

ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non

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

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

Objectives
Upon completion of this lab, you should be able to:
● Declare, create, and manipulate one-dimensional primitive arrays s a
Use an array to represent a one-to-many object relationship ) h a

c o m

ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non

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

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

0 2 11Opening
e n t Projects
t 9 2 Java
Java Development: Java Classes:nCreating S t udClasses
sai Modifying

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

Java Classes R
LT Java to
E s e
O B licen
Java Development:
● Classes: Modifying Java Classes: Executing
JavaN Programs
O RE rable
O e
MFor thissfexercise, you work in the ArrayProject project in the
tra n
AR n-exercises/05_arrays/exercise1 directory.
E N
G no Demonstration – The demonstration for this exercise can be found in the
1 demos/05_arrays/exercise1 directory.
2
3

Task 1 – Creating the TestArrays Class


Complete the following steps:
1. Open the ArrayProject project in the
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 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-4) to display these s a
integer arrays. ) h a
c o m
6. ฺ
ail eฺ
Assign the array2 variable equal to the array1. Modify the even
g m
indexed element in array2 to be equal to the index value (for
id
@ u
example, array2[0] = 0; and array2[2] = 2; and so on). Print
G
out array1.
0 2 11 ent
n t 9 2
S t ud
( s ai this
Task 2 – Compiling the N TestArrays
s e Class
A u
L TR e to
In this task,B E compile
you n s the TestArrays class.
O
N le lic e
E
M OR
Task rab
3 s–feRunning the TestArrays Program
O n
N AR n-tra
GE no In this task, you run the TestArrays program. The output should be
similar to the following:
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-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)

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

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-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 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ฺ
g
Tool Reference – Tool references used in this exercise: m id
@ G u
● Java Development: Java Application 2
0 11 eOpening
Projects: n t Projects
t 9 d Classes
2CreatingtuJava

n
Java Development: Java Classes:
ai his S
Java Development: Java(s
Classes:tModifying Java Classes: Compiling

A N s e
T e to u
Java Classes R
L

O BE ens Java Classes: Modifying Java Classes: Executing
Java Development:

E N le lic
Java Programs
R rab
OFor
O M
n s fe exercise, you work in the exercises/05_arrays/exercise1
this

N AR n-tradirectory.
GE no Demonstration – The demonstration for this exercise can be found in the
1 demos/05_arrays/exercise1 directory.
2
3

Task 1 – Creating the TestArrays Class


Complete the following steps:
1. Open the ArrayProject project in the
exercises/05_arrays/exercise1 directory.

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 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;
s a
}
// insert code here
) h a
c o m
} ฺ
aitol theefirst
ฺ eight
m
4. Using the curly-brace notation, {}, initialize array1
g i d
@ t Gu
prime numbers: 2, 3, 5, 7, 11, 13, 17, and119.
1
int[] array1 = { 2, 3, 5, 7, 11, 13, 17,
9 2 0192 };uden
int[] array2;
a i nt is St
s
of( array1. h might want to use the
tYou
N
5. Display the contents e
s on page L5-4) to display these
A (seeu‘‘Hint’’
T R
printArray method
t o
EL nse
integer arrays.
B
N O liceis ");
System.out.print("array1
RE rable
printArray(array1);
O
M sfe
System.out.println();
O
A R -tran6. Assign the array2 variable equal to the array1. Modify the even
G EN non 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.
array2 = 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-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)

Task 2 – Compiling the TestArrays Class


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

Task 3 – Running the TestArrays Program


In this task, you run the TestArrays program. The output should be
similar to the following:
array1 is <2, 3, 5, 7, 11, 13, 17, 19>
array1 is <0, 3, 2, 7, 4, 13, 6, 19>

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

bank and 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-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 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: Copying Existing Resources
● Java Development: Java Classes: Modifying Java Classes: Compiling
Java Classes
● Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs s a
) h a
c o m
directory.

For this exercise, you work in the BankPrj project in the projects
ail eฺ
g m id
@
1 ncan G u
Demonstration – The demonstration for0this2 1exercise
e t be found in the
1 demos/05_arrays/exercise2 directory.
n t 9 2
S t ud
2
( s ai this
3
R AN use
E LT se to
Task 1 – Creating
O B ethe n Bank Class
l i c
R EN ble
M OIn this
f e ra you create the Bank class that must satisfy the UML diagram
task,
s 5-1 on page L5-8. The class has the following characteristics:
RO -trainnFigure
A
GEN non Class Name: Bank
Project: BankPrj
Location: Source Packages
Package: com.mybank.domain

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.

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)

Task 3 – Copying the TestBanking Class


In this task, you copy the TestBanking.java file from the
resources/05_arrays directory to the com.mybank.test source
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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


s a
)
In this task, you run the TestBanking program. The output should be h a
o m
ilฺc ฺ
similar to the following:
a
Customer [1] is Simms, Jane
@ gm uide
Customer [2] is Bryant, Owen
2 1 1 nt G
20 tude
Customer [3] is Soley, Tim
Customer [4] is Soley, Maria t 9
in is S
s a
( e th
A N us
T R t o
B EL nse
N O lice
O RE rable
O M sfe
A R -tran
N on
GE n

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

bank and 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
( used
Tool Reference – Tool references
N e thin this exercise:
T R
Java Development: t o us Creating Java Classes
A Java Classes:
EL nseOther Files: Deleting Files

B
O lice
Java Development:

N
O REJava

a b le
Development: Java Classes: Copying Existing Resources

O M sfJavaer Development: Java Classes: Modifying Java Classes: Compiling


A R -tran Java Classes


GEN non Java Development: Java Classes: Modifying Java Classes: Executing

Java Programs

For this exercise, you work in the BankPrj project in the projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/05_arrays/exercise2 directory.
2
3

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 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
) h a
some appropriate maximum size (at least bigger than five).
c o m
4. Add the addCustomer method. This method must construct

ail aenew ฺ
Customer object from the parameters (first name and g m last u i d
name) and
place it on the customers array. It must also
@
11increment G
t the
0 2 e n
numberOfCustomers instance variable.
n t 9 2
S t ud
5. Add the getNumOfCustomers s i
aaccessor ismethod, which returns the
( t h
R AN use
numberOfCustomers instance variable.
LT semethod.
6. Add the getCustomer
E to This method returns the customer
associatedBwith then given index parameter.
O l i c e
R EN ble
Task
M 2 f ra the Current TestBanking Class
O– Deleting
e
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
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-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)

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

bank and 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 A
t o us Creating Java Classes
Java Classes:
EL nOther

B
Java Development:e se Files: Deleting Files

O lic
NDevelopment:
E
R rable
Java
● Java Classes: Copying Existing Resources
O
M Java feDevelopment: Java Classes: Modifying Java Classes: Compiling
O n●
s
N AR n-tra Java Classes
G E no Java Development: Java Classes: Modifying Java Classes: Executing

Java Programs

For this exercise, you work in the BankPrj project in the projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/05_arrays/exercise2 directory.
2
3

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 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
3. Add a public
E e to that initializes the customers array with
LTconstructor
s
B en maximum size (at least bigger than five).
some appropriate
O
N le lic
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-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)

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
ail eฺ
resources/05_arrays directory to the com.mybank.test source
m
package of the BankPrj project.
@ g u id
11 ent G
0 2
Task 4 – Compiling the TestBanking n t 9 2 Class
S t ud
( sai this
In this task, you compile
R the se class.
ANTestBanking
u
E LT se to
O B en
Task 5 – Running
E N le lthe ic TestBanking Program
M OR ferab
A RO -In
t r a nstask, you run the TestBanking program. The output should be
this

G EN non similar to the following:


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

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

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

Objectives
Upon completion of this lab, you should be able to:
● Create subclasses with inheritance and overriding of methods s a
Create a heterogeneous collection and use polymorphism ) h a

c o m

ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non

Lab 6-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Creating Bank Account Subclasses (Level 1)

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

types have 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
s a
amount of overdraft protection. The account’s overdraft amount is
) h a
decremented as it is used.
c o m

ail etheฺ
g
Figure 6-1 shows the UML class diagram for a design that m id
satisfies
@ G u
business rules described above.
0 2 11 ent
n t 9 2
S t ud
com.mybank.domain
( sai this
R AN use
E LT se to
Account
B : edouble
#balance
O n
l i c
R EN «constructors»
b le
O a
M sfer«methods»
#Account(initBalance:double)
O
R -tran
A
N on +getBalance():double
G E n +deposit(amt:double):boolean
+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”
“Task 3 – Creating the CheckingAccount Class”
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

● “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
There is no preparation for this exercise. ) h a
c o m

ail eฺ
g m
Tool Reference – Tool references used in this exercise: id
@ G u

0 2 11JavaeClasses
Java Development: Java Classes: Creating n t
n
2
Java Development: Other Files:t9Deleting
S t ud
Files
ai his Existing Resources

Java Development: Java(sClasses:tCopying


AN se Modifying Java Classes: Compiling

R u

E LT se to
Java Development: Java Classes:
B en
Java Classes
O
E●Java
l e lic
N Development: Java Classes: Modifying Java Classes: Executing
R
O fera Java b
Programs
M
A nsthis exercise, you work in the BankPrj project in the projects
RO -traFor
GEN non directory.
Demonstration – The demonstration for this exercise can be found in the
1 demos/06_class1/exercise1 directory.
2
3

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

diagram in Figure 6-1 on page L6-2; in particular, the balance instance


variable and Account class constructor are now protected (indicated by the
# character instead of the - character).

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
following characteristics:
s a
Class Name: SavingsAccount ) h a
c o m
Project: BankPrj ฺ
ail eฺ
g m id
Extends: Account
@ G u
Location: Source Packages
0 2 11 ent
Package: com.mybank.domain int9
2
S tud
( sa this
R
This class must satisfy the u se in Figure 6-1 on page L6-2 and
N diagram
AUML
LT sinethetointroduction to ‘‘Exercise 1: Creating
the business rules defined
E
B en(Level 1)’’ on page L6-2.
Bank Account Subclasses
O
E N le lic
M OR ferab
Task
O 3ra–nCreating
s the CheckingAccount Class
A R t
G EN non-In this task, you 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
Extends: Account
Location: Source Packages
Package: com.mybank.domain

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.

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 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
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
In this task, you runR AN
the u se program. The output should be
LT se to
TestBanking
similar to the E
following:
O B en
N le lSmith.
Creating the customer
E Jane ic
R raAccount
Ocustomer
Creating her Savings b with a 500.00 balance and 3% interest.
M
Creating the e
sf Account with a 500.00 balance and no overdraft
OhisraChecking Owen Bryant.
R n
NA on-t
Creating
Eprotection.
n
G 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.

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

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 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
Retrieving the customer Maria Soley with her joint checking account with
c o m
husband Tim. ฺ
ail eฺ
Deposit 150.00: true
g m id
@ G u
11 ent
Withdraw 750.00: false
Customer [Soley, Maria] has a balance of 150.0
0 2
n t 9 2
S t ud
i
sachecking isaccount behave
Jane’s savings account and Owen’s
( t h
fundamentally as a basic bank
R ANworth seoverdraft
account.
u But Tim and Maria’s joint
checking account hasT
L 500.00
e t o of protection. Tim’s
transactions dip E thatnprotection
Binto s and therefore his ending balance
is 0.00. His O
N account’sl ic e
overdraft protection level is 424.88. Finally, Maria
E
R 150.00
deposits e
blshe
into this joint account; raising the balance from 0.00
toO
Mthe balance
150.00.
f e r a
Then tries to withdraw 750.00, which fails because neither
O
R -tran s nor the overdraft protection can cover that requested amount.
A
G EN non

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
s i this
There is no preparation for thisaexercise.
(
N use
Areferences
Tool Reference – T
L R
Tool
t o used in this exercise:
e
BE ens Java Classes: Creating Java Classes
Java Development:

O lic
N Development:
E
R rab
● Java l e Other Files: Deleting Files
O
M sfJava e Development: Java Classes: Copying Existing Resources
O n ●

N AR n-tra Java Development: Java Classes: Modifying Java Classes: Compiling


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

For this exercise, you work in the BankPrj project in the projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/06_class1/exercise1 directory.
2
3

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)

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

Complete the following steps:


1. Change the balance instance variable from private to protected.
2. Change the Account constructor from public to protected.

Task 2 – Creating the SavingsAccount Class


In this task, you create the SavingsAccount class source file in the
s a
com.mybank.domain source package of the BankPrj project.
) h a
c o m
Complete the following steps: ฺ
ail eฺ
g m id
1. Create the SavingsAccount class source file in @the G u
com.mybank.domain source package of 2
0 11BankPrj
the e n t project with
the following characteristics:
n t 9 2
S t ud
Class Name: SavingsAccount ( sai this
N use
Project: BankPrj RA
E LT se to
B en
Extends: Account
O
E N Source
Location: l e lic Packages
M ORPackage:
f e r a b
com.mybank.domain
O n s
N AR n-t2.ra Add the interestRate instance variable to the SavingsAccount
G E no class.
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.

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
Extends: Account
s a
Location: Source Packages
) h a
c o m
Package: com.mybank.domain ฺ
ail eฺ
2. Add the overdraftAmount instance variable to g m
the id
@ G u
CheckingAccount class.
0 2 11 ent
3. Add a public constructor that takes
and overdraftAmount. Passinthe
tud parameter
t92initBalance
two arguments:
S
initBalance

s a h i s
super constructor. Save(the overdraftAmount
t
to the
parameter to the
A N s e
TR e to u
instance variable.
L
4. Add aB E public
second
n s constructor that takes only one argument:
N O l
initBalance. ic eCall the first constructor with the initBalance
E e
bl and use the default value 0.0 for the overdraftAmount
R parameter
O
M sfe r a
parameter.
O
R -tra5.n Override the withdraw method to use the overdraftAmount
A
GEN non variable. Here is the pseudo-code for the withdraw method:
if balance < amount
then
overdraftNeeded = amount - balance
if overdraftAmount < overdraftNeeded
then transaction fails
else
balance = 0
decrement overdraftAmount by overdraftNeeded
else
decrement balance by amount

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
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 t ud
Program
S
( sai this
AN use program. The output should be
In this task, you run theRTestBanking
E LT se to
similar to the following:
Creating the customerNJane O BSmith.
l i cen
O
Creating her SavingsRE Account
a b le with a 500.00 balance and 3% interest.
r Bryant.
Creating the M
O customers f eOwen
A
Creating
- t an Account with a 500.00 balance and no overdraft
Rhis Checking
r
EN non
protection.
G
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.

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.
(
R AN used u sein this exercise:
E LT se to
Tool Reference – Tool references

O B enJava Classes: Creating Java Classes
Java Development:
E l e lic Other Files: Deleting Files
NDevelopment:
ORJavafeDevelopment:
rab
Java

M
O rans ● Java Classes: Copying Existing Resources
A R t
G EN non- Java ● Development: Java Classes: Modifying Java Classes: Compiling
Java Classes
● Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs

For this exercise, you work in the BankPrj project in the projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/06_class1/exercise1 directory.
2
3

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)

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

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.
protected Account(double initBalance) {
balance = initBalance;
}
s a
) h a
Task 2 – Creating the SavingsAccount Class com
lฺ ai eฺ
m
g fileuiind the
In this task, you create the SavingsAccount class
1 @ source
t G
1 nproject.
com.mybank.domain source package of the 2
20 tude
BankPrj
t 9 S
Complete the following steps:sain i s
N ( usclass h
e t source file in the
A
1. Create the SavingsAccount
L TR e source
com.mybank.domain to package of the BankPrj project with
E s
B echaracteristics:
the following n
O
N Name: l i c
R EClass b le SavingsAccount
O a
er BankPrj
M sfProject:
O
R -tran Extends: Account
A
N on
GE n Location: Source Packages
Package: com.mybank.domain
package com.mybank.domain;
public class SavingsAccount extends Account {
// 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) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

super(initBalance);
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. a
h a s
Complete the following steps: m )
ฺ c o
1. Create the CheckingAccount class source file in the ail
g eฺ
m projectidwith
the following characteristics: 1 1 @ t Gu
com.mybank.domain source package of the BankPrj

Class Name: CheckingAccount t92


02 uden
a i n is St
Project: BankPrj
N (s e th
Extends: Account RA
T t o us
Location: B EL nPackages
Source se
e
NO com.mybank.domain
lic
E
Package: l e
M OR ferab
package com.mybank.domain;
R
public class
A t r a ns
O CheckingAccount extends Account {
//Ninsert n
E -
code here
G
} no
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) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

this(initBalance, 0.0);
}
5. Override the withdraw method to use the overdraftAmount
variable.
public boolean withdraw(double amount) {
boolean result = true;
if ( balance < amount ) {
double overdraftNeeded = amount - balance;
if ( overdraftAmount < overdraftNeeded ) {
s a
result = false;
) h a
} else {
c o m
balance = 0.0; ฺ
ail eฺ
overdraftAmount -= overdraftNeeded; g m id
@ G u
}
} else { 0 2 11 ent
balance -= amount;
n t 9 2
S t ud
}
( sai this
return result;
R AN use
}
E LT se to
O B en
Task R 4E–N Deleting
l e lic the Current TestBanking Class
M O ferab
s
RO -traInnthis
N A n
task, you delete the current TestBanking class in the
GE no com.mybank.test source package of the BankPrj project.

Task 5 – Copying the TestBanking Class


In this task, you copy the TestBanking.java file from the
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.

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 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:
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
s a
protection.
Creating the customer Tim Soley. ) h a
c o m
overdraft protection.

Creating his Checking Account with a 500.00 balance and 500.00 in
ail eฺ
g m id
Creating the customer Maria Soley.
@ G u
2 11 ent
Maria shares her Checking Account with her husband Tim.
0
2
t9savings d
tuaccount.
n
Retrieving the customer Jane Smith with iher S
Withdraw 150.00: true ( sa this
Deposit 22.50: true R AN use
Withdraw 47.62: true
E LT se to
Withdraw 400.00: false B e n
O
N has
Customer [Simms,EJane] l i c
R b l e a balance of 324.88
O fera Owen Bryant with his checking account with no
RetrievingMthe customer
A
overdraft t ans
RO -protection.
r
N on150.00: true
EWithdraw
G n
Deposit 22.50: true
Withdraw 47.62: true
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

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

aggregation of 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 Customer R
LT With to or More Different Accounts
One
E
B en s e
N O licthe Customer class to support a heterogeneous
E
Your job is to modify
l e
M OR feofraAccount
collection b objects.

RO -This s
anexercise
A t r contains the following sections:
G EN non ● “Task 1 – Modifying the Customer Class”
● “Task 2 – Copying and Completing the CustomerReport Class”
● “Task 3 – Copying the TestReport Class”
● “Task 4 – Compiling the TestReport Class”
● “Task 5 – Running the TestReport Program”

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: Copying Existing Resources
● 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 projectsha
m )
directory. o
a ilฺc ฺ
Demonstration – The demonstration for this exercise
@ de in the
gmcan beuifound
demos/06_class1/exercise2 directory.11 n t G
1
2
20 tude
2
3 t 9
in is S
s a
( e th
A N us
Task 1 – Modifying T
L seR the t o
Customer Class
E
B en
O
Ntask, lyou c
limodify
E
In this e
R rab of the BankPrj the Customer class in the com.mybank.domain
M O source package
f e project. Modify the Customer class to

A ns the association with multiple accounts, just as you did in the


RO -trahandle
EN non addAccount(Account), getAccount(int), and getNumOfAccounts().
Exercise 2 of Lab 5. It must include the public methods:
G
Task 2 – Copying and Completing the CustomerReport
Class
Complete the following steps:
1. Create the com.mybank.report source package in the BankPrj
project.
2. Copy the CustomerReport.java file from the
resources/06_class1 directory into the com.mybank.report
source package of the BankPrj project.

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)

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.

Task 3 – Copying the TestReport Class


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

In this task, you copy the TestReport.java file from the


resources/06_class1 directory into the com.mybank.test source
package of the BankPrj project.

Task 4 – Compiling the TestReport Class


s a
In this task, you compile the TestReport class.
) h a
c o m
il ฺ
Task 5 – Running the TestReport Programgma ideฺ
1 1 @ t Gu
In this task, you run the TestReport program.
2 02 The
u d en should be
output
similar to the following: i 9
nt is St
a
(s e thREPORT
NCUSTOMERS
us
A ================
T R t o
B EL nse
Customer:O
N Simms, c
l i e
Jane
E bAccount:
RSavings le current balance is 500.0
M O e r
Checking
f a Account: current balance is 200.0

A t r ans Bryant, Owen


RO -Customer:
G EN non 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
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

aggregation of 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ฺ
Preparation g m id
@ G u
0 2 11 ent
There is no preparation required for
n t 9
this S t ud
2 exercise.
( sai this
Tool Reference – ToolA N usused
references e in this exercise:
R
LT seJavatoPackages: Creating Java Packages
● E
B en
Java Development:
O lic
N Development:
R E ●Java
b l e Java Classes: Copying Existing Resources

M O fJava

e raDevelopment: Java Classes: Modifying Java Classes: Compiling
A RO -trans Java Classes
GEN non ●Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs

For this exercise, you work in the BankPrj project in the projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/06_class1/exercise2 directory.
2
3

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)

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

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:


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.
s a
2. Modify the constructor to initialize the accounts array.
) h a
3. o m
Add the addAccount method. This method takes a single parameter,
c

ail eฺ
an Account object, and stores it in the accounts array. It must also
g m id
increment the numberOfAccounts instance variable. This method
@ G u
0 2 11 ent
replaces the setAccount method, which should be removed.
4. Add the getNumOfAccounts accessor
n t 9 2method,
S t udwhich returns the
numberOfAccounts instance a i
s variable. is
( t h
N uThis
5. Add the getAccountAmethod.
R se method returns the account
T given
associated withLthe
e o parameter. This method replaces the
tindex
E s
B en method, which should be removed.
previous getAccount
O
N le lic
E
TaskM O–RCopying
2 f e r a b
and Completing the CustomerReport
O n s
N ARClass
n - tra
G E no
Complete the following steps:
1. Create the com.mybank.report source package in the BankPrj
project.
2. Copy the CustomerReport.java file from the
resources/06_class1 directory into the com.mybank.report
source package of the BankPrj project.

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

is and 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
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
1
In this task, you compile the TestReport2class.
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
In this task,B ELrun ntheseTestReport program. The output should be
you
N
similar Othe output
to l i ce listed on page L6-20.
O RE rable
O M sfe
A R -tran
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

aggregation of 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ฺ
Preparation g m id
@ G u
0 2 11 ent
There is no preparation required n t
for 9this S t ud
2 exercise.
( sai this
N usused
Tool Reference – ToolAreferences e in this exercise:
R
LT seJava to Packages: Creating Java Packages
E
B en
Java Development:

N O lic
R E Java Development:

b l e Java Classes: Copying Existing Resources

M O feJava ra Development: Java Classes: Modifying Java Classes: Compiling


A RO -trans Java Classes


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

Java Programs

For this exercise, you work in the BankPrj project in the projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/06_class1/exercise2 directory.
2
3

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)

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

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:


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.
s a
private Account[] accounts;
private int numberOfAccounts; ) h a
c o m

ail eฺ
2. Modify the constructor to initialize the accounts array.
g m id
public Customer(String f, String l) {
@ G u
firstName = f;
0 2 11 ent
lastName = l;
n t 9 2
S t ud
sai this
// initialize accounts array
accounts = new Account[10]; (
numberOfAccounts = 0;
R AN use
}
E LT se to
O B addAccount
e n method. This method takes a single parameter,
3. Add the
N Account l i c
R Ean b le object, and stores it in the accounts array. It must also
M O f e r a
increment the numberOfAccounts instance variable. This method

A RO -trans replaces the setAccount method, which should be removed.


GENpublic
non
void addAccount(Account acct) {
int i = numberOfAccounts++;
accounts[i] = acct;
}
4. Add the getNumOfAccounts accessor method, which returns the
numberOfAccounts instance variable.
public int getNumOfAccounts() {
return numberOfAccounts;
}
5. Add the getAccount method. This method returns the account
associated 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];
}

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)

Task 2 – Copying and Completing the CustomerReport


Class
Complete the following steps:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1. Create the com.mybank.report source package in the BankPrj


project.
2. Copy the CustomerReport.java file from the
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 of the code that you must supply.
s a
a. Use the instanceof operator to test what type of account this
) h a
c o m
is and set account_type to an appropriate value, such as

ail eฺ
Savings Account or Checking Account.
g m id
if ( account instanceof SavingsAccount ) {
@ G u
account_type = "Savings Account";
0 2 11 e)n{t
n t 2
} else if ( account instanceof CheckingAccount
9 S t ud
sai this
account_type = "Checking Account";
} else { (
account_type = "Unknown
R ANAccount
u seType";
}
E LT se to
B outethe
b.O Print n type of account and the balance.
l i c
R EN ble
System.out.println(" " + account_type + ": current balance is "
O
M sfe r a + account.getBalance());
O
R -tran
A
G EN non Task 3 – Copying the TestReport Class
In this task, you copy the TestReport.java file from the
resources/06_class1 directory into the com.mybank.test source
package of the BankPrj project.

Task 4 – Compiling the TestReport Class


In this task, you compile the TestReport class.

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 2: Creating a Heterogeneous Collection of Customer Accounts (Level 3)

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

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)

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.

s a
TestBatch
) h a
c o m

ail eฺ
g m id
@ G u
AccumulateSavingsBatch
0 2 11 CustomerReport
e n t
-bank : Bank
t 9 2 -banktu: dBank
a i n i s S
«methods» s h
( e t +generateReport():void
«methods»
+doBatch():void
A N us
L T R
+setBank(bank:Bank):void
t o +setBank(bank:Bank):void

B E nse
N O lice
O RE rablSavingsAccount
e
O M sfe
A R -tran-interestRate : double
G EN non «constructors»
+SavingsAccount(initBalance:double,
interestRate:double)

«methods»
+accumulateInterest():void

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”
● “Task 5 – Running the TestBatch Program”

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)

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 Classes: Creating Java Classes
● Java Development: Java Classes: Copying Existing Resources
● Java Development: Java Classes: Modifying Java Classes: Compiling
Java Classes
● Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs
s a
For this exercise, you work in the BankPrj project in the projectsha
m )
directory. o
a ilฺc ฺ
gm uide
Task 1 – Modifying the SavingsAccount 1 1 Class
@ t G
2 n
t 9 20 tude
A savings account gains interest.in
a The bank
i s S
permits customers to store
s h
money in a savings account (and, on at monthly basis, the savings account
will accumulate basedR u se formula: balance = balance +
AonNthe following
LT s/e12)).
(balance * (interestRate
E to
O B en
Ntask, lyou c the accumulateInterest method to perform this
liadd
E
In this
R rab e
M Ooperation.
fe
O n s
N AR n-tra
GE noTask 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
The class must conform to the specification defined in Figure 6-3 on
page L6-28.
2. Add an instance variable bank of the type Bank.

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)

3. Add a setBank method to set the method parameter to the bank


instance variable.
4. Add a doBatch method using the following hints:
for each Customer in the Bank do
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

for each Account in the Customer do


if the Account is a SavingsAccount,
then call the accumulateInterest method

Task 3 – Copying the TestBatch Class


In this task, you copy the TestBatch.java file from the
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 TestBatch Class ฺ
ail eฺ
g m id
@ G u
In this task, you compile the TestBatch class.11 n t
0 2 e
n t 9 2
S t ud
Task 5 – Running the TestBatch ( sai tProgram
h is
R AN use
E Lthe e to program. The output should be
T TestBatch
In this task, you run
B en s
O
N le lic
similar to the following:
E
M OR ferab CUSTOMERS REPORT

R O rans ================
A t
G EN non-Customer: Simms, Jane
Savings Account: current balance is 500.0
Checking Account: current balance is 200.0

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
Savings Account: current balance is 150.0

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 3: Creating a Batch Program (Advanced)

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


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

ail eฺ
Checking Account: current balance is 200.0
m id
Savings Account: current balance is 150.625
g
@ 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-31


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

Advanced Class Features


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

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

o m
properties of these types of components
a ilฺc ฺ
@ gm uide
2 1 1 nt G
t 9 20 tude
s a in is S
N ( e th
T R A
t o us
B EL nse
N O lice
O RE rable
O M sfe
A R -tran
GEN non

Lab 7-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Applying Static Members to a Design (Level 1)

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

the concept of a bank, which contains the set of customers for the bank.
The project team has decided that this is a risky design because it would
be possible to instantiate multiple Bank objects each with the potential to
contain different sets of customers.

The design team has decided to make the Bank class a utility class. A
utility class is one that is not instantiated and all of its members are static.
Figure 7-1 shows the new design for the Bank class. Your job is to program
these changes to the Bank class and to all of the classes that use the Bank
class.
s a
) h a
c o m
com.mybank.domain ฺ
ail eฺ
g m id
@ G u
Bank
0 2 11 ent
-customers : Customer[]
t 9 2 t u d
n S
-numberOfCustomers : int
( sai this
«constructors»
R AN use
-Bank()
E LT se to
«methods»
O B en
E N le lic
+addCustomer(f:String, l:String)

OR ferab
+getNumOfCustomers():int

M
+getCustomer(index:int):Customer

A RO -trans
G EN non serves
has-a 1
Customer Account
0..*

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: Copying Existing Resources
● Java Development: Java Classes: Modifying Java Classes: Compiling
Java Classes
● Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs s a
) h a
c o m
directory.

For this exercise, you work in the BankPrj project in the projects
ail eฺ
g m id
@
1 ncan G u
Demonstration – The demonstration for0this 2 1exercise
e t be found in the
1 demos/07_class2/exercise1 directory.
n t 9 2
S t ud
2
( s ai this
3
R AN use
E LT se to
Task 1 – Modifying
O B enthe Bank Class
E N le lic
M OInRthis
f e r a
task,
b
you open the BankPrj project in the projects directory,
O n s
N AR n-traand modify the Bank class in the com.mybank.domain source package of

GE no the BankPrj project. All the members (both instance variables and
methods) should be changed to static, as shown in Figure 7-1 on
page L7-2. Also, move the original variable initialization code from the
constructor to either a static block or on the static variable declarations.

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.

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

Task 4 – Copying the TestReport Class


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

Task 5 – Compiling the TestReport Class a


h a s
m )
In this task, you compile the TestReport class.
ฺ c o
m ail eฺ
@ g u id
Task 6 – Running the TestReport Program 2 11 ent G
9 2 0 ud
n t S t
( s ai program.
In this task, you run the TestReport
t h is The output should be
N utests
similar to the output from previous
A s e as shown in Exercise 2, Task 5 of
Lab 6 (Level 1).
L TR e to
O BE ens
E N le lic
M OR ferab
A RO -trans
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

the concept of a bank, which contains the set of customers for the bank.
The project team has decided that this is a risky design because it would
be possible to instantiate multiple Bank objects each with the potential to
contain different sets of customers.

The design team has decided to make the Bank class a utility class. A
utility class is one that is not instantiated and all of its members are static.
Figure 7-1 on page L7-2 shows the new design for the Bank class. Your job
is to program these changes to the Bank class and to all of the classes that
use the Bank class.
s a
) h a
This exercise contains the following sections:
c o m
“Task 1 – Modifying the Bank Class”

ail eฺ

m
@
“Task 2 – Modifying the CustomerReport1Class”

g
G uid
0 2 1 ent

t 9 2
“Task 3 – Deleting the Current TestReport
t u d
Class”
n S
sai thClass”
“Task 4 – Copying the TestReport

( is
“Task 5 – Compiling

R se Class”
ANthe TestReport
u
LT sthe
“Task 6 –ERunning
● e o
tTestReport Program”
B e n
E NO le lic
OR ferab
Preparation
M
A RO -trans
GEN non There is no preparation required for this exercise.
Tool Reference – Tool references used in this exercise:
● Java Development: Java Application Projects: Opening Projects
● Java Development: Other Files: Deleting Files
● Java Development: Java Classes: Copying Existing Resources
● Java Development: Java Classes: Modifying Java Classes: Compiling
Java Classes
● Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs

For this exercise, you work in the BankPrj project in the projects
directory.

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)

Demonstration – The demonstration for this exercise can be found in the


1 demos/07_class2/exercise1 directory.
2
3
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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 methods) should be changed to static, as shown in Figure 7-1 on
page L7-2.

Complete the following steps: s a


) h a
1. m
Open the BankPrj project in the projects directory if you have
c o
closed it.
a il ฺ
2. Open the Bank class in the com.mybank.domain source g m i
packaged eฺ of
the BankPrj project. 1 1 @ t Gu
9 2 02 uden
St
3. Change all instance variables to static.
i n t
s a
4. Move the original variable(initialization i s
th codedeclarations.
from the constructor to
either a static block or A N
on the
us e
static variable
T R t o
L seto be private and remove the body of the
5. Change the E constructor
O B
constructor. e n
l i c
6. R EN all
Change b lemethods to static.
O
M sfer a
O
R -tran
A
G EN Task
non
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.

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.

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

Task 4 – Copying the TestReport Class


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

Task 5 – Compiling the TestReport Class a


h a s
m )
In this task, you compile the TestReport class.
ฺ c o
m ail eฺ
@ g u id
Task 6 – Running the TestReport2Program 11 ent G
9 2 0 ud
n t S t
( s ai thprogram.
In this task, you run the TestReport is The output should be
similar to the output from
A Nprevious
u s etests as shown in Exercise 2, Task 5 of
Lab 6 (Level 1).
L TR e to
O BE ens
E N le lic
M OR ferab
A RO -trans
GEN non

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

the concept of a bank, which contains the set of customers for the bank.
The project team has decided that this is a risky design because it would
be possible to instantiate multiple Bank objects each with the potential to
contain different sets of customers.

The design team has decided to make the Bank class a utility class. A
utility class is one that is not instantiated and all of its members are static.
Figure 7-1 on page L7-2 shows the new design for the Bank class. Your job
is to program these changes to the Bank class and to all of the classes that
use the Bank class.
s a
) h a
This exercise contains the following sections:
c o m
“Task 1 – Modifying the Bank Class”

ail eฺ

g m id
@ G u
“Task 2 – Modifying the CustomerReport

0 2 11 ent
Class”

t 9 2
“Task 3 – Deleting the Current TestReport
t u d
Class”
n S
sai thClass”
“Task 4 – Copying the TestReport

( is
“Task 5 – Compiling

R se Class”
ANthe TestReport
u
“Task 6 E
● LT sethetoTestReport Program”
– Running
O B en
E N le lic
OR ferab
Preparation
M
A RO -trans
G EN non There is no preparation required for this exercise.
Tool Reference – Tool references used in this exercise:
● Java Development: Java Application Projects: Opening Projects
● Java Development: Other Files: Deleting Files
● Java Development: Java Classes: Copying Existing Resources
● Java Development: Java Classes: Modifying Java Classes: Compiling
Java Classes
● Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs

For this exercise, you work in the BankPrj project in the projects
directory.

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)

Demonstration – The demonstration for this exercise can be found in the


1 demos/07_class2/exercise1 directory.
2
3
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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 methods) should be changed to static, as shown in Figure 7-1 on
page L7-2.

Complete the following steps: s a


) h a
1. m
Open the BankPrj project in the projects directory if you have
c o
closed it.
a il ฺ
2. Open the Bank class in the com.mybank.domain g m d eฺ of
source ipackage
the BankPrj project. 1 1 @ t Gu
2 02 uden
3. Change all instance variables to9static.
private static Customer[] customers;sai
nt is St
N ( e th
private static int
T R A
t o us
numberOfCustomers;

either B
EL block
4. Move the original
a static e n
variable initialization code from the constructor to
seor on the static variable declarations.
static { E NO le lic
M
customersO=Rnewe r a b
Customer[10];
O ransf = 0;
numberOfCustomers
R
}A t
GEN non- 5. Change the constructor to be private and remove the body of the
constructor.
private Bank() {
// this constructor should never be called
}
6. Change all methods to static.
public static void addCustomer(String f, String l) {
int i = numberOfCustomers++;
customers[i] = new Customer(f, l);
}
public static int getNumOfCustomers() {
return numberOfCustomers;
}
public static Customer getCustomer(int customer_index) {
return customers[customer_index];
}
Advanced Class Features Lab 7-9
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Applying Static Members to a Design (Level 3)

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
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 this Fish
e : String
AN us-name
-name : String R
LT se to «constructors»
«constructors» E
B en
«constructors»
+Spider()
N O
+Cat(n:String)
l ic +Fish()
«methods» E
R rabl
+Cat() e «methods»
+eat():void O f e
M s«methods» +getName():String
O
R -tran +getName():String +setName(n:String):void
A
N on +play():void
G E n
+setName(n:String):void
+play():void +walk():void
+eat():void +eat():void

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
) h a
exercises/07_class2/exercise2 directory. o m
a ilฺc ฺ
Demonstration – The demonstration for this exercise
@ de in the
gmcan beuifound
demos/07_class2/exercise2 directory.11 n t G
1
2
20 tude
2
3 t 9
in is S
s a
( e th
A N us
Task 1 – Creating T R
the t
Pet o
L se Interface
E
B en
O lic steps:
N thelefollowing
E
Complete
M O1.R fOpen
e rabthe InterfaceProject project in the
A RO -trans exercises/07_class2/exercise2 directory.
N on 2. Create the Pet interface with the following characteristics:
GE n
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.

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
s a
for the Animal class might say something similar to This animal walks
) h a
o
on 4 legs, where 4 is the value of the legs instance variable.
c m
l ฺ
aiPackages
g m
2. Create the Spider, Cat, and Fish classes in the Source
i d eฺ of
the InterfaceProject project to satisfy the UML
1 1 @ t Gu
diagram in
Figure 7-1 on page L7-2.
9 2 02 uden
a i nt is St
Task 3 – Creating the TestAnimals
N (s e th Class
T R A
t o us
B EL nsteps:
Complete the following se
NOtask,leyou e
liccreate the TestAnimals class with the following
1. InEthis
M ORcharacteristics:
e r a b
R sf Name: TestAnimals
O ranClass
A t
G EN non- Project: InterfaceProject
Location: Source Packages
Package: default package
2. Add the main method to create and manipulate instances of the
classes you created previously.
Start with:
Fish d = new Fish();
Cat c = new Cat("Fluffy");
Animal a = new Fish();
Animal e = new Spider();
Pet p = new Cat();

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” m
ฺ c o
“Task 4 – Compiling the TestAnimals Class”

m ail eฺ
“Task 5 – Running the TestAnimals Program”@g
● u id
11 ent G
0 2
t 9 2
S t ud
Preparation n
sai this
( e
R AN forusthis
L T e to
There is no preparation required exercise.

O BE ens
N l–eTool
Tool Reference
E lic references used in this exercise
M ORJavafeDevelopment:
● rab Java Application Projects: Opening Projects
O s
R -tranJava Development: Java Classes: Creating Java Classes
A ●

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


exercises/07_class2/exercise2 directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/07_class2/exercise2 directory.
2
3

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)

Task 1 – Creating the Pet Interface


Complete the following steps:
1. Open the InterfaceProject project in the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

exercises/07_class2/exercise2 directory.
2. Create the Pet interface with the following characteristics:
Class Name: Pet
Project: InterfaceProject
Location: Source Packages
Package: default package

s a
The Pet interface must satisfy the UML diagram in Figure 7-1 on
page L7-2. ) h a
c o m

ail eฺ
Task 2 – Creating the Animal Classes@g m id
G u
0 2 11 ent
Complete the following steps:
n t 9 2
S t ud
(
1. Create the abstract Animal saiclass.this
R AN classu sewith the following characteristics:
a.
LT se to
Create the
E
Animal

O B Name:
Class e n Animal
l i c
R EN Project:
b le InterfaceProject
O a
M sfer Location: Source Packages
O
R -tran
A
EN non
Package: default package
G b. Declare a protected integer instance variable called legs, which
records the number of legs for this animal.
c. Define a protected constructor that initializes the legs instance
variable.
d. Declare an abstract method eat.
e. Declare a concrete method walk that prints out something
about how the animals walks (include the number of legs).

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ฺ

Extends: Animal
Location: Source Packages
Package: default package
b. Define a no-arg constructor that calls the superclass
constructor to specify that all spiders have eight legs.
c. Implement the eat method.
3. Create the Cat class.
s a
a. Create the Cat class with the following characteristics: ) h a
c o m
Class Name: Cat ฺ
ail eฺ
g m id
Project: InterfaceProject
@ G u
Extends: Animal
0 2 11 ent
n t 9 2
S t ud
Implements: Pet
( s ai this
Location: SourceNPackages
R A u se
Package: L
E
default to
T e package
B e s
ninclude a String instance variable to store the
O
b. This class must
l i c
R ENnameb l e the pet.
of
M ra a constructor that takes one String parameter that
O c. feDefine
A RO -trans specifies the cat’s name. This constructor must also call the
G EN non superclass constructor to specify that all cats have four legs.
d. Define another constructor that takes no parameters. Have this
constructor call the previous constructor (using the this
keyword) and pass an empty string as the argument.
e. Implement the Pet interface methods.
f. Implement the eat method.
4. Create the Fish class.
a. Create the Fish class with the following characteristics:
Class Name: Fish
Project: InterfaceProject
Extends: Animal

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)

Implements: Pet
Location: Source Packages
Package: default package
b. This class must include a String instance variable to store the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

name 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 c o m

ail eฺ
g m id
Complete the following steps: @ G u
0 2 11classewith
n t the following
ud
1. In this task, you create the TestAnimals
t 9 2 t
characteristics: n S
Class Name: TestAnimals ( sai this
R AN use
LT se to
Project: InterfaceProject
E
B Source
Location:
O e n Packages
l i c
N ledefault package
R EPackage:
M e rabthe main method to create and manipulate instances of the
O2. f.Add
A RO -trans classes you 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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

abstract 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” a
“Task 4 – Compiling the TestAnimals Class” h a s

m )
“Task 5 – Running the TestAnimals Program” ฺ c o
ail eฺ

g m id
@ G u
Preparation
0 2 11 ent
n t 9 2
S t ud
( saifor this
There is no preparation required
t h isexercise.
R AN use
Tool Reference L
E –T to used in this exercise:
Tool references
e
s
B en Java Application Projects: Opening Projects
● O
N le lic
Java Development:
E
M OR fJava

e
b
raDevelopment: Java Classes: Creating Java Classes

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

GEN non Java Classes


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

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


exercises/07_class2/exercise2 directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/07_class2/exercise2 directory.
2
3

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)

Task 1 – Creating the Pet Interface


Complete the following steps:
1. Open the InterfaceProject project in the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

exercises/07_class2/exercise2 directory.
2. Create the Pet interface with the following characteristics:
Class Name: Pet
Project: InterfaceProject
Location: Source Packages
Package: default package

s a
The Pet interface must satisfy the UML diagram in Figure 7-1 on
page L7-2. ) h a
c o m
public interface Pet { ฺ
ail eฺ
public String getName(); g m id
@ G u
public void setName(String n);
0 2 11 ent
ud
public void play();
t 9 2 t
} n S
( sai this
A N use
Task 2 – Creating L R
the
T Animal to Classes
E
B en s e
O lic steps:
Nthe following
E
Complete
R rab l e
M1.O Create
f e the Animal class.
O s
R -trana. Create the Animal class with the following characteristics:
A
N on
GE n Class Name: Animal
Project: InterfaceProject
Location: Source Packages
Package: default package
public abstract class Animal {
// more code here
}
b. Declare a protected integer instance variable called legs, which
records the number of legs for this animal.
protected int legs;
c. Define a protected constructor that initializes the legs instance
variable.

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)

protected Animal(int legs) {


this.legs = legs;
}
d. Declare an abstract method eat.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

public abstract void eat();


e. 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.");
}
2. Create the Spider class.
a. Create the Spider class with the following characteristics:
s a
Class Name: Spider
) h a
Project: InterfaceProject
c o m

ail eฺ
Extends: Animal
g m id
@ G u
Location: Source Packages
0 2 11 ent
Package: default package
n t 9 2
S t ud
sai the
b. The Spider class extends
( t h is class.
Animal
public class Spider extends Animal
R AN{ use
// more code here L T e to
} E
B ens
O
N Define lica no-arg constructor that calls the superclass
E c. l e
M OR feraconstructor
b to specify that all spiders have eight legs.
ROSpider()
public
A t r a ns {
-
EN super(8);
G } non
d. Implement the eat method.
public void eat() {
System.out.println("The spider eats a fly.");
}
3. Create the Cat class.
a. Create the Cat class with the following characteristics:
Class Name: Cat
Project: InterfaceProject
Extends: Animal
Implements: Pet

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)

Location: Source Packages


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

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) {
super(4);
name = n;
}
d. Define another constructor that takes no parameters. Have this s a
constructor call the previous constructor (using the this ) h a
c o m
keyword) and pass an empty string as the argument.

ail eฺ
public Cat() {
g m id
this(""); @ G u
}
0 2 11 ent
n
e. Implement the Pet interface t 9 2
methods. S t ud
public String getName() { ( sai this
return name;
R AN use
}
E LT se to
public void setName(String
O B n) e{ n
name = n;
E N le lic
} O R rab
O M
public void play()
n s fe{
A R -tra
System.out.println(name + " likes to play with string.");
N n
G}E no
f. Implement the eat method.
public void eat() {
System.out.println("Cats like to eat spiders and mice.");
}
4. Create the Fish class.
a. Create the Fish class with the following characteristics:
Class Name: Fish
Project: InterfaceProject
Extends: Animal
Implements: Pet

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)

Location: Source Packages


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

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
}
d. Implement the Pet interface methods.
public void setName(String name) {
s a
this.name = name;
) h a
}
c o m
public String getName() { ฺ
ail eฺ
return name;
g m id
} @ G u
public void play() {
0 2 11 ent
9 2 t
System.out.println("Fish swim in their tanks all day.");
n t S ud
}
( sai this
e. Override theAwalk
R u se This method should call the super
N method.
methodT
L and
e o a message that fish do not walk
theytprint
public void walk() { BE n s
super.walk(); N O lic e
E l e
M OR ferab
System.out.println("Fish, of course, can’t walk; they swim.");

RO -trans f. Implement the eat method.


}
A
GEN non
public void eat() {
System.out.println("Fish eat pond scum.");
}

Task 3 – Creating the TestAnimals Class


Complete the following steps:
1. In this task, you create the TestAnimals class with the following
characteristics:
Class Name: TestAnimals
Project: InterfaceProject

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)

Location: Source Packages


Package: default package
2. Add the main method to create and manipulate instances of the
classes you created previously.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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();
Pet p = new Cat();

s a
// Demonstrate different implementations of an interface
f.play(); ) h a
c o m
c.play(); ฺ
ail eฺ
g m id
// Demonstract virtual method invocation @ G u
e.eat();
0 2 11 ent
e.walk();
n t 9 2
S t ud
( sai this
AN use
// Demonstrate calling super methods
a.walk(); R
LT se to
}
E
B en
}
O
N le lic
E
M OR ferab
Task
O 4ra–nCompiling
s the TestAnimals Class
R
E NA on-t
G n In this task, you compile the TestAnimals class.

Task 5 – Running the TestAnimals Program


In this task, you run the TestAnimals program.

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

Exceptions and Assertions


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

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

deposit 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
c o m

ail eฺ
Account
«exception»g
m id
@
1 nt G u
#balance : double
2 1java.lang}
Exception
«constructors»
t 9 2 0
{from
t u de
a i s S
in«constructors»
#Account(initBalance:double)
s h
«methods»
A N ( use+Exception(msg:String)
t
+getBalance():double
+deposit(amt:double):void EL
TR e to «methods»
O B ens +getMessage():String
+withdraw(amt:double):void
l i c
R EN ble «send»

M O fera
R O a n s
CheckingAccount
«exception»

NA on-tr : double
OverdraftException

G E-overdraftAmount
n -deficit : double
«constructors»
«constructors»
+CheckingAccount(initBalance:double,
overdraft:double) +OverdraftException(msg:String,
deficit:double)
+CheckingAccount(initBalance:double)
«methods»
«methods»
«send» +getDeficit():double
+withdraw(amt:double):boid

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
il ฺ
aResources
g
Java Development: Java Classes: Copying Existing
● m i d eฺ
1 G u
@Java Classes:

2 1
Java Development: Java Classes: Modifying
e n t Compiling
Java Classes
9 2 0 ud
n t S t

( ai tModifying
Java Development: Java sClasses: h is Java Classes: Executing
Java Programs
R AN use
T e to
Lyou
E
B enwork
For this exercise, s in the BankPrj project in the projects
O
N le lic
directory.
E
M OR ferab
R O a s
Demonstration
n – The demonstration for this exercise can be found in the
A1 tr demos/08_except/exercise1 directory.
GEN 2non-
3

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
Extends: Exception
Location: Source Packages
Package: com.mybank.domain

This class must satisfy the UML diagram in Figure 8-1 on page L8-2.
s a
) h a
c o m
Task 2 – Modifying the Account Class ฺ
ail eฺ
g m id
@ G u
In this task, you modify the Account class source
0 2 11file einnthe
t
com.mybank.domain source package of the
n t 9 2 BankPrj
S t udL8-2.
project. This class

s a i
must satisfy the UML diagram in Figure 8-1
i on
s page In particular,
N ( usshould
the deposit and withdraw methods h
e t not return a boolean flag.
A
L TR e to
Task 3 – Modifying
O BE thee n sCheckingAccount Class
E N le lic
InO
R rayou b modify the CheckingAccount class source file in the
M e
this task,
sf
O com.mybank.domain
A R t r a n source package of the BankPrj project. This class

G EN non-must 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
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
2 11 ent
Customer [Bryant, Owen] has a savings balance of 200.0
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.

R AN used u sein this exercise:


E LT se to
Tool Reference – Tool references

O B enJava Classes: Creating Java Classes
Java Development:
E l e lic Other Files: Deleting Files
NDevelopment:
ORJavafeDevelopment:
rab
Java

M
O rans ● Java Classes: Copying Existing Resources
A R t
G EN non- Java ● Development: Java Classes: Modifying Java Classes: Compiling
Java Classes
● Java Development: Java Classes: Modifying Java Classes: Executing
Java Programs

For this exercise, you work in the BankPrj project in the projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/08_except/exercise1 directory.
2
3

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

com.mybank.domain source package of the BankPrj project with


the following characteristics:
Class Name: OverdraftException
Project: BankPrj
Extends: Exception
Location: Source Packages
Package: com.mybank.domain
s a
2. Add a private instance variable called deficit that holds a double.
) h a
3. o m
Add a public constructor that takes two arguments: message and
c

ail eฺ
deficit. The message parameter should be passed to the superclass
g m id
@ G u
constructor. The deficit parameter initializes the deficit instance
variable.
0 2 11 ent
n t 9 2
4. Add a public accessor called getDeficit.
S t ud
( sai this
Task 2 – Modifying R ANAccount
the u se Class
E LT se to
O Byoulimodify
In thisNtask, cen the Account class source file in the
O RE rable
com.mybank.domain source package of the BankPrj project.
M sf
O raCompletee
R
A n-t n the following steps:
E N
G no 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.
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
02file ufrom
d n
ethe
2
In this task, you copy the TestBanking.java
9
a i s St
nt com.mybank.test
resources/08_except directory to ithe source
s h
N ( use t
package of the BankPrj project.
A
L TR e to
Task 6 – Compiling
O BE thee n sTestBanking Class
E N le lic
InO
R
this task,ra b compile the TestBanking class.
you
M
O ransf e
R
A n-t
G EN Task
no 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.
N use
Areferences
Tool Reference – T
L R
Tool
t o used in this exercise:
e
BE ens Java Classes: Creating Java Classes
Java Development:

O lic
N Development:
E
R rab
● Java l e Other Files: Deleting Files
O
M sfJava e Development: Java Classes: Copying Existing Resources
O n ●

N AR n-tra Java Development: Java Classes: Modifying Java Classes: Compiling


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

For this exercise, you work in the BankPrj project in the projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/08_except/exercise1 directory.
2
3

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

com.mybank.domain source package of the BankPrj project with


the following characteristics:
Class Name: OverdraftException
Project: BankPrj
Extends: Exception
Location: Source Packages
Package: com.mybank.domain
s a
package com.mybank.domain;
) h a
public class OverdraftException extends Exception {
c o m
// insert code here ฺ
ail eฺ
}
g m id
2. Add a private instance variable called deficit @
1 nt G
that u
holds a double.
2 1
private final double deficit;
t 9 20 tude
a S arguments: message and
in takesistwo
3. Add a public constructor s that
h
( e tshould be passed to the superclass
A Nparameter
deficit. The message
us
constructor. T R
The deficit
t oparameter initializes the deficit instance
variable.EL e
O B ens
E N le lic
public OverdraftException(String msg, double deficit) {
OR f=edeficit;
super(msg);
M rab
ns
this.deficit
} RO r a
A t
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
s a
is, void). Declare that this method throws the OverdraftException.
) h a
o m
Modify the code to throw a new exception that specifies
c

ail eฺ
Insufficient 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 mClass id
@ G u
0 2 11classenintthe
92BankPrjtudproject.
In this task, you delete the current TestBanking
com.mybank.test source packageiof n tthe S
( sa this
R AN use
Task 5 – Copying the to
LT TestBanking
e Class
E
B en s
In this E
O licthe TestBanking.java file from the
N youlecopy
task,
M OR ferab
resources/08_except directory to the com.mybank.test source

A t r ans of the BankPrj project.


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

Collections and Generics Framework


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

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

in the 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 s a
associations: a bank serves many customers, and a customer has many ) h a
c o m
accounts. Figure 9-1 also shows the detailed design for Bank and

ail eฺ
Customer classes that use a generic List to maintain these links.
g m id
@ G u
0 2 11 ent
com.mybank.domain
n t 9 2
S t ud
serves ( s ai 0..*this
has-a
Bank 0..* Customer N
A u s e Account
L TR e to
O BE ens
E N le lic
M OR ferab SavingsAccount CheckingAccount

A RO -trans
N on
GE n Bank Customer
-customers : List<Customer> -accounts : List<Account>
-firstName : String
«constructors»
-lastName : String
-Bank()
«methods» «constructors»
+addCustomer(f:String, l:String) +Customer(f:String, l:String)
+getNumOfCustomers():int «methods»
+getCustomer(index:int):Customer +addAccount(acct:Account)
+getNumOfAccounts():int
+getAccount(index:int):Account

Figure 9-1 Domain Model of the Bank Project with Details on the Bank
and Customer Classes

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”
“Task 3 – Compiling the TestReport Class”
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

● “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
c o m
Java Development: Java Classes: Modifying Javam ailฺ Executing
Classes: eฺ

Java Programs g
@ t Gu i d
1 1
2 02 project
u d einnthe projects
9
nt is St
For this exercise, you work in the BankPrj
i
directory. a
(s e th
N us for this exercise can be found in the
Demonstration L –T RA
The t o
demonstration
B E nse
demos/09_collections/exercise directory.
1
O l i c e
2
R EN ble
3
M O fera
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. This class
must satisfy the UML diagram in Figure 9-1 on page L9-2.

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.

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 3 – 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 4 – Running the TestReport Program


In this task, you run the TestReport program. The output should be
similar to the following:
CUSTOMERS REPORT
================

Customer: Simms, Jane


s a
Savings Account: current balance is 500.0
Checking Account: current balance is 200.0 ) h a
c o m
Customer: Bryant, Owen

ail eฺ
g m id
Checking Account: current balance is 200.0
@ G u
0 2 11 ent
Customer: Soley, Tim
n t 9 2
S t ud
sai balance is is 200.0
Savings Account: current balance is 1500.0
Checking Account: current( t h
R AN use
LT Maria
Customer: Soley,
E e to
Savings B
Account: e s
ncurrent balance is 150.0
O l i c
R EN ble
M O fera
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

in the 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
Tool Reference – Tool references used in this
There is no preparation for this exercise.

0 2 11exercise:
e n t
Java Development: Java Classes:
n t 9 2
Modifying

S t udJava Classes: Compiling
Java Classes ( sai this
R
Java Development: AN u se Modifying Java Classes: Executing
Java Classes: ●
LT se to
Java Programs
E
O B en
ForE N exercise,
this l e licyou work in the BankPrj project in the projects
R rab
Odirectory.
O M
n s fe
N AR n-traDemonstration – The demonstration for this exercise can be found in the
GE no 1 demos/09_collections/exercise directory.
2
3

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.

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.

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)

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

5. Modify the getNumOfCustomers method to use the size method.

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:


s a
1. Modify the declaration for the accounts instance variable to)be haof
type List<Account>, and drop the numberOfAccounts c o m
instance
variable.

ail eฺ
m id variable to
g instance
@ G u
be a new ArrayList object. 0 2 11 ent
2. Modify the constructor to initialize the accounts

n t 9 2
S t udadd method.
3. Modify the addAccount method
( s ai this to use the

A N method
4. Modify the getAccount
u s e to use the get method.
TR e to
5. Modify theLgetNumOfAccounts method to use the size method.
E
B en s
O
N le lic
Task E
M OR3 –feCompiling
rab the TestReport Class
A RO -traInnsthis task, you compile the TestReport class.
N on
GE n
Task 4 – Running the TestReport Program
In this task, you run the TestReport program. The output should be
similar to the following:
CUSTOMERS REPORT
================

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

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)

Customer: Soley, Tim


Savings Account: current balance is 1500.0
Checking Account: current balance is 200.0
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Customer: Soley, Maria


Savings Account: current balance is 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

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

in the 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
Tool Reference – Tool references used tin
n 9 S t ud
2this exercise:
( sai Modifying
Java Development: Java Classes: t h is Java Classes: Compiling
AN use

Java Classes R
LT Java to Modifying Java Classes: Executing
E s e
O B licen
Java Development:
● Classes:
JavaN Programs
O RE rable
O e
MFor thissfexercise, you work in the BankPrj project in the projects
AR n-tra n
directory.
E N
G no Demonstration – The demonstration for this exercise can be found in the
1 demos/09_collections/exercise directory.
2
3

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.
s a
private static List<Customer> customers; ) h a
c o m
3. ฺ
ail eฺ
Modify the static block to initialize the customers instance variable
to be a new ArrayList object.
g m id
@ G u
static {
customers = new ArrayList<Customer>(10); 02
11 ent
} n t 9 2
S t ud
i
samethod is
4. Modify the addCustomer( t hto use the add method.
R AN uf, seString l) {
LT sel));
public static void addCustomer(String
E
customers.add(new Customer(f,
to
O B en
}
E N le lic
M O5.R fModify
e r ab the getCustomer method to use the get method.
O static s
public
R tr a n Customer getCustomer(int customer_index) {
Areturn customers.get(customer_index);
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;
s a
// initialize accounts instance variable
) h a
accounts = new ArrayList<Account>(10);
c o m
}
a il ฺ
g
4. Modify the addAccount method to use the add method. m i d eฺ
1 1 @ t Gu
02 uden
public void addAccount(Account acct) {
accounts.add(acct);
9 2
}
a i nt is St
5. Modify the getAccount N (s eto tuse
method
h the get method.
T R A
t o us {
EL nse
public Account getAccount(int account_index)
B
return accounts.get(account_index);
O lice
} N
E ble
6.OR Modify rathe getNumOfAccounts method to use the size method.
M f e
publicRint
A t r a ns
O getNumOfAccounts() {
N on
return -
accounts.size();
G}E n

Task 3 – Compiling the TestReport Class


In this task, you 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 n t 200.0
ud is 150.0
balance
t 9 2 balance
t
n
Savings Account: current 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

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 lic
_____________________________________________________________
l e
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

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

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

Console I/O and File I/O


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

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
R -Figure
G EN non File

Code 11-1 shows an example of the format of the customer data file. The
first line contains an integer, which determines the number of customers
in the data file. A customer record contains the first name, last name, and
the number of accounts, separated by tab characters. Each account record
contains a single-character code that determines the type of account and
also the data in that record.

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

overdraft protection of 400.00.

Code 11-2 Example Test Data File


4

Jane Simms 2
S 500.00 0.05
C 200.00 400.00

s a
Owen Bryant 1
) h a
C 200.00 0.00
c o m

ail eฺ
Tim Soley 2
g m id
S 1500.00 0.05 @ G u
C 200.00 0.00
0 2 11 ent
n t 9 2
S t ud
Maria Soley 1
150.00 0.05N (s
ai this
se
S
R A u
E LT the e to
This exercise contains
B e n s following sections:

E NO 1le– Creating
“Task
● lic a data Directory”
M OR f“Task
e
● rab2 – Copying the Resource File”
A RO -trans “Task 3 – Creating the DataSource Class”

GEN non “Task 4 – Deleting Unnecessary Classes”


● “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: Copying Existing Resources
● Java Development: Java Packages: Creating Java Packages
● Java Development: Java Classes: Creating Java Classes
● Java Development: Other Files: Deleting Files
● Java Development: Java Classes: Modifying Java Classes: Compiling
s a
Java Classes
) h a
● o m
Java Development: Java Application Projects: Setting Arguments
c

ailMaineClass

Java Development: Java Application Projects: Setting

g m the
i d
1 @ G u
Java Development: Java Application Projects:

1 Runningt Projects

9 2 02 uden
i nt iproject
For this exercise, you work in the BankPrj
a s St in the projects
directory.
N (s e th
T R A
t o us
Demonstration –E L demonstration
The
se directory.
for this exercise can be found in the
B e n
NO le lic
1 demos/11_fileio/exercise
2 E
3
M OR ferab
A RO -trans
G EN Task
non 1 – Creating a data Directory

Tool Reference – Java Development: Other Files: Creating Folders

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 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.
s a
Furthermore, the Customer class has the addAccount method to add the
accounts from the data file. ) h a
c o m

ail eฺ
Task 4 – Deleting Unnecessary Classes g m id
@ G u
0 2 11 ent
n t
In this task, you delete the following 9 2 classes
Java S t udthat are no longer used:
( sai this
TestReport
TestAccount RA
N use
E LT se to
TestAccount2
O B en
TestBatch
E N le lic
TestBanking
M OR ferab
ROTask a n s
A t r 5 – Copying the TestReport Class
GEN non-
In this task, you copy the TestReport class from the
resources/11_fileio directory to the com.mybank.test source
package of the BankPrj project.

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

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 s a
com.mybank.test.TestReport. ) h a
c o m
Tool Reference – Java Development: Java Application a

il Running
g m Projects:
i d eฺ
Projects
1 1 @ t Gu
3. Run the BankPrj project. The output
2 02 should
u d eben similar to the
following:
i 9
nt is St
Reading data file: ../data/test.dat (s a th
N
A REPORT
CUSTOMERS us e
T R t o
B EL nse
================

N
Customer: Simms, Jane O lice
Savings O RE racurrent
Account: ble balance is 500.0
Checking
O n fe current balance is 200.0
M Account:
s
N AR n-Bryant,
tra Owen
G E no
Customer:
Checking Account: current balance is 200.0

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
s i this
There is no preparation for thisaexercise.
(
N use
Areferences
Tool Reference – T
L R
Tool
t o used in this exercise:
e
BE ens Other Files: Creating Folders
Java Development:

O lic
N Development:
E
R rab
●Java l e Java Classes: Copying Existing Resources
O
M sfJava e Development: Java Packages: Creating Java Packages
O n ●

N AR n-tra Java Development: Java Classes: Creating Java Classes


GE no ● 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 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)

Demonstration – The demonstration for this exercise can be found in the


1 demos/11_fileio/exercise directory.
2
3
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 1 – Creating a data Directory


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 resources/11_fileio s a
directory into the data directory. ) h a
c o m

ail eฺ
Task 3 – Creating the DataSource Class@g m id
G u
0 2 11 ent
Complete the following steps:
n t 9 2
S t ud
1. Create the DataSource class( saini thethcom.mybank.data
is source
A Nprojects e
L T R to u
package of the BankPrj with the following characteristics:
Class Name:EDataSource
B e n se
E NOBankPrj
Project:
l e lic
M ORLocation:
e r a bSource Packages
R sf
O ranPackage:
N A n-t com.mybank.data

G E no 2. Add the dataFile instance variable to the DataSource class.


3. Add a public constructor that takes a string argument dataFilePath
and initializes the dataFile instance variable.
4. Add a public method, loadData, that populates the Bank customer
objects 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>

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)

Savings:
read <initial-balance> and <interest-rate)
create account and add account to customer
Checking:
read <initial-balance> and <overdraft-amount)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

create account and add account to customer

Task 4 – Deleting Unnecessary Classes


In this task, you delete the following Java classes that are no longer used:
TestReport
TestAccount
TestAccount2
s a
TestBatch
) h a
TestBanking
c o m

ail eฺ
g m id
Task 5 – Copying the TestReport Class @ G u
0 2 11 ent
n t 9 S t ud the
2 class from
sai to the
In this task, you copy the TestReport
(
resources/11_fileio directory t h s
icom.mybank.test source
package of the BankPrj N
A project.us e
R
L se to
T
E
Task 6 E –N O B licenthe TestReport Class
Compiling
O R rable
O M In this
n s fetask, you compile the TestReport class. If there are compilation
N AR n-traerrors, make necessary changes to the class and recompile it.
GE no
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.

Tool Reference – Java Development: Java Application Projects: Setting


Arguments
1. Set the argument of the BankPrj project to data/test.dat.

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: Setting the


Main Class
2. Set the main class of the BankPrj project to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
CUSTOMERS REPORT
================
s a
Customer: Simms, Jane ) h a
Savings Account: current balance is 500.0 c o m
Checking Account: current balance is 200.0

ail eฺ
g m id
@ G u
Customer: Bryant, Owen
Checking Account: current balance is 200.0 20
211 dent
i n t9 Stu
Customer: Soley, Tim ( sa this
R
Savings Account: current balance u se
ANis 1500.0
T e is
Checking Account: current Lbalance
E to 200.0
B en s
O
N le lic
E
Customer: Soley, Maria
OR fecurrent
Savings Account:
M rab balance is 150.0
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
s i this
There is no preparation for thisaexercise.
(
N use
Areferences
Tool Reference – T
L R
Tool
t o used in this exercise:
e
BE ens Other Files: Creating Folders
Java Development:

O lic
N Development:
E
R rab
●Java l e Java Classes: Copying Existing Resources
O
M sfJava e Development: Java Packages: Creating Java Packages
O n ●

N AR n-tra Java Development: Java Classes: Creating Java Classes


GE no ● 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 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)

Demonstration – The demonstration for this exercise can be found in the


1 demos/11_fileio/exercise directory.
2
3
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Task 1 – Creating a data Directory


Create a data directory in the BankPrj project.
1. With the BankPrj project open, click the Files tab.
2. Right-click BankPrj in the file tree.
3. Select New -> Other.
s a
4. Select Other in the Categories pane.
) h a
5. Select Folder in the File Types pane. c o m

ail eฺ
6. Click Next.
g m id
@ G u
7. Enter data for the folder name.
0 2 11 ent
8. Click Finish.
n t 9 2
S t ud
( sai this
Task 2 – CopyingTthe R AN Resource
u se File
E L se to
O B en
N le
In this task, youlic
copy the test.dat file from the resources/11_fileio
E
R rab
directory into the data directory.
O
M sfe
O
R -tran
A
G EN noTask
n 3 – Creating the DataSource Class
Complete the following steps:
1. Create the DataSource class in the com.mybank.data source
package of the BankPrj project with the following characteristics:
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

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)

}
2. Add an import statement to import necessary class names:
import com.mybank.domain.*;
import java.io.File;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

import java.io.IOException;
import java.util.Scanner;
3. Add the dataFile instance variable to the DataSource class.
private File dataFile;
4. Add a public constructor that takes a string argument dataFilePath
and initializes the dataFile instance variable.
public DataSource(String dataFilePath) {
this.dataFile = new File(dataFilePath);
}
s a
) h a
c o m

ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non

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
resources/11_fileio directory to the com.mybank.test source s a
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 TestReport
n t 9 2 class.
S t udIf there are compilation
errors, make necessary changes
( satoi thethclass
is and recompile it.
R AN use
Task 7 – Running E to
LTtheseBankPrj Project
B e n
E NO le lic
Rthis task,
In
OBankPrj r a b you set the TestReport class as the main class of the
O M s f e project, and run the BankPrj project with an argument
n
AR n-tradata/test.dat.
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

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)

3. Run the BankPrj project. The output should be similar to the


following:
Reading data file: ../data/test.dat
CUSTOMERS REPORT
================
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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 s a
Checking Account: current balance is 200.0 ) h a
c o m
a il ฺ
eฺ
Customer: Soley, Maria
Savings Account: current balance is 150.0 g m i d
1 1 @ t Gu
9 2 02 uden
a i nt is St
N (s e th
T R A
t o us
B EL nse
N O lice
O RE rable
O M sfe
A R -tran
N on
GE n

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

Building Java GUIs Using the Swing API


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

Objectives
Upon completion of this lab, you should be able to:
● Create a 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ฺ
projects directory, and then work in this project for all the following
g m id
exercises that are part of the ChatRoomPrj project.
@ G u
0 2 11 ent
Demonstration – The demonstration
n t 9for
S t ud can be found in the
2 this exercise
1
( ai this
demos/12_gui/exercise1sdirectory.
2
R AN use
LT se to
3
E
B en
O lic the ChatClient Class
Task R 1E–N Creating
l e
M O ferab
s task, you create the ChatClient class in the source package of the
RO -traInnthis
A
GEN non ChatRoomPrj project implement the GUI design in Figure 12-1 on
page 12-2.

Complete the following steps:


1. Create the ChatRoomPrj Java Application Project with the
following characteristics:
Project Name: ChatRoomPrj
Project Location: projects
Project Folder: 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
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)

Project: ChatRoomPrj
Location: Source Packages
Package: default package
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

The ChatClient class must implement the GUI design in Figure 12-1 on
page 12-2.

Task 2 – Compiling the ChatClient Class


In this task, you compile the ChatClient class.

Task 3 – Running the ChatClient Program s a


) h a
c o m

ail eฺ
In this task, you run the ChatClient program. You should see the GUI
g m
shown in Figure 12-1 on page 12-2. If your GUI does not look exactly like
id
@ u
the figure, then edit the code to tweak the design to match this figure.
G
0 2 11 ent
n t 9 2
S t ud
Task 4 – Terminating the Running
( sai thChatClient
is
Program AN use
R
LT se to
E
B en
O
N l–eJava
Tool Reference lic Development: Java Classes: Terminating a Running
E
M OR ferab
Process

A nstask, you terminate the running ChatClient program.


RO -Intrathis
G EN non

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”

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

Java Development: Java(sClasses:tCreating


AN se Modifying Java Classes: Compiling

R u

E LT se to
Java Development: Java Classes:
B en
Java Classes
O
E Java

l e lic
N Development: Java Classes: Modifying Java Classes: Executing
R
O fJava b
raPrograms
M e
A RO -trans Java Development: Java Classes: Terminating a Running Process

GEN non For this exercise, you first create the ChatRoomPrj project in the
projects directory, and then work in this project for all the following
exercises that are part of the ChatRoomPrj project.

Demonstration – The demonstration for this exercise can be found in the


1 demos/12_gui/exercise1 directory.
2
3

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)

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

page 12-2.

Complete the following steps:


1. Create the ChatRoomPrj Java Application Project with the
following characteristics:
Project Name: ChatRoomPrj
Project Location: projects
Project Folder: projects/ChatRoomPrj
s a
Set as Main Project: No
) h a
c o m
Create Main Class: No
il ฺ
2. Create the ChatClient class with the following g ma ideฺ
characteristics:
Class Name: ChatClient 1 1 @ t Gu
9 2 02 uden
Project: ChatRoomPrj
a i nt is St
Location: Source Packages
N (s e th
T
A
Package: defaultRpackage
t o us
3. Add four B EL variables
instance n se to the ChatClient class to hold the GUI
NO le lic
components.
e
E
R public b constructor that initializes each of the four GUI
4.O Add ara
M sf e
O rancomponent instance variables: The text area should be 10 rows tall
A R t
EN non- send button should have the word Send in the display, and the quit
and 50 columns wide, the text field should be 50 columns wide, the
G
button should display a similar label.
5. Create a launchFrame method that 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.
6. Create the main method. This method instantiates a new
ChatClient object and then calls the launchFrame method.

Task 2 – Compiling the ChatClient Class


In this task, you compile the ChatClient class.

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

the figure, then edit the code to tweak the design to match this figure.

Task 4 – Terminating the Running ChatClient


Program

Tool Reference – Java Development: Java Classes: Terminating a Running


Process
s a
In this task, you terminate the running ChatClient program. ) 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”

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

a i n i s S Projects
(s eCreating
Java Development: Java Classes:

N th Java Classes
T
Java Development: R A
t o usModifying Java Classes: Compiling
Java Classes:
EL nse

B
Java Classes
O lice Java Classes: Modifying Java Classes: Executing
Java
●N
E Programs
le
Development:
O RJava a b
O M sfer
A R -tranJava Development: Java Classes: Terminating a Running Process

G EN non For this exercise, you first create the ChatRoomPrj project in the
projects directory, and then work in this project for all the following
exercises that are part of the ChatRoomPrj project.

Demonstration – The demonstration for this exercise can be found in the


1 demos/12_gui/exercise1 directory.
2
3

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)

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

page 12-2.

Complete the following steps:


1. Create the ChatRoomPrj Java Application Project with the
following characteristics:
Project Name: ChatRoomPrj
Project Location: projects
Project Folder: projects/ChatRoomPrj
s a
Set as Main Project: No
) h a
c o m
Create Main Class: No ฺ
ail eฺ
2. Create the ChatClient class with the following g m id
characteristics:
@ G u
Class Name: ChatClient
0 2 11 ent
Project: ChatRoomPrj
n t 9 2
S t ud
( sai this
Location: Source Packages
R AN u se
T e to
Package: default package
3. ImportBthe ELjava.awt
n s and javax.swing packages.
O
N le lic e
import java.awt.*;E
OR ferab
import javax.swing.*;
M
public O
R n s
class ChatClient
a
{
Ainsert trcode here
E}N non-
//
G
4. Add four instance variables to the ChatClient class to hold the GUI
components.
private JTextArea output;
private JTextField input;
private JButton sendButton;
private JButton quitButton;
5. Add a public constructor that initializes each of the four GUI
component instance variables: The text area should be 10 rows tall
and 50 columns 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");
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)

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

above.
public void launchFrame() {
JFrame frame = new JFrame("Chat Room");

// Use the Border Layout for the frame


frame.setLayout(new BorderLayout());

frame.add(output, BorderLayout.WEST);
frame.add(input, BorderLayout.SOUTH);
s a
) h a
// Create the button panel
c o m
JPanel p1 = new JPanel(); ฺ
ail eฺ
p1.setLayout(new GridLayout(2,1));
g m id
p1.add(sendButton); @ G u
p1.add(quitButton);
0 2 11 ent
n t 9 2
S t ud
// Add the button panel to the center ai is
( s t h
AN use
frame.add(p1, BorderLayout.CENTER);
R
LT se to
frame.pack(); E
B en
O
N le lic
frame.setVisible(true);
} E
R rab
M7.O Create
f e the main method. This method instantiates a new
O s
R -tranChatClient object and then calls the launchFrame method.
A
EN nstatic
Gpublic on void main(String[] args) {
ChatClient c = new ChatClient();
c.launchFrame();
}

Task 2 – Compiling the ChatClient Class


In this task, you compile the ChatClient class.

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

the figure, then edit the code to tweak the design to match this figure.

Task 4 – Terminating the Running ChatClient


Program

Tool Reference – Java Development: Java Classes: Terminating a Running


Process
s a
In this task, you terminate the running ChatClient program. ) 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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

the Bank 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. a
h a s
Action Button Panel
m
Output JTextArea Component )
ฺ c o
m ail eฺ
@ g u id
11 ent G
0 2
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A ns Entry JTextField Component
RO -traData
EN non
GKey Pad Panel Message JTextField Component

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: Copying Existing Resources
● 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
)
For this exercise, you work in the BankPrj project in the projects h a
o m
directory.
a ilฺc ฺ
@ de in the
gmcan beuifound
1 nt G
Demonstration – The demonstration for this exercise
demos/12_gui/exercise2 directory. 021
1
2 t 9 2 t u de
3 s a in is S
N ( e th
T R A
t o us
Task 1 – CopyingB EL the n seATMClient Class
NO le lic e
E
R rabthe following steps:
Complete
O e the com.mybank.gui source package in the BankPrj project.
M 1. sfCreate
O n
N AR n-tra2. Copy the ATMClient.java template file from the
GE no resources/12_gui directory into the com.mybank.gui source
package of the BankPrj project. This template code provides the
main method, which initializes a set of bank customers 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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

have the 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
s a
(called rows in the API) of 10 characters and it must be read-only.
) h a
c o m

aofil the ATM
g m
Note – In this exercise, you will only be creating the layout i d eฺ
screen. You will not be creating the code to make1the@buttons G u
2 1 n t respond to

t 9 20 tude
user actions; you will do that in the next module.

s a in is S
N ( e th
Task 3 – Compiling Tthe R t o us
AATMClient Class
L
E nse
B
N Oyou compile
In this task, l i ce the ATMClient class.
O RE rable
O M sfe
A R -t4ra–nRunning the ATMClient Program
Task
G EN non
Complete the following steps:
1. Set the main class of the BankPrj project to
com.mybank.gui.ATMClient.
2. Run the BankPrj project. You should see the GUI shown in
Figure 12-2 on page 12-12.

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

read-only.
● A grid layout can be used to create a vertical layout by placing a 1 in
the rows parameters of the GridLayout(int rows, int columns)
constructor.
● A grid layout can be used to create a horizontal layout by placing a 1
in the columns parameters of the GridLayout(int rows, int
columns) constructor.

s a
) h a
c o m

ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non

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

Handling GUI-Generated Events


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

Objectives
Upon completion of this lab, you should be able to:
● Create the GUI event handlers for the ChatRoom project s a
) h
(Optional) Create the GUI event handlers for the Banking project
a

o m
a ilฺc ฺ
@ gm uide
2 1 1 nt G
t 9 20 tude
s a in is S
N ( e th
T R A
t o us
B EL nse
N O lice
O RE rable
O M sfe
A R -tran
N on
GE n

Lab 13-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise 1: Creating the ChatClient GUI Part 2 (Level 1)

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

need 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
M O isfno
There e a
rpreparation 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 projects
directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/13_events/exercise1 directory.
2
3

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

the introduction to this exercise.

Task 2 – Compiling the ChatClient Class


In this task, you compile the ChatClient class.

Task 3 – Running the ChatClient Program


s a
In this task, you run the ChatClient program. Test the behavior of ) h
the
a
o m
ilฺc ฺ
event listeners you added.
a
@ gm uide
Hints 2 1 1 nt G
t 9 20 tude
Use the following hints duringathis in exercise:
i s S
s h
N ( classes)
Have the listenersA(inner s e t
u to the access the instance variables of

L seT
their containing
R class t
toorefer components like the output text
area and E
B the input n text field. Remember that you made the
O l i c e
N le instance variables in the previous lab.
R Ecomponents
M e●rab to import the java.awt.event package.
O fRemember
A RO -trans To get the text from a JTextArea or JTextField, you can use the

N on
GE n getText method; to set the text, use either the setText or append
method.

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

need 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
Tool Reference – Tool references used in this 0 2 11
exercise:en
t
n t 9 2
S t ud
Java Development: Java Classes:

( s ai Modifying
t h i s Java Classes: Compiling
AN use
Java Classes
Java Development:
● R
LT Java to Modifying Java Classes: Executing
Classes:
E
B en
Java Programs s e
O
N le lic
E
R exercise,b you work in the ChatRoomPrj project in the projects
M Othis
For
e r a
R O ransf
directory.
A t
G EN non-Demonstration – The demonstration for this exercise can be found in the
1 demos/13_events/exercise1 directory.
2
3

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

area. Use an inner 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
) h a
Task 2 – Compiling the ChatClient Class c o m

ail eฺ
g m id
In this task, you compile the ChatClient class.@ G u
0 2 11 ent
n t 9 2
S t ud
Task 3 – Running the ChatClient ( sai this Program
R AN use
In this task, youLrun
E to
T the eChatClient program. Test the behavior of the
B youeadded.
event listeners n s
O l i c
R EN ble
M O fera
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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”

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

Java Classes (
R
Java Development:
● se Modifying Java Classes: Executing
ANJava Classes:
u
LT se to
Java Programs
E
O B en
N exercise,
ForEthis l e licyou work in the ChatRoomPrj project in the projects
R rab
Odirectory.
O M
n s fe
N AR n-traDemonstration – The demonstration for this exercise can be found in the
G E no 1 demos/13_events/exercise1 directory.
2
3

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.
1. Import the java.awt.event package.
import java.awt.event.*;
public class ChatClient {
// your code here
}
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)

2. Add the ActionListener for the Send button. This listener must
extract the text from the text field and display that text in the text
area. Use an inner class for this listener.
private void launchFrame() {
// GUI component initalization code here
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

sendButton.addActionListener(new SendHandler());
// more code
}

private class SendHandler implements ActionListener {


public void actionPerformed(ActionEvent e) {
String text = input.getText();
output.append(text+"\n");
input.setText("");
} s a
} ) h a
c o m
3. ฺ
ail eฺ
Add the ActionListener for the text field. Can you use the same
listener in Step 2?
g m id
private void launchFrame() { @
1 nt G u
// GUI component initalization code here 021
t 9 2 t u de
input.addActionListener(new SendHandler());
s a in is S
// more code
N ( e th
}
T R A
t o us
B ELcode.nthe
In this solution,
s eSendHandler inner class was reused to reduce
O lice
redundant
N
O REAdd
4.
a leWindowListener to the GUI frame. This listener must exit
the
b
O M sfthe er ChatClient program. Use an inner class for this listener.
R void
private
A - t r anlaunchFrame() {
GEN //nGUI
on component initalization code here
frame.addWindowListener(new CloseHandler());
// more code
}

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

quitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// more code
}
In this solution, the CloseHandler was not reused because the Quit
button requires an ActionListener rather than a WindowListener. a
How could you have satisfied both listener interfaces using the
h a s
CloseHandler class? m )
ฺ c o
m ail eฺ
Task 2 – Compiling the ChatClient Class @ g u id
11 ent G
0 2
2class. tud
n
In this task, you compile the ChatClient
i t 9 S
s a h i s
A N ( use t
Task 3 – Running L TRChatClient
the
e to Program
E
B en s
In this E
O
N youlerunlicthe ChatClient program. Test the behavior of the
task,
M ORlisteners
event
e r a byou added.
R O ransf
A t
G EN non-

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

by 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
) h a
c o m
At this stage, the Action buttons must be disabled and the following

ail eฺ
text must be displayed in the Output text area: Enter your
customer ID into the key pad and press the ENTER
g m id
button. @ G u
0 2 11buttons.
e n t Each number is
2 tud
2. The user enters the ID using the key pad
displayed in the Data Entryin t9field.
text S
( sisaselected,
t h isthe application retrieves the
When the ENTER button
specified customerR
N and
Aobject u sedisplays the following text in the
E
T Welcome
Larea: e to FIRST-NAME LAST-NAME if the customer
Output text
B otherwise,
e s
n the following text is displayed: Customer ID
was Ofound;
l i c
N notle found. Finally, if the customer was found, then the Action
R Ewas
M O fbuttons
e rab are enabled.
A RO -tra3.ns The user selects one of the Action buttons.
GEN non If the action is either deposit or withdraw, then the user is prompted
to enter the amount. The user can then enter the amount by clicking
the key pad 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 projects
directory.

s a
1
Demonstration – The demonstration for this exercise can be found in the
demos/13_events/exercise2 directory. ) h a
c o m
2
3

ail eฺ
g m id
@ G u
2 11 ent
Task 1 – Modifying the ATMClient 9 2Class
0
t ud
n t S
( s ai this
In this task, you modify the N
A ATMClient
u s e class in the source package of the
LTR sbehavior.
to rely on necessary event listeners to
BankPrj project. This class must
implemented theE required
B en e
O
N le lic
E
TaskM2O–RCompiling
f e r a b the ATMClient Class
O
R -tran s
A
G EN non In this task, you compile the ATMClient class.
Task 3 – Running the BankPrj Project
In this task, you run the BankPrj project.

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

GUI-Based Applications
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Objectives
Upon completion of this lab, you should be able to add menus to the GUI
for the ChatRoom project.
s a
) h a
c o m

ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non

Lab 14-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise: Creating the ChatClient GUI, Part 3 (Level 1)

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

component, a 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
@ G u
Figure 14-1 GUI Layout for the ChatClient Application
0 2 11 ent
You need to add four features to thein t92 GUI:
existing S tud
( sa component
t h is

A N use
Add the user name JComboBox under the Send and Quit
T R enables
buttons. This component
L t o you to select a name that is posted
B E ns
with every chat line e
that you enter. You must alter the Send button
NO lecomponent.
and JTextField e
lic listenersAdd
to write the username to the output
E
Ryour full
JTextAreab several user name options including
O a
M sfer name and a few nicknames, such as 1337dud3 or Java Geek.
O
R -tranPut the JTextArea component into a JScrollPane component. Add
A ●

G EN non a vertical scroll bar but no horizontal scroll bar. Auto scroll the text
to the bottom of the JTextArea as the user adds text to the text chat
window.
● Add the File menu. This menu must include a Quit menu item that
terminates the program when selected.
● Add the Help menu. This menu must include an About menu item
that pops up a simple dialog box, which displays a comment about
the program and about you, the developer.

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 projects
directory.
a
Demonstration – The demonstration for this exercise can be found) in
as
hthe
c o m
1 demos/14_guiapps/exercise1 directory. ฺ
ail eฺ
2
g m id
3
@ G u
0 2 11 ent
Task 1 – Modifying the ChatClient n t 9 2
S t ud
Class
( sai this
N use
Athe
L R
T This
In this task, you modify
t oclass must implement
ChatClient class in the source package of the
ChatRoomPrj
B E ns
project. e the GUI design in
NO on
Figure 14-1 page
l e
ic L14-2.
E
R rabl e
O
M 2s–feCompiling the ChatClient Class
OTask
R -tran
A
GEN non
In this task, you compile the ChatClient class.

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

and two 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:

n t 9 2
Java Development: Java Classes: Modifying
S t ud Classes: Compiling
Java
Java Classes
( sai this

R ANClasses:
Java Development: Java
u seModifying Java Classes: Executing
Java ProgramsLT
E e to
B en s
O
N leyoulicwork in the ChatRoomPrj project in the projects
For this exercise,
E
M OR ferab
directory.

A t ans
RO -Demonstration
r – The demonstration for this exercise can be found in the
G EN1 non demos/14_guiapps/exercise1 directory.
2
3

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 the GUI design in
Figure 14-1 on page L14-2.

Complete the following steps:

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)

1. Add the user name JComboBox component under the Send and Quit
buttons. This component enables you to select a name that is posted
with every chat line that you enter. Add several user name options
including your full name and a few nicknames, such as 1337dud3 or
Java Geek.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2. Enhance the listeners for the Send button and JTextField to write
the user name to the output JTextArea component.
3. Put the JTextArea component into a JScrollPane component. Add
a vertical scroll bar but no horizontal scroll bar. Auto scroll the text
to the bottom of the JTextArea as the user adds text to the text chat
window.
4. Add the File menu. This menu must include a Quit menu item that
terminates the program when selected.
s a
5. Add the Help menu. This menu must include an About menu item
) h a
c o m
that pops up a simple dialog box, which displays a comment about
the program and about you, the developer. ฺ
ail eฺ
g m id
@
1 nt G u
Task 2 – Compiling the ChatClient 2 1Class
t 9 2 0
t u de
s a in is S
N e th class.
In this task, you compile the( ChatClient

T R A
t o us
Task 3 – Running B EL the n seChatClient Program
NO le lic e
E
M OInRthis
e r a b you run the ChatClient program. You should see the GUI,
task,
R O rashown
n sf in Figure 14-1 on page L14-2. If your GUI does not look exactly like
A t the figure, then edit the code to tweak the design to match this figure.
GEN non-

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

and two 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:

n t 9 2
Java Development: Java Classes: Modifying
S t ud Classes: Compiling
Java
Java Classes
( sai this

R ANClasses:
Java Development: Java
u seModifying Java Classes: Executing
Java ProgramsLT
E e to
B en s
O
N leyoulicwork in the ChatRoomPrj project in the projects
For this exercise,
E
M OR ferab
directory.

A t ans
RO -Demonstration
r – The demonstration for this exercise can be found in the
G EN1 non demos/14_guiapps/exercise1 directory.
2
3

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 the GUI design in
Figure 14-1 on page L14-2.

Complete the following steps:

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)

1. Add the user name JComboBox component under the Send and Quit
buttons. This component enables you to select a name that is posted
with every chat line that you enter. Add several user name options
including your full name and a few nicknames, such as 1337dud3 or
Java Geek.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

public class ChatClient {


// existing code here
private JComboBox usernames;
// existing code here
public ChatClient() {
// more GUI components initialized
usernames = new JComboBox();
usernames.addItem("Jane Doe");
usernames.addItem("1337dud3");
usernames.addItem("Java Geek"); s a
} ) h a
public void launchFrame() {
c o m
// existing code here ฺ
ail eฺ
g m id
// Create the button panel
@ G u
JPanel p1 = new JPanel();
0 2 11 ent
p1.setLayout(new GridLayout(3,1));
n t 9 2
S t ud
sai this
p1.add(sendButton);
p1.add(quitButton); (
p1.add(usernames);
R AN use
LT se to
// existing code here
E
}
O B en
N le lic
// existing code here
E
}
M OR ferab
A RO -tra2.ns Add the aboutDialog instance variable of type
javax.swing.JDialog to the ChatClient class.
GEN non 3. Add the frame instance variable of type javax.swing.JFrame to
the ChatClient class.
4. Modify the declaration and initialization of the frame variable in the
launchFrame method to the following:
frame = new JFrame("Chat Room");
5. Enhance the listeners for the Send button and JTextField to write
the user name to the output JTextArea component.
private class SendHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = input.getText();
output.append(usernames.getSelectedItem() + ": " + text + "\n");
input.setText("");
}

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)

}
6. Add a JScrollPane component to the project and add the
JTextArea component to the a JScrollPane. Add a vertical scroll
bar but no horizontal scroll bar.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

// Add declaration
private JScrollPane textPane;
// existing code here

// Put JTextArea into JScrollPane and define scroll bars


textPane = new JScrollPane(output,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// existing code here

s a
// Add JScrollPane to Layout
) h a
frame.add(textPane, BorderLayout.WEST);
c o m
7. Auto scroll the text to the bottom of the JTextArea as the ฺ
ail usereadds

text to the text chat window. g m i d
1 1 @ t Gu
02 uden
// Add to SendHandler to enable AutoScroll
2
output.setCaretPosition(output.getDocument().getLength()-1);
9
a i nt is St
8. Add the File menu. This N (s must
menu e thinclude a Quit menu item that
R s
A whenuselected.
T
terminates the program
t o
public void launchFrame() B E{ L nse
// existing code N O lice
here
// Create menu
O REbarraband le File menu
O M mb
JMenuBar
n s fe= new JMenuBar();
A R -tra = new JMenu("File");
JMenu file
N JMenuItem
on
GE
quitMenuItem = new JMenuItem("Quit");
nquitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
file.add(quitMenuItem);
mb.add(file);
frame.setJMenuBar(mb);
// existing code here
}
9. Add the Help menu. This menu must include an About menu item
that pops up a simple dialog box, that displays a comment about the
program and about you, the developer.
public void launchFrame() {

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)

// existing menu bar code here


// Add Help menu to menu bar
JMenu help = new JMenu("Help");
JMenuItem aboutMenuItem = new JMenuItem("About");
aboutMenuItem.addActionListener(new AboutHandler());
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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 ) {
s a
aboutDialog = new AboutDialog(frame, "About", true);
) h a
}
c o m
aboutDialog.setVisible(true); ฺ
ail eฺ
}
g m id
@ G u
11 ent
}
0 2
n t 9 2
S t ud
ai thimplements
private class AboutDialog extends sJDialog
( is ActionListener
{ N use
Aparent,
R
T e to String title, boolean modal) {
public AboutDialog(Frame
L
BE enChatClient
s
super(parent,title,modal);
O
E N le lic
add(new JLabel("The is a neat tool that allows you

OR fer"to
to talk " +
M ab other ChatClients via a
ans b = new JButton("OK");
RO -trJButton
ChatServer"),BorderLayout.NORTH);
A
GEN non add(b,BorderLayout.SOUTH);
b.addActionListener(this);
pack();
}
// Hide the dialog box when the OK button is pushed
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
}

Task 2 – Compiling the ChatClient Class


In this task, you compile the ChatClient class.

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: Creating the ChatClient GUI, Part 3 (Level 3)

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

the figure, then edit the code to tweak the design to match this figure.

s a
) h a
c o m

ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
G EN non

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

GUI-Based Applications Lab 14-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 15

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

Objectives
Upon completion of this lab, you should be able to create a simple
multithreaded application.
s a
) h a
c o m

ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non

Lab 15-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.2
7i Business Solutions, SฺAฺ de CฺVฺ
Exercise: Using Multithreaded Programming (Level 1)

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( aithis texercise.
sfor h is
R AN use
Tool Reference –E LTreferences
Tool e to used in this exercise:
s
JavaN
● O B licenJava Application Projects: Opening Projects
Development:
E ble
RJava
M O ●
f e ra
Development: Java Classes: Creating Java Classes
s Development: Java Classes: Modifying Java Classes: Compiling
RO -tranJava
A ●

G EN non Java Classes


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

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


exercises/15_threads directory.

Demonstration – The demonstration for this exercise can be found in the


1 demos/15_threads directory.
2
3

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

directory.
2. Create a PrintMe class in the source package of the
ThreadProject with the following characteristics:
Class Name: PrintMe
Project: ThreadProject
Implements: Runnable
Location: Source Packages
s a
Package: default package
) h a
c o m
The class implements the Runnable interface. The run method ฺ
aofilthe ofcurrent
the class

performs the following actions 10 times: Print the name g m i d e
thread and then sleep for 2 seconds.
1 1 @ t Gu
9 2 02 uden
Task 2 – Creating the TestThreeThreadsa i nt is St Class
( s t h
R AN use
In this task, youLcreate
E to
T aeTestThreeThreads class in the source package
B n s
N O lice
of the ThreadProject with the following characteristics:

O REClass a b le TestThreeThreads
Name:

O er ThreadProject
M sfProject:
A R -tran Location: Source Packages
GEN non
Package: default package

The main method of the class creates three threads using the PrintMe
runnable class. Give each thread a unique name using the setName
method. Start each thread.

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 - Curly
0 2 11 ent
ud
T1 - Larry
t 9 2 t
T3 - Moe n S
T2 - (
Curly sai this
T1 - AN use
Larry
R
T3
E
-
LT se to
Moe
T2
O B en
- Curly

E N le lic
T1 - Larry

OR ferab
T3 - Moe
M T2 - Curly
A RO -trans T1 - Larry

G EN non T3
T2
-
-
Moe
Curly
T1 - Larry
T3 - Moe
T2 - Curly

Run this program several times. You might see different results for each
execution.

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”

Preparation s a
) h a
c o m
There is no preparation required for this exercise. ฺ
ail eฺ
g m id
@ G u
Tool Reference – Tool references used in this
0 2 11exercise:
e n t
n t 9
Java Development: Java Application S t ud Opening Projects
2 Projects:
ai his Java Classes

Java Development: Java(sClasses:tCreating


AN se Modifying Java Classes: Compiling

R u

E LT se to
Java Development: Java Classes:
B en
Java Classes
O
E Java

l e lic
N Development: Java Classes: Modifying Java Classes: Executing
R
O fJava b
raPrograms
M e
A nsthis exercise, you work in the ThreadProject project in the
RO -traFor
GEN non exercises/15_threads directory.
Demonstration – The demonstration for this exercise can be found in the
1 demos/15_threads directory.
2
3

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

directory.
2. Create the PrintMe class with the following characteristics:
Class Name: PrintMe
Project: ThreadProject
Implements: Runnable
Location: Source Packages
Package: default package
s a
This class must implement the Runnable interface. ) h a
c o m
3. ฺ
ail eฺ
Create the run method to loop the following 10 times: Print the name
g m
of the current thread and then sleep for 2 seconds.
id
@ G u
0 2 11 ent
Task 2 – Creating the TestThreeThreads
n t 9 2
S t udClass
( sai this
R AN use
In this task, you create a TestThreeThreads class in the source package
of the ThreadProject
E LT project.
e to
B en s
CompleteNtheO following
lic steps:
E l e
R ratheb TestThreeThreads class with the following
1.O Create
O M
n s fe
AR n-tra Class Name: TestThreeThreads
characteristics:
E N
G no
Project: ThreadProject
Location: Source Packages
Package: default package
2. Create the main method.
a. Create three Thread objects and pass an instance of the
PrintMe class to each constructor.
b. Give each thread a unique name using the setName method.
c. Start each thread.

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 3 – Compiling the TestThreeThreads Class


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

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

Preparation s a
) h a
c o m
There is no preparation required for this exercise. ฺ
ail eฺ
g m id
@ G u
Tool Reference – Tool references used in this2
0 11 ent
exercise:
t 9 d
2Projects:tuOpening

a i n
Java Development: Java Application
i s S Projects
(s eCreating
Java Development: Java Classes:

N th Java Classes
T R
Java Development:
A
t o usModifying Java Classes: Compiling
Java Classes:
EL nse

B
Java Classes
O lice Java Classes: Modifying Java Classes: Executing
Java
● N
E Programs
le
Development:
O RJava a b
O M sfer
A R -For
t r n exercise, you work in the ThreadProject project in the
athis
G EN non exercises/15_threads directory.
Demonstration – The demonstration for this exercise can be found in the
1 demos/15_threads directory.
2
3

Task 1 – Creating the PrintMe Class


Complete the following steps:
1. Open the ThreadProject project in the 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
Implements: Runnable
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Location: Source Packages


Package: default package
This class must implement the Runnable interface.
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. s a
) h a
public void run() {
c o m
for(int x = 0; x < 10; x++) { ฺ
ail eฺ
System.out.println(Thread.currentThread().getName());
g m id
try { @ G u
Thread.sleep(2000);
0 2 11 ent
} catch(Exception e) {}
n t 9 2
S t ud
}
( sai this
AN use
}
R
LT se to
Task 2 – Creating
E
B ethe n TestThreeThreads Class
O l i c
R EN ble
M OIn this
f e ra you create a TestThreeThreads class in the source package
task,
s ThreadProject project.
RO -traofnthe
A
GEN non Complete the following steps:
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
E
Bcompile nthe TestThreeThreads class.
In this task, you
O l i c e
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

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

Objectives
Upon completion of this lab, you should be able to build a GUI client to
connect to a remote server by using Transmission Control
s a
Protocol/Internet Protocol (TCP/IP).
) h a
c o m

ail eฺ
g m id
@ G u
0 2 11 ent
n t 9 2
S t ud
( sai this
R AN use
E LT se to
O B en
E N le lic
M OR ferab
A RO -trans
GEN non

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

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
c o m
a il ฺ
client: PC/Win95
1 “Simon: This is cool!” g m i d eฺ
1 1 @ t Gu
ChatClient
3 “Simon: This is cool!”
9 2 02 uden
Simon
a i t
nserveri s St
N (s e th
T R A
t o us
client: SparcSol9
B EL nse
N O lice ChatServer
E e
R rabl 2 “Simon: This is cool!”
O
ChatClient
M sfe
Debbie O
R -tran
A
N on
GE n
client: PC/WinXP

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

ChatClient class to initiate the socket 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
B en
instance variable in the ChatClient.

O
Figure
E 16-2 lic Design of the ChatClient Application
N leDetailed
M OR ferab
R O raThis
n s exercise contains the following sections:
A t
GEN non- “Task 1 – Modifying the ChatClient Class”

● “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
Demonstration – The demonstration for this exercise can be

il inฺ the
afound
1 demos/16_network directory.
@ g m
u ide
2
2 1 1 nt G
3
t 9 20 tude
s a in is S
N ( e th
Task 1 – Modifying the R us
AChatClient Class
T t o
B EL nse
In this task,O
N you modify
l i c ethe ChatClient class in the source package of the
RE rabproject.
ChatRoomPrj
onOthe detailed
le Implement the client-server communication based
design in Figure 16-2 on page L16-3.
M f e
A RO -trans
G EN Task
non 2 – Compiling the ChatClient Class
In this task, you compile the ChatClient class.

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:

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)

-DserverIP=<server-host>
-DserverPort=2000

Note – Ask your instructor for the value of the server-host.


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

3. Run the ChatRoomPrj project.


If your program connects to the server successfully, then the output
text area will display a message from the server with a secret
passphrase. When you send that passphrase to the server, you then
trigger an event on the server that plays a gong. This event will
indicate that your application is working correctly.

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 gm id
@ G u
Java Development: Java Classes: Modifying

0 2 11Java eClasses:
n t Compiling
Java Classes
n t 9 2
S t ud
sai thethMain
Java Application Projects: (Setting
● is Class
ANApplication
Java Development:RJava u se Projects: Setting VM Options
to

E LT Java
s e

O B en
Java Development: Application Projects: Running Projects

E N le lic
O R rab you work in the ChatRoomPrj project in the projects
For this exercise,
O n s fe
Mdirectory.
N AR n-tra
G E no Demonstration – The demonstration for this exercise can be found in the
1 demos/16_network directory.
2
3

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.

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)

2. Add instance variables to hold the input and output streams for the
socket connection. You might need additional instance variables,
depending on your implementation.
3. Add the doConnect method to initiate the TCP/IP socket connection
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

to the server. Ask your instructor for the hostname (or IP address)
and port number of the server application.
a. Initialize server IP and port information.
b. Create the connection to the chat server.
c. Prepare the input stream and store it in an instance variable.
d. Prepare the output stream and store it in an instance variable.
e. Launch the reader thread.
f. Use a catch clause to capture any exceptions. s a
4. Modify the launchFrame method to call the doConnect method. ) h a
o m
5. Modify the SendHandler nested class to send the message
a ilฺc textฺ (and
m e
displayed the message to the output text1area.@ g
the user name) to the socket output stream. Delete the
G uid
code that

0 2 1 ent
6. Create the RemoteReader nested
t 9 class d
2 thattuimplements the Runnable
interface. The run methodamust n S
i readisa line at a time from the socket
(
input stream in an infinite s loop. th
A N us e
L seT R t o
B
Task 2 – Compiling
E nthe ChatClient Class
O l i c e
R EN ble
M OIn this
f e ra you compile the ChatClient class.
task,
A RO -trans
GEN non Task 3 – Running the ChatRoomPrj Project
Complete the following steps:
1. Set the main class of the ChatRoomPrj project to ChatClient.

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

text area will display a message from the server with a secret
passphrase. When you send that passphrase to the server, you then
trigger an event on the server that plays a gong. This event will
indicate that your application is working correctly.

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ฺ
g
Tool Reference – Tool references used in this exercise: m id
@ G u

0 2 11 Java
Java Development: Java Classes: Modifying
e n t
Classes: Compiling
Java Classes 2
t9 Stu d
i n is Main Class
● ( saSettingththe
Java Application Projects:

R
Java Development:AN u se
Java Application Projects: Setting VM Options

L T e to

O BE ens Java Application Projects: Running Projects
Java Development:

E N le lic
O R rexercise,
For this
a b you work in the ChatRoomPrj project in the projects
O n s fe
M directory.
N AR n-tra
GE no Demonstration – The demonstration for this exercise can be found in the
1 demos/16_network directory.
2
3

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
g m id
to the server. Ask your instructor for the hostname (or IP address)
@ G u
and port number of the server application.
0 2 11 ent
private void doConnect() {
n t 9 2
S t ud
a.
sai information.
Initialize server IP and port
( t h is
// Initialize server IP and port
R u se
ANinformation
L T e to
String serverIP = System.getProperty("serverIP", "127.0.0.1");

O BE ens
String serverPort = System.getProperty("serverPort", "2000");

E N le lic
M OR– You
Note f e r a b have hard coded the server IP address and port number
could
R O inrathensSocket constructor call below. The code for this step demonstrates
A
N on - t
how to make these values dynamic at runtime. The system properties,
G E n serverIP and serverPort, can be assigned on the java command using
the -D option, as follows:

java -DserverIP=myhost.example.com
-DserverPort=47 ChatClient

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 etext ฺ (and
g m i d
the user name) to the socket output stream. Delete theucode that
1 @ tG
1area.
0 ud{en
displayed the message to the output 2 text
9 2
a i nt e) is{ St
private class SendHandler implements ActionListener
(s e th
public void actionPerformed(ActionEvent
N us+ ": " + text + "\n";
String text = input.getText();
R A
T
text = usernames.getSelectedItem()
t o
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
} // END of RemoteReader nested class

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)

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
@
1 nt G u
Note – Ask your instructor for the value of the 1 server-host.
2 0 2 de
t 9 t u
3. Run the ChatRoomPrj project.
s a in is S
If your program connects N ( e th successfully, then the output
to thesserver
R Aa messageu from the server with a secret
T
text area will display
L t o
passphrase.B E
When you
e n sesend that pass phrase to the server, you then
N
triggerOan event
l icon the server that plays a gong. This event will
E
Rindicate e
bl your application is working correctly.
that
O
M sfe r a
O
R -Good
r anluck and have fun!
A t
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 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

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

You might also like