Material de Oracle para certificación Java

276
 Java Programming Language, Java SE 6 Activity Guide - Volume 1 SL-275-SE6 G.2 D61748GC11 Edition 1.1 June 2010 D67982

description

Primer manual para la certificación JAVA

Transcript of Material de Oracle para certificación Java

Page 1: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 1/276

Java Programming Language,

Java SE 6

Activity Guide - Volume 1

SL-275-SE6 G.2

D61748GC11

Edition 1.1

June 2010

D67982

Page 2: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 2/276

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 anddisclosure, 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 expresslypermitted 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 expressauthorization of Oracle.

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. Thisdocument 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 SunMicrosystems, Inc. Certain materials, offerings, services, or products may no longer be offered or provided.Oracle and itsaffiliates 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:

U.S. GOVERNMENT RIGHTSThe U.S. Government’s rights to use, modify, reproduce, release, perform, display, or disclose these training materials arerestricted by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.

Trademark Notice

Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respectiveowners.

 AMD, Opteron, the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced MicroDevices. Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are usedunder license and are trademarks or registered trademarks of SPARC International, Inc. UNIX is a registered trademarklicensed through X/Open Company, Ltd.

Page 3: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 3/276

This page intentionally left blank.

Page 4: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 4/276

This page intentionally left blank.

Page 5: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 5/276

vCopyright2008Sun Microsystems,Inc. All Rights Reserved.Sun Services, RevisionG.2

Table of Contents

About This Workbook .......................................................Preface-xvii

Lab Goals............................................................................. Preface-xviiPerforming the Exercises ................................................. Preface-xviiiConventions..........................................................................Preface-xix

Typographical Conventions...................................... Preface-xixAdditional Conventions.............................................. Preface-xx

Getting Started..................................................................................1-1

Objectives ........................................................................................... 1-1Exercise 1: Exploring Java™ Program Errors ................................ 1-2

Preparation................................................................................. 1-2Task – Correcting Compilation and Runtime Errors........... 1-2

Exercise 2: Creating a Test Program (Level 1) ............................... 1-4Preparation................................................................................. 1-4Task 1 – Copying the Account Class ..................................... 1-5

Task 2 – Creating the TestAccount Class............................. 1-5Task 3 – Compiling the TestAccount Class.........................1-6Task 4 – Running the TestAccount Program ...................... 1-6

Exercise 2: Creating a Test Program (Level 2) ............................... 1-7Preparation................................................................................. 1-7Task 1 – Copying the Account Class ..................................... 1-8Task 2 – Creating the TestAccount Class............................. 1-8Task 3 – Compiling the TestAccount Class.........................1-9Task 4 – Running the TestAccount Program ...................... 1-9

Exercise 2: Creating a Test Program (Level 3) ............................. 1-10Preparation............................................................................... 1-10

Task 1 – Copying the Account Class ................................... 1-11Task 2 – Creating the TestAccount Class........................... 1-11Task 3 – Compiling the TestAccount Class ....................... 1-12Task 4 – Running the TestAccount Program .................... 1-12

Exercise Summary............................................................................ 1-13

Page 6: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 6/276

vi Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

Objectives ........................................................................................... 2-1Exercise 1: Using the Java API Documentation............................. 2-2

Preparation................................................................................. 2-2Task – Using the Java API Documentation........................... 2-2

Exercise 2: Exploring Encapsulation, Version 1 (Level 1) ............ 2-3Preparation................................................................................. 2-4Task 1 – Deleting the Account Class...................................... 2-4Task 2 – Creating the Account Class ..................................... 2-4Task 3 – Creating the TestAccount2 Class .......................... 2-5Task 4 – Compiling the TestAccount2 Class....................... 2-5Task 5 – Running the TestAccount2 Program ....................2-5

Exercise 2: Exploring Encapsulation, Version 1 (Level 2) ............ 2-6Preparation................................................................................. 2-6Task 1 – Deleting the Account Class...................................... 2-7Task 2 – Creating the Account Class ..................................... 2-7

Task 3 – Creating the TestAccount2 Class .......................... 2-7Task 4 – Compiling the TestAccount2 Class....................... 2-8Task 5 – Running the TestAccount2 Program ....................2-8

Exercise 2: Exploring Encapsulation, Version 1 (Level 3) ............ 2-9Preparation................................................................................. 2-9Task 1 – Deleting the Account Class.................................... 2-10Task 2 – Creating the Account Class ................................... 2-10Task 3 – Creating the TestAccount2 Class ........................ 2-10Task 4 – Compiling the TestAccount2 Class..................... 2-11Task 5 – Running the TestAccount2 Program.................. 2-11

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

Preparation............................................................................... 2-12Task 1 – Modifying the Account Class................................ 2-13Task 2 – Modifying the TestAccount Class ....................... 2-13Task 3 – Compiling the TestAccount Class ....................... 2-13Task 4 – Running the TestAccount Program .................... 2-13

Exercise 3: Exploring Encapsulation, Version 2 (Level 2) .......... 2-14Preparation............................................................................... 2-14Task 1 – Modifying the Account Class................................ 2-14Task 2 – Modifying the TestAccount Class ....................... 2-15Task 3 – Compiling the TestAccount Class ....................... 2-15Task 4 – Running the TestAccount Program .................... 2-15

Exercise 3: Exploring Encapsulation, Version 2 (Level 3) .......... 2-16Preparation............................................................................... 2-16Task 1 – Modifying the Account Class................................ 2-16Task 2 – Modifying the TestAccount Class ....................... 2-17Task 3 – Compiling the TestAccount Class ....................... 2-17Task 4 – Running the TestAccount Program .................... 2-17

Exercise 4: Creating Java Packages................................................ 2-18Preparation............................................................................... 2-19

Page 7: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 7/276

viiCopyright2008Sun Microsystems,Inc. All Rights Reserved.Sun Services, RevisionG.2

Task 1 – Creating the Java Packages .................................... 2-19Task 2 – Moving and Modifying the Account Class ......... 2-19Task 3 – Moving the TestAccount Class............................ 2-20Task 4 – Compiling the TestAccount Class ....................... 2-20Task 5 – Running the TestAccount Program .................... 2-20

Exercise Summary............................................................................ 2-21Identifiers, Keywords, and Types ...................................................3-1

Objectives ........................................................................................... 3-1Exercise 1: Investigating Reference Assignment........................... 3-2

Preparation................................................................................. 3-2Task 1 – Creating the TestMyPoint Class............................. 3-3Task 2 – Compiling the TestMyPoint Class.........................3-4Task 3 – Running the TestMyPoint Program ...................... 3-4

Exercise 2: Creating Customer Accounts (Level 1) ....................... 3-5Preparation................................................................................. 3-6Task 1 – Creating the Customer Class ................................... 3-6

Task 2 – Copying the TestBanking Class............................. 3-6Task 3 – Compiling the TestBanking Class.........................3-7Task 4 – Running the TestBanking Program ...................... 3-7

Exercise 2: Creating Customer Accounts (Level 2) ....................... 3-8Preparation................................................................................. 3-8Task 1 – Creating the Customer Class ................................... 3-9Task 2 – Copying the TestBanking Class............................. 3-9Task 3 – Compiling the TestBanking Class.........................3-9Task 4 – Running the TestBanking Program .................... 3-10

Exercise 2: Creating Customer Accounts (Level 3) ..................... 3-11Preparation............................................................................... 3-11Task 1 – Creating the Customer Class .................................3-12Task 2 – Copying the TestBanking Class........................... 3-13Task 3 – Compiling the TestBanking Class ....................... 3-13Task 4 – Running the TestBanking Program .................... 3-13

Exercise Summary............................................................................ 3-14

Expressions and Flow Control........................................................4-1

Objectives ........................................................................................... 4-1Exercise 1: Using Loops and Branching Statements ..................... 4-2

Preparation................................................................................. 4-3Task 1 – Creating the FooBarBaz Class.................................4-3

Task 2 – Compiling the FooBarBaz Class ............................. 4-4Task 3 – Running the FooBarBaz Program........................... 4-4Hints............................................................................................ 4-4

Exercise 2: Using Conditional Statements in the Account Class(Level 1) ............................................................................................ 4-5

Preparation................................................................................. 4-5Task 1 – Modifying the Account Class .................................. 4-6Task 2 – Deleting the Current TestBanking Class................ 4-6

Page 8: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 8/276

viii Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 3 – Copying the TestBanking Class.............................4-6Task 4 – Compiling the TestBanking Class ......................... 4-6Task 5 – Running the TestBanking Program ...................... 4-7

Exercise 2: Using Conditional Statements in the Account Class(Level 2) ............................................................................................ 4-8

Preparation................................................................................. 4-8Task 1 – Modifying the Account Class.................................. 4-9Task 2 – Deleting the Current TestBanking Class ................ 4-9Task 3 – Copying the TestBanking Class.............................4-9Task 4 – Compiling the TestBanking Class ......................... 4-9Task 5 – Running the TestBanking Program ...................... 4-9

Exercise 2: Using Conditional Statements in the Account Class(Level 3) .......................................................................................... 4-10

Preparation............................................................................... 4-10Task 1 – Modifying the Account Class................................ 4-11Task 2 – Deleting the Current TestBanking Class .............. 4-11

Task 3 – Copying the TestBanking Class........................... 4-11Task 4 – Compiling the TestBanking Class ....................... 4-11Task 5 – Running the TestBanking Program .................... 4-12

Exercise 3: Using Nested Loops (Advanced) ............................... 4-13Preparation............................................................................... 4-13Task 1 – Writing the isSubString Method........................ 4-14Task 2 – Compiling the TestIsSubString Class .............. 4-14Task 3 – Running the TestIsSubString Program............4-14Hints......................................................................................... 4-15

Exercise Summary............................................................................ 4-16

Arrays................................................................................................ 5-1

Objectives ........................................................................................... 5-1Exercise 1 – Using Primitive Arrays (Level 2) ............................... 5-2

Preparation................................................................................. 5-2Task 1 – Creating the TestArrays Class............................... 5-2Task 2 – Compiling the TestArrays Class ...........................5-3Task 3 – Running the TestArrays Program......................... 5-3Hint ............................................................................................ 5-4

Exercise 1 – Using Primitive Arrays (Level 3) ............................... 5-5Preparation................................................................................. 5-5Task 1 – Creating the TestArrays Class............................... 5-5Task 2 – Compiling the TestArrays Class ...........................5-7Task 3 – Running the TestArrays Program......................... 5-7

Exercise 2 – Using Arrays to Represent One-to-Many Associations(Level 1) ............................................................................................ 5-8

Preparation................................................................................. 5-9Task 1 – Creating the Bank Class............................................ 5-9Task 2 – Deleting the Current TestBanking Class............. 5-9Task 3 – Copying the TestBanking Class........................... 5-10

Page 9: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 9/276

ixCopyright2008Sun Microsystems,Inc. All Rights Reserved.Sun Services, RevisionG.2

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

Task 2 – Deleting the Current TestBanking Class...........5-12Task 3 – Copying the TestBanking Class........................... 5-12Task 4 – Compiling the TestBanking Class ....................... 5-12Task 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-15Task 2 – Deleting the Current TestBanking Class...........5-16Task 3 – Copying the TestBanking Class........................... 5-16Task 4 – Compiling the TestBanking Class ....................... 5-16Task 5 – Running the TestBanking Program .................... 5-16

Exercise Summary............................................................................ 5-17Class Design.....................................................................................6-1

Objectives ........................................................................................... 6-1Exercise 1: Creating Bank Account Subclasses (Level 1).............. 6-2

Preparation................................................................................. 6-3Task 1 – Modifying the Account Class.................................. 6-4Task 2 – Creating the SavingsAccount Class ...................... 6-4Task 3 – Creating the CheckingAccount Class....................6-4Task 4 – Deleting the Current TestBanking Class..............6-5Task 5 – Copying the TestBanking Class............................. 6-5Task 6 – Compiling the TestBanking Class.........................6-5Task 7 – Running the TestBanking Program ...................... 6-5

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

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

Page 10: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 10/276

x Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Creating a Heterogeneous Collection of CustomerAccounts (Level 1)......................................................................... 6-18

Preparation............................................................................... 6-19Task 1 – Modifying the Customer Class.............................. 6-19Task 2 – Copying and Completing the CustomerReport

Class ....................................................................................... 6-19Task 3 – Copying the TestReport Class............................. 6-20Task 4 – Compiling the TestReport Class ......................... 6-20Task 5 – Running the TestReport Program....................... 6-20

Exercise 2: Creating a Heterogeneous Collection of CustomerAccounts (Level 2)......................................................................... 6-21

Task 1 – Modifying the Customer Class.............................. 6-22Task 2 – Copying and Completing the CustomerReport

Class ....................................................................................... 6-22Task 3 – Copying the TestReport Class............................. 6-23Task 4 – Compiling the TestReport Class ......................... 6-23

Task 5 – Running the TestReport Program....................... 6-23Exercise 2: Creating a Heterogeneous Collection of CustomerAccounts (Level 3)......................................................................... 6-24

Task 1 – Modifying the Customer Class.............................. 6-25Task 2 – Copying and Completing the CustomerReport

Class ....................................................................................... 6-26Task 3 – Copying the TestReport Class............................. 6-26Task 4 – Compiling the TestReport Class ......................... 6-26Task 5 – Running the TestReport Program....................... 6-27

Exercise 3: Creating a Batch Program (Advanced) ..................... 6-28Preparation............................................................................... 6-29

Task 1 – Modifying the SavingsAccount Class................. 6-29Task 2 – Creating the AccumulateSavingsBatchClass ....................................................................................... 6-29

Task 3 – Copying the TestBatch Class............................... 6-30Task 4 – Compiling the TestBatch Class ........................... 6-30Task 5 – Running the TestBatch Program.........................6-30

Exercise Summary............................................................................ 6-32

Advanced Class Features ............................................................... 7-1

Objectives ........................................................................................... 7-1Exercise 1: Applying Static Members to a Design (Level 1) ........ 7-2

Preparation................................................................................. 7-3Task 1 – Modifying the Bank Class......................................... 7-3Task 2 – Modifying the CustomerReport Class................... 7-3Task 3 – Deleting the Current TestReport Class ................ 7-4Task 4 – Copying the TestReport Class............................... 7-4Task 5 – Compiling the TestReport Class ...........................7-4Task 6 – Running the TestReport Program......................... 7-4

Exercise 1: Applying Static Members to a Design (Level 2) ........ 7-5

Page 11: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 11/276

xiCopyright2008Sun Microsystems,Inc. All Rights Reserved.Sun Services, RevisionG.2

Task 1 – Modifying the Bank Class......................................... 7-6Task 2 – Modifying the CustomerReport Class................... 7-6Task 3 – Deleting the Current TestReport Class ................ 7-7Task 4 – Copying the TestReport Class............................... 7-7Task 5 – Compiling the TestReport Class ...........................7-7

Task 6 – Running the TestReport Program......................... 7-7Exercise 1: Applying Static Members to a Design (Level 3) ........ 7-8Task 1 – Modifying the Bank Class......................................... 7-9Task 2 – Modifying the CustomerReport Class................. 7-10Task 3 – Deleting the Current TestReport Class..............7-10Task 4 – Copying the TestReport Class............................. 7-10Task 5 – Compiling the TestReport Class ......................... 7-11Task 6 – Running the TestReport Program....................... 7-11

Exercise 2: Working With Interfaces and Abstract Classes(Level 1) .......................................................................................... 7-12

Preparation............................................................................... 7-13

Task 1 – Creating the Pet Interface ....................................... 7-13Task 2 – Creating the Animal Classes .................................. 7-14Task 3 – Creating the TestAnimals Class........................... 7-14Task 4 – Compiling the TestAnimals Class ....................... 7-15Task 5 – Running the TestAnimals Program .................... 7-15

Exercise 2: Working With Interfaces and Abstract Classes(Level 2) .......................................................................................... 7-16

Preparation............................................................................... 7-16Task 1 – Creating the Pet Interface ....................................... 7-17Task 2 – Creating the Animal Classes .................................. 7-17Task 3 – Creating the TestAnimals Class........................... 7-19

Task 4 – Compiling the TestAnimals Class ....................... 7-20Task 5 – Running the TestAnimals Program .................... 7-20Exercise 2: Working With Interfaces and Abstract Classes

(Level 3) .......................................................................................... 7-21Preparation............................................................................... 7-21Task 1 – Creating the Pet Interface ....................................... 7-22Task 2 – Creating the Animal Classes .................................. 7-22Task 3 – Creating the TestAnimals Class........................... 7-25Task 4 – Compiling the TestAnimals Class ....................... 7-26Task 5 – Running the TestAnimals Program .................... 7-26

Exercise Summary............................................................................ 7-27

Exceptions and Assertions .............................................................8-1

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

Task 1 – Creating the OverdraftException Class ............. 8-4Task 2 – Modifying the Account Class.................................. 8-4Task 3 – Modifying the CheckingAccount Class ................ 8-4Task 4 – Deleting the Current TestBanking Class.............. 8-4

Page 12: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 12/276

xii Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 5 – Copying the TestBanking Class.............................8-4Task 6 – Compiling the TestBanking Class ......................... 8-5Task 7 – Running the TestBanking Program ...................... 8-5

Exercise: Creating Your Own Exception (Level 2)........................ 8-6Task 1 – Creating the OverdraftException Class ............. 8-7

Task 2 – Modifying the Account Class.................................. 8-7Task 3 – Modifying the CheckingAccount Class ................ 8-8Task 4 – Deleting the Current TestBanking Class.............. 8-8Task 5 – Copying the TestBanking Class.............................8-8Task 6 – Compiling the TestBanking Class ......................... 8-8Task 7 – Running the TestBanking Program ...................... 8-8

Exercise: Creating Your Own Exception (Level 3) ........................ 8-9Task 1 – Creating the OverdraftException Class ........... 8-10Task 2 – Modifying the Account Class................................ 8-11Task 3 – Modifying the CheckingAccount Class .............. 8-11Task 4 – Deleting the Current TestBanking Class............8-12

Task 5 – Copying the TestBanking Class........................... 8-12Task 6 – Compiling the TestBanking Class ....................... 8-12Task 7 – Running the TestBanking Program .................... 8-12

Exercise Summary............................................................................ 8-13

Collections and Generics Framework............................................ 9-1

Objectives ........................................................................................... 9-1Exercise 1: Using Collections to Represent Association

(Level 1) ............................................................................................ 9-2Preparation................................................................................. 9-3Task 1 – Modifying the Bank Class......................................... 9-3Task 2 – Modifying the Customer Class................................9-3Task 3 – Compiling the TestReport Class ...........................9-4Task 4 – Running the TestReport  Program ....................... 9-4

Exercise 1: Using Collections to Represent Association(Level 2) ............................................................................................ 9-5

Preparation................................................................................. 9-5Task 1 – Modifying the Bank Class......................................... 9-5Task 2 – Modifying the Customer Class................................9-6Task 3 – Compiling the TestReport Class ...........................9-6Task 4 – Running the TestReport Program......................... 9-6

Exercise 1: Using Collections to Represent Association(Level 3) ............................................................................................ 9-8

Preparation................................................................................. 9-8Task 1 – Modifying the Bank Class......................................... 9-9Task 2 – Modifying the Customer Class................................ 9-9Task 3 – Compiling the TestReport Class ......................... 9-10Task 4 – Running the TestReport Program....................... 9-11

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

Page 13: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 13/276

xiiiCopyright2008Sun Microsystems,Inc. All Rights Reserved.Sun Services, RevisionG.2

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

Console I/O and File I/O .................................................................11-1

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

Preparation............................................................................... 11-4

Task 1 – Creating a data Directory ...................................... 11-4Task 2 – Copying the Resource File...................................... 11-4Task 3 – Creating the DataSource Class............................. 11-5Task 4 – Deleting Unnecessary Classes ............................... 11-5Task 5 – Copying the TestReport Class............................. 11-5Task 6 – Compiling the TestReport Class ......................... 11-5Task 7 – Running the BankPrj Project................................. 11-6

Exercise 1: Reading a Data File (Level 2)...................................... 11-7Preparation............................................................................... 11-7Task 1 – Creating a data Directory ...................................... 11-8Task 2 – Copying the Resource File...................................... 11-8

Task 3 – Creating the DataSource Class............................. 11-8Task 4 – Deleting Unnecessary Classes ............................... 11-9Task 5 – Copying the TestReport Class............................. 11-9Task 6 – Compiling the TestReport Class ......................... 11-9Task 7 – Running the BankPrj Project................................. 11-9

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

Exercise Summary.......................................................................... 11-17

Building Java GUIs Using the Swing API.....................................12-1

Objectives ......................................................................................... 12-1Exercise 1: Creating the ChatClient GUI Part 1 (Level 1)........ 12-2

Preparation............................................................................... 12-3Task 1 – Creating the ChatClient Class............................. 12-3Task 2 – Compiling the ChatClient Class ......................... 12-4

Task 3 – Running the ChatClient Program....................... 12-4Task 4 – Terminating the Running ChatClient Program 12-4

Exercise 1: Creating the ChatClient GUI Part 1 (Level 2)........ 12-5Preparation............................................................................... 12-5Task 1 – Creating the ChatClient Class............................. 12-6Task 2 – Compiling the ChatClient Class ......................... 12-6Task 3 – Running the ChatClient Program....................... 12-7Task 4 – Terminating the Running ChatClient Program 12-7

Page 14: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 14/276

xiv Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Creating the ChatClient GUI Part 1 (Level 3)........... 12-8Preparation............................................................................... 12-8Task 1 – Creating the ChatClient Class............................. 12-9Task 2 – Compiling the ChatClient Class ....................... 12-10Task 3 – Running the ChatClient Program.....................12-11

Task 4 – Terminating the Running ChatClientProgram............................................................................... 12-11Exercise 2: Creating the Bank ATM GUI Part 1

(Advanced)................................................................................... 12-12Preparation............................................................................. 12-13Task 1 – Copying the ATMClient Class............................. 12-13Task 2 – Modifying the ATMClient Class.......................... 12-14Task 3 – Compiling the ATMClient Class ......................... 12-14Task 4 – Running the ATMClient Program....................... 12-14Hints........................................................................................ 12-15

Exercise Summary.......................................................................... 12-16

Handling GUI-Generated Events .................................................. 13-1Objectives ......................................................................................... 13-1Exercise 1: Creating the ChatClient GUI Part 2 (Level 1)........ 13-2

Preparation............................................................................... 13-2Task 1 – Modifying the ChatClient Class ......................... 13-3Task 2 – Compiling the ChatClient Class ......................... 13-3Task 3 – Running the ChatClient Program....................... 13-3Hints.......................................................................................... 13-3

Exercise 1: Creating the ChatClient GUI Part 2 (Level 2)........ 13-4Preparation............................................................................... 13-4Task 1 – Modifying the ChatClient Class ......................... 13-4Task 2 – Compiling the ChatClient Class ......................... 13-5Task 3 – Running the ChatClient Program....................... 13-5

Exercise 1: Creating the ChatClient GUI Part 2 (Level 3)........ 13-6Preparation............................................................................... 13-6Task 1 – Modifying the ChatClient Class ......................... 13-6Task 2 – Compiling the ChatClient Class ......................... 13-8Task 3 – Running the ChatClient Program....................... 13-8

Exercise 2: Creating the Bank ATM GUI Part 2(Advanced)..................................................................................... 13-9

Preparation............................................................................. 13-10Task 1 – Modifying the ATMClient Class.......................... 13-10Task 2 – Compiling the ATMClient Class ......................... 13-10Task 3 – Running the BankPrj Project............................... 13-10

Exercise Summary.......................................................................... 13-12

GUI-Based Applications................................................................ 14-1

Objectives ......................................................................................... 14-1Exercise: Creating the ChatClient GUI, Part 3 (Level 1).......... 14-2

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

Page 15: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 15/276

xvCopyright2008Sun Microsystems,Inc. All Rights Reserved.Sun Services, RevisionG.2

Task 1 – Modifying the ChatClient Class ......................... 14-3Task 2 – Compiling the ChatClient Class ......................... 14-3Task 3 – Running the ChatClient Program....................... 14-3

Exercise: Creating the ChatClient GUI, Part 3 (Level 2)..........14-4Preparation............................................................................... 14-4

Task 1 – Modifying the ChatClient Class ......................... 14-4Task 2 – Compiling the ChatClient Class ......................... 14-5Task 3 – Running the ChatClient Program....................... 14-5

Exercise: Creating the ChatClient GUI, Part 3 (Level 3)..........14-6Preparation............................................................................... 14-6Task 1 – Modifying the ChatClient Class ......................... 14-6Task 2 – Compiling the ChatClient Class ......................... 14-9Task 3 – Running the ChatClient Program..................... 14-10

Exercise Summary.......................................................................... 14-11

Threads............................................................................................15-1

Objectives ......................................................................................... 15-1

Exercise: Using Multithreaded Programming (Level 1)............. 15-2Preparation............................................................................... 15-2Task 1 – Creating the PrintMe Class ................................... 15-3Task 2 – Creating the TestThreeThreads Class................15-3Task 3 – Compiling the TestThreeThreads Class............15-3Task 4 – Running the TestThreeThreads Program ......... 15-4

Exercise: Using Multithreaded Programming (Level 2)............. 15-5Preparation............................................................................... 15-5Task 1 – Creating the PrintMe Class ................................... 15-6Task 2 – Creating the TestThreeThreads Class................15-6Task 3 – Compiling the TestThreeThreads Class............15-7Task 4 – Running the TestThreeThreads Program ......... 15-7

Exercise: Using Multithreaded Programming (Level 3)............. 15-8Preparation............................................................................... 15-8Task 1 – Creating the PrintMe Class ................................... 15-8Task 2 – Creating the TestThreeThreads Class................15-9Task 3 – Compiling the TestThreeThreads Class.......... 15-10Task 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-2Preparation............................................................................... 16-4Task 1 – Modifying the ChatClient Class ......................... 16-4Task 2 – Compiling the ChatClient Class ......................... 16-4Task 3 – Running the ChatRoomPrj Project........................ 16-4

Exercise: Creating a Socket Client (Level 2) ................................. 16-6Preparation............................................................................... 16-6Task 1 – Modifying the ChatClient Class ......................... 16-6

Page 16: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 16/276

xvi Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 2 – Compiling the ChatClient Class ......................... 16-7Task 3 – Running the ChatRoomPrj Project........................16-7

Exercise: Creating a Socket Client (Level 3) ................................. 16-9Preparation............................................................................... 16-9Task 1 – Modifying the ChatClient Class ......................... 16-9

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

Page 17: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 17/276

LabPreface-xviiCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

LabPreface

 AboutThisWorkbook

Lab Goals

Upon completion of this workbook, you should be able to:

●   Write a Java™ technology program using the fundamental language

elements: primitive types, reference types, arithmetic operators,relational operators, conditional statements, and iterative statements

●   Write a Java technology program using good object-orientedprogramming concepts and principles: encapsulation, inheritance,interfaces, polymorphism, object association, and multiplicity inassociations

●   Write a robust Java technology program using exception handling,generic collections, and concurrency control

●   Write a rich Java technology program using the graphical user

interface (GUI) application programming interfaces (APIs),input/output (I/O) APIs, and networking APIs

This workbook presents the lab exercises for each module of the StudentGuide.

Page 18: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 18/276

Performing the Exercises

Lab Preface-xviii Java™ ProgrammingLanguageCopyright 2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Performing the Exercises

You have the option to complete any one of three versions of a lab. Todecide which to choose, consult the following descriptions of the levels:

●   Level 1 – This version of the lab provides the least amount of guidance. Each bulleted paragraph provides a task description, butyou must determine your own way of accomplishing each task.

●   Level 2 – This version of the lab provides more guidance. Althougheach step describes what you should do, you must determine whichcommands (and options) to input.

●   Level 3 – This version of the lab is the easiest to accomplish becauseeach step provides exactly what you should input to the system. Thislevel also includes the task solutions for all three levels.

Also, several modules have advanced labs. These labs are optional. Theselabs are intended for more advanced students who complete the primarylabs easily.

Page 19: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 19/276

Conventions

 About This Workbook Lab Preface-xixCopyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Conventions

The following conventions are used in this course to represent varioustraining elements and alternative learning resources.

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.

Courier is also used to indicate programming constructs, such as class

names, methods, and keywords; for example:The getServletInfo method is used to get author information.The java.awt.Dialog class contains Dialog constructor.

Courier bold is used for characters and numbers that you type; forexample:

To list the files in this directory, type:# ls

Courier bold is also used for each line of programming code that is

referenced in a textual description; for example:

1 import java.io.*;2 import javax.servlet.*;3 import javax.servlet.http.*; Notice thejavax.servlet interface is imported to allow access to its life cycle

methods (Line 2).

Courier italics is used for variables and command-line placeholdersthat 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 executerights for filename to world, group, and users.

Page 20: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 20/276

Conventions

Lab Preface-xx Java™ Programming LanguageCopyright 2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Palatino italics is used for book titles, new words or terms, or words thatyou want to emphasize; for example:

Read Chapter 6 in the  User’s Guide.These are called class options.

 Additional Conventions

 Java programming language examples use the following additionalconventions:

●   Method names are not followed with parentheses unless a formal oractual parameter list is shown; for example:

“The doIt method...” refers to any method called doIt.

“The doIt() method...” refers to a method called doIt that takes

no arguments.

●   Line breaks occur only where there are separations (commas),conjunctions (operators), or white space in the code. Broken code isindented four spaces under the starting code.

●   If a command used in the Solaris™ Operating System (Solaris OS) isdifferent from a command used in the Microsoft Windows platform, both commands are shown; for example:

If working in the Solaris OS

$ cd $SERVER_ROOT/bin

If working in Microsoft Windows

C:\> cd %SERVER_ROOT%\bin

Page 21: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 21/276

Lab 1-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 1

GettingStarted

Objectives

Upon completion of this lab, you should be able to:

●   Diagnose simple compilation and runtime errors

●   Create a test program for an existing class

Page 22: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 22/276

Exercise1: Exploring Java™ Program Errors

Lab 1-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Exploring Java™ Program Errors

In this exercise, you view the source of several simple Java programs, andcorrect their compilation and runtime errors.

This exercise contains the following sections:

●   “Task – Correcting Compilation and Runtime Errors”

Preparation

No preparation is needed for this exercise.

Tool Reference – Tool references used in this exercise:

●   Java Development: Java Classes: Opening 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 TestProject project in theexercises/01_intro/exercise1 directory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/01_intro/exercise1 directory.

Task – Correcting Compilation and Runtime Errors

In this task, you are presented with four Java programs that containerrors. The errors can be either compilation or runtime errors. Your job is

to diagnose and fix those errors so the programs will execute.

Page 23: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 23/276

Exercise 1: Exploring Java™ Program Errors

Getting Started Lab 1-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

1. Open the Java file.

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

2. Compile the Java file.

3. If a compilation error occurs, identify the source of the error and fixit.

4. Repeat step 2 and step 3 until there are no more errors.

Tool Reference – Java Development: Java Classes: Modifying JavaClasses: Executing Java Programs

5. Execute the Java program.

6. If a runtime error occurs, identify the source of the error and fix it.

7. Repeat step 5 and step 6 until there are no more errors.

Page 24: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 24/276

Exercise 2: Creating a Test Program (Level 1)

Lab 1-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Creating a Test Program (Level 1)

In this exercise, you create a test program (also known as a test harness) toexercise a pre-provided class. These are the Level 1 instructions thatprovide additional hints.

Figure 1-1 shows the definition of the Account class using a UnifiedModeling Language (UML) Class diagram.

Figure 1-1   Banking Account Class

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”

Preparation

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

Account

+getBalance():double

+withdraw(amt:double):void+deposit(amt:double):void

«constructors»

«methods»

+Account(initBalance:double)

Page 25: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 25/276

Exercise 2: Creating a Test Program (Level 1)

Getting Started Lab 1-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

123

Demonstration – The demonstration for this exercise can be found in thedemos/01_intro/exercise2 directory.

Task 1 – Copying the AccountClass

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

1. Create the BankPrj Java Application Project with the following

characteristics:Project Name: BankPrj

Project Location: projects

Project Folder: projects/BankPrj

Set as Main Project: No

Create Main Class: No

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

2. Copy the pre-provided Account.java source file from theresources/01_intro/exercise2 directory to the sourcepackage of the BankPrj project.

Task 2 – Creating the TestAccountClass

In this task, you complete the following steps to create a newTestAccount Java class.

Tool Reference – Java Development: Java Classes: Creating Java Classes

1. Create a new Java class in the BankPrj project with the followingcharacteristics:

Class Name: TestAccount

Project: BankPrj

Location: Source Packages

Package: default package

Page 26: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 26/276

Exercise 2: Creating a Test Program (Level 1)

Lab 1-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

2. Edit the source file for the TestAccount class to add a mainmethod. 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 printout the balance of the Account object to the standard output stream.

Task 3 – Compiling the TestAccountClass

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

Task 4 – Running the TestAccountProgram

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

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

Final account balance is: 3.0

Page 27: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 27/276

Exercise 2: Creating a Test Program (Level 2)

Getting Started Lab 1-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.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 additionalhints.

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”

PreparationNo 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

123

Demonstration – The demonstration for this exercise can be found in thedemos/01_intro/exercise2 directory.

Page 28: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 28/276

Exercise 2: Creating a Test Program (Level 2)

Lab 1-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Copying the AccountClass

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

1. Create the BankPrj Java Application Project with the followingcharacteristics:

Project Name: BankPrj

Project Location: projects

Project Folder: projects/BankPrj

Set as Main Project: No

Create Main Class: No

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

2. Copy the pre-provided Account.java source file from theresources/01_intro/exercise2 directory to the sourcepackage of the BankPrj project.

Task 2 – Creating the TestAccountClassIn this task, you complete the following steps to create a newTestAccount 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.

Page 29: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 29/276

Exercise 2: Creating a Test Program (Level 2)

Getting Started Lab 1-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.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 getBalancemethod to retrieve the new account balance anduse the System.out.println method to display the balance to the

standard output stream.

Task 3 – Compiling the TestAccountClass

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

Task 4 – Running the TestAccountProgram

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

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

Final account balance is: 3.0

Page 30: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 30/276

Exercise 2: Creating a Test Program (Level 3)

Lab 1-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

PreparationNo 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

123

Demonstration – The demonstration for this exercise can be found in thedemos/01_intro/exercise2 directory.

Page 31: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 31/276

Exercise 2: Creating a Test Program (Level 3)

Getting Started Lab 1-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Copying the AccountClass

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

1. Create the BankPrj Java Application Project with the followingcharacteristics:

Project Name: BankPrj

Project Location: projects

Project Folder: projects/BankPrj

Set as Main Project: No

Create Main Class: No

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

2. Copy the pre-provided Account.java source file from theresources/01_intro/exercise2 directory to the sourcepackage of the BankPrj project.

Task 2 – Creating the TestAccountClassIn this task, you complete the following steps to create a newTestAccount 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

}}

Page 32: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 32/276

Exercise 2: Creating a Test Program (Level 3)

Lab 1-12 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

3. Declare a variable of type Account and initialize that variable bycreating an instance of the Account class with an initial balance of 100.

 Account acct = new Account(100.0);

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

acct.deposit(50.0);

5. Use the withdraw method to subtract 147 from the account.

acct.withdraw(147.0);

6. Use the getBalancemethod to retrieve the new account balance anduse the System.out.println method to display the balance to thestandard output stream.

System.out.println(“Final account balance is ” + acct.getBalance());

Task 3 – Compiling the TestAccountClass

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

Task 4 – Running the TestAccountProgram

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

program again.

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

Final account balance is: 3.0

Page 33: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 33/276

Exercise Summary

Getting Started Lab 1-13Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 34: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 34/276

Page 35: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 35/276

Lab 2-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 2

Object-OrientedProgramming

Objectives

Upon completion of this lab, you should be able to:

●   Use the Java API documentation to research a class

●   Explore information hiding and encapsulation

●   Use packages to organize your classes

Page 36: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 36/276

Exercise1: Using theJava API Documentation

Lab 2-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Using the Java API Documentation

In this exercise, you explore the Java™ Platform, Standard Edition 6 (JavaSE 6) API documentation to explore the methods of a class.

This exercise contains the following sections:

●   “Task – Using the Java API Documentation”

Preparation

You must have a web browser window open.

Task – Using the Java API DocumentationComplete the following steps to use the Java API documentation:

1. Open the Java™ Platform, Standard Edition 6 API Specification Webpage in the browser.

Note – The API documentation for Java Platform SE 6 can be found athttp://java.sun.com/javase/6/docs/api.

2. Select the java.text package in the package list in the upper-leftcorner panel of the API frameset.

3. Select the NumberFormat class in the class list in the lower-left panel.

4. Read about the class in the top part of the documentation windowon the right panel of the frameset. Review the format and parsemethods.

Page 37: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 37/276

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

Object-Oriented Programming Lab 2-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

In this exercise, you explore the purpose of proper object encapsulation. Youcreate a class in two steps to demonstrate the use of information hiding. Inthis version, you create an Account class with public data members. Youwill then create a test program that demonstrates the danger of using thepublic data directly.

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

Figure 2-1   UML Class Diagram of  Account With No Hiding

There is only one business rule that applies to the Account class: Thebalance of the bank account must never go below zero . In this exercise, you willdiscover that the Account class cannot ensure this business rule.

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”

Account

«constructors»

+Account(initBalance:double)

+balance : double

Page 38: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 38/276

Exercise2: Exploring Encapsulation, Version 1 (Level 1)

Lab 2-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

No preparation is needed for this exercise.

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

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

directory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/02_OOP/exercise2 directory.

Task 1 – Deleting the AccountClass

Tool Reference – Java Development: Other Files: Deleting Files

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

Task 2 – Creating the AccountClass

In this task, you create the Account class according to the UML diagramin 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 anda constructor according to the UML diagram in Figure 2-1. Initialize thebalance instance variable with the parameter of the constructor.

Page 39: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 39/276

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

Object-Oriented Programming Lab 2-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 3 – Creating the TestAccount2Class

In this task, you create the TestAccount2 class with the followingcharacteristics:

Class Name: TestAccount2Project: 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 thestandard output stream.

Task 4 – Compiling the TestAccount2Class

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

Task 5 – Running the TestAccount2Program

In this task, you run the TestAccount2 program.

The output should be similar to the following:

Final account balance is -3.0

Page 40: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 40/276

Exercise2: Exploring Encapsulation, Version 1 (Level 2)

Lab 2-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.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.

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”

Preparation

No preparation is needed for this exercise.

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

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/02_OOP/exercise2 directory.

Page 41: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 41/276

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

Object-Oriented Programming Lab 2-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Deleting the AccountClass

Tool Reference – Java Development: Other Files: Deleting Files

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

Task 2 – Creating the AccountClass

In this task, you complete the following steps to create a Java class named Account:

1. Create the Account class with the following characteristics:

Class Name: Account

Project: BankPrj

Location: Source Packages

Package: default package

2. Add the balance instance variable.

3. Add a constructor that sets the balance instance variable to theinitial balance argument passed to the constructor.

Task 3 – Creating theTestAccount2

Class

In this task, you complete the following steps to create a Java class namedTestAccount2:

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 Accountnamed acct. Also, in the same statement, initialize the variableacct to a new instance of  Account by passing 100.00 to theconstructor as the initial balance.

 b. Use the addition operator to add 47 to the account object’s balance.

Page 42: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 42/276

Exercise2: Exploring Encapsulation, Version 1 (Level 2)

Lab 2-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

c. Use the subtraction operator to subtract 150 from the accountobject’s balance.

d. Use the System.out.printlnmethod to display the balance tothe standard output stream.

Task 4 – Compiling the TestAccount2Class

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

Task 5 – Running the TestAccount2Program

In this task, you run the TestAccount2 program.

The output should be similar to the following:

Final account balance is -3.0

Page 43: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 43/276

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

Object-Oriented Programming Lab 2-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

Preparation

No preparation is needed for this exercise.

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

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

1

23

Demonstration – The demonstration for this exercise can be found in thedemos/02_OOP/exercise2 directory.

Page 44: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 44/276

Exercise2: Exploring Encapsulation, Version 1 (Level 3)

Lab 2-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Deleting the AccountClass

Tool Reference – Java Development: Other Files: Deleting Files

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

Task 2 – Creating the AccountClass

In this task, you complete the following steps to create a Java class named Account:

1. Create the Account class with the following characteristics:

Class Name: Account

Project: BankPrj

Location: Source Packages

Package: default package

2. Add the balance instance variable.

public double balance;

3. Add a constructor that sets the balance to the initial balanceargument passed to the constructor.

public Account(double initBalance) {

balance = initBalance;}

Task 3 – Creating the TestAccount2Class

In this task, you complete the following steps to create a Java class namedTestAccount2:

1. Create the TestAccount2 class with the following characteristics:

Class Name: TestAccount2Project: BankPrj

Location: Source Packages

Package: default package

Page 45: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 45/276

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

Object-Oriented Programming Lab 2-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

2. Add the main method:

public static void main(String[] args) {// code here

}

3. Declare a variable within the main method of type Account named

acct. Also, in the same statement, initialize the variable acct to anew instance of  Account by passing 100.00 to the constructor as theinitial 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.

acct.balance = acct.balance - 150.0;

6. Use the System.out.println method to display the balance to thestandard output stream.

System.out.println(“Final account balance is ” + acct.balance);

Task 4 – Compiling the TestAccount2Class

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

Task 5 – Running the TestAccount2Program

In this task, you run the TestAccount2 program.

The output should be similar to the following:

Final account balance is -3.0

Page 46: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 46/276

Exercise3: Exploring Encapsulation, Version 2 (Level 1)

Lab 2-12 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

In this exercise, you explore the purpose of proper object encapsulation. Youmodify the Account class to hide its data member and provide publicmethods to manipulate the balance. You then use the test program thatyou created in Lab 1 to test that the business rule (balance must not fallbelow zero) is satisfied.

Figure 2-2 shows the UML class diagram of the Account class that youcreate. 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 methodremoves money from the account. The getBalance method returns thecurrent value of the balance instance variable.

Figure 2-2   UML Class Diagram of  Account With Information Hiding

Remember, there is still one business rule that must be maintained:  Thebalance of the bank account must never go below zero. This business ruleshould 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.

Account

+getBalance():double

+withdraw(amt:double):void

+deposit(amt:double):void

«constructors»

«methods»

+Account(initBalance:double)

-balance : double

Page 47: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 47/276

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

Object-Oriented Programming Lab 2-13Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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 BankPrj project in the projectsdirectory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/02_OOP/exercise3 directory.

Task 1 – Modifying the AccountClass

In this task, you modify the Account class source file. This class mustsatisfy the UML diagram in Figure 2-2.

Task 2 – Modifying the TestAccountClass

In this task, you modify the TestAccount class to deposit 47 to and

withdraw 150 from the Account object.

Task 3 – Compiling the TestAccountClass

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

Task 4 – Running the TestAccountProgram

In this task, you run the TestAccount program. The output should besimilar to the following:

Final account balance is 147.0

The 150 withdraw command did not take effect, because it would havemade the balance drop below zero. However, the Account object did nottell program that the withdraw command failed, it ignored the command.You will fix this problem in future exercises.

Page 48: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 48/276

Exercise3: Exploring Encapsulation, Version 2 (Level 2)

Lab 2-14 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.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.

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.

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 BankPrj project in the projectsdirectory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/02_OOP/exercise3 directory.

Task 1 – Modifying the AccountClass

In this task, you complete the following steps to modify the Accountclass:

1. Change the balance instance variable from public to private.

2. Add the depositmethod that takes an amount (of type double) andadds that amount to the balance. Save the new balance in theinstance variable.

Page 49: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 49/276

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

Object-Oriented Programming Lab 2-15Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

3. Add the withdraw method that takes an amount (of type double)and subtracts that amount from the balance. Save the new balance inthe instance variable.

This operation might set the balance to a value below zero if theamount to withdraw is larger than the current balance. You must use

a conditional statement to verify that the amount is not greater thanthe balance before doing the subtraction. The conditional statementlooks like the following:

if (   <boolean_test> ) {<statement_when_true>*

} else {<statement_when_false>*

}

4. Add the getBalance method to return the balance instancevariable.

Task 2 – Modifying the TestAccountClass

In this task, you complete the following steps to modify the TestAccountclass:

1. Change the amount in the call to the deposit method to 47.0.

2. Change the amount in the call to the withdraw method to 150.0.

Task 3 – Compiling the TestAccountClass

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

Task 4 – Running the TestAccountProgram

In this task, you run the TestAccount program. The output should besimilar to the following:

Final account balance is 147.0

Page 50: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 50/276

Exercise3: Exploring Encapsulation, Version 2 (Level 3)

Lab 2-16 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

PreparationThere is no preparation for this exercise.

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 BankPrj project in the projectsdirectory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/02_OOP/exercise3 directory.

Task 1 – Modifying the AccountClass

In this task, you complete the following steps to modify the Accountclass:

1. Change the balance instance variable from public to private.

private double balance;

Page 51: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 51/276

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

Object-Oriented Programming Lab 2-17Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

2. Add the depositmethod that takes an amount (of type double) andadds that amount to the balance. Save the new balance in thebalance instance variable.

public void deposit(double amt) {balance = balance + amt;

}3. Add the withdraw method that takes an amount (of type double)

and subtracts that amount from the balance. Save the new balance inthe balance instance variable.

public void withdraw(double amt) {if ( amt <= balance ) {balance = balance - amt;

}}

4. Add the getBalance method to return the balance instance

variable.

public double getBalance() {return balance;

}

Task 2 – Modifying the TestAccountClass

In this task, you complete the following steps to modify the TestAccountclass:

1. Change the amount in the call to the deposit method to 47.0.

acct.deposit(47.0);

2. Change the amount in the call to the withdraw method to 150.0.

acct.withdraw(150.0);

Task 3 – Compiling the TestAccountClass

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

Task 4 – Running the TestAccountProgram

In this task, you run the TestAccount program. The output should besimilar to the following:

Final account balance is 147.0

Page 52: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 52/276

Exercise4: Creating Java Packages

Lab 2-18 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 4: Creating Java Packages

In this exercise, you will place the Account class and TestAccount classinto different packages.

Figure 2-3 shows a UML diagram of the packages that you will create inthis exercise. The Account class is placed in the com.mybank.domainpackage and the TestAccount class is placed in the com.mybank.testpackage.

Figure 2-3   The Package Structure of the Banking Project

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”

com.mybank

domain

Account

+getBalance():double

+withdraw(amt:double):void

+deposit(amt:double):void

«constructors»

«methods»

+Account(initBalance:double)

-balance : double

test

TestAccount

+main(args:String[])

Page 53: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 53/276

Exercise 4: Creating Java Packages

Object-Oriented Programming Lab 2-19Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

There is no preparation for this exercise.

Tool Reference – Tool references used in this exercise:●   Java Development: Java Packages: Creating Java Packages

●   Java Development: Java Classes: Moving Java Classes (withoutrefactoring)

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/02_OOP/exercise4 directory.

Task 1 – Creating the Java Packages

Tool Reference – Java Development: Java Packages: Creating JavaPackages

In this task, you create two Java Source Packages in the BankPrj projectwith the following names:

com.mybank.domaincom.mybank.test

Task 2 – Moving and Modifying the AccountClass

In this task, you complete the following steps to move the Account classand add the appropriate package statement to the class:

Tool Reference – Java Development: Java Classes: Moving Java Classes(without refactoring)

Page 54: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 54/276

Exercise4: Creating Java Packages

Lab 2-20 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

1. Move the Account class source file to the com.mybank.domainpackage.

2. Add the following package statement at the top of the Accountclass:

package com.mybank.domain;

Task 3 – Moving the TestAccountClass

In this task, you complete the following steps to move the TestAccountclass and add the appropriate package and import statements to the class:

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

2. Add the following package statement at the top of the

TestAccount class:package com.mybank.test;

3. Add the following import statement under the package statement inthe TestAccount class:

import com.mybank.domain.Account;

Task 4 – Compiling the TestAccountClass

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

Task 5 – Running the TestAccountProgram

In this task, you run the TestAccount program. The code has notchanged, so the output should be similar to the following:

Final account balance is 147.0

Page 55: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 55/276

Exercise Summary

Object-Oriented Programming Lab 2-21Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 56: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 56/276

Page 57: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 57/276

Lab 3-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 3

Identifiers,Keywords, andTypes

Objectives

Upon completion of this lab, you should be able to:

●   Explore reference variable assignment

●   Use a reference variable to encode an object association

Page 58: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 58/276

Exercise 1: Investigating Reference Assignment

Lab 3-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Investigating Reference Assignment

In this exercise, you will investigate reference variables, object creation,and reference variable assignment.

Figure 3-1 shows a class diagram for the MyPoint class that is provided inthe exercise directory. Notice that the instance variables, x and y, are bothpublic so you can access these data members in your test programdirectly. Also, the toString method is used when you print the objectusing the System.out.println method.

Figure 3-1   UML Class Diagram for the MyPoint Class

Your task is to create a test program that explores object references.

This exercise contains the following sections:

●   “Task 1 – Creating the TestMyPoint Class”

●   “Task 2 – Compiling the TestMyPoint Class”

●   “Task 3 – Running the TestMyPoint Program”

Preparation

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 theexercises/03_types/exercise1 directory.

MyPoint

+toString() : String

+x : int+y : int

Page 59: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 59/276

Exercise 1: Investigating Reference Assignment

Identifiers, Keywords, and Types Lab 3-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

123

Demonstration – The demonstration for this exercise can be found in thedemos/03_types/exercise1 directory.

Task 1 – Creating the TestMyPointClass

Tool Reference – Java Development: Java Application Projects: OpeningProjects

Complete the following steps:

1. Open the PointProject project in theexercises/03_types/exercise1 directory.

2. Create the TestMyPoint class with the following characteristics:

Class Name: TestMyPoint

Project: PointProject

Location: Source Packages

Package: default package

3. Create a main method, and complete the following steps in the mainmethod:

a. Declare two variables of type MyPoint and called start andend. Assign both of these variables a new MyPoint object.

 b. Set the x and y values of start to 10. Set the x value of end to20 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 outputwill 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.

Page 60: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 60/276

Exercise 1: Investigating Reference Assignment

Lab 3-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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.

Task 2 – Compiling the TestMyPointClass

In this task, you compile the TestMyPoint class.

Task 3 – Running the TestMyPointProgram

In this task, you run the TestMyPoint program.

The output should look similar to the following:

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

Stray point is [20,30]End point is [20,30]

Stray point is [47,50]End point is [47,50]Start point is [10,10]

The values reported by end reflect the change made in stray, indicatingthat both variables refer to the same MyPoint object. However, start hasnot changed, which indicates that it is independent of the other twovariables.

Page 61: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 61/276

Exercise2: Creating Customer Accounts (Level 1)

Identifiers, Keywords, and Types Lab 3-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Creating Customer Accounts (Level 1)

In this exercise, you expand the Banking project by adding a Customerclass.

Figure 3-2 shows the UML class diagram of the Customer class and itsrelationship to the Account class. This relationship can be read as: Acustomer has one account.

Figure 3-2   UML Class Diagram for the Customer Class

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”

com.mybank.domain

Account

+getBalance():double

+withdraw(amt:double):void

+deposit(amt:double):void

«constructors»

«methods»

+Account(initBalance:double)

-balance : double-firstName : String

+getFirstName():String

+getAccount():Account

-lastName : String

+getLastName():String

+Customer(f:String, l:String)

+setAccount(acct:Account):void

1

-account : Account

Customer

«constructors»

«methods»

has-a

Page 62: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 62/276

Exercise2: Creating Customer Accounts (Level 1)

Lab 3-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

No preparation is needed for this exercise.

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

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

directory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/03_types/exercise2 directory.

Task 1 – Creating the CustomerClass

In this task, you create the Customer class to satisfy the UML diagram inFigure 3-2. The class has the following characteristics:

Class Name: Customer

Project: BankPrj

Location: Source Packages

Package: com.mybank.domain

In the constructor, initialize the firstName and lastName instancevariables with the constructor parameters.

Task 2 – Copying the TestBankingClass

In this task, you copy the TestBanking.java file from theresources/03_types/exercise2directory into the com.mybank.testsource package of the BankPrj project.

Page 63: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 63/276

Exercise2: Creating Customer Accounts (Level 1)

Identifiers, Keywords, and Types Lab 3-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 3 – Compiling the TestBankingClass

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

Task 4 – Running the TestBankingProgram

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

Creating the customer Jane Smith.Creating her account with a 500.00 balance.Withdraw 150.00Deposit 22.50

Withdraw 47.62Customer [Smith, Jane] has a balance of 324.88

Page 64: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 64/276

Exercise2: Creating Customer Accounts (Level 2)

Lab 3-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Creating Customer Accounts (Level 2)

In this exercise you expand the Banking project by adding a Customerclass. These are the Level 2 instructions, which provide additional hints.

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

No preparation is needed for this exercise.

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

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/03_types/exercise2 directory.

Page 65: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 65/276

Exercise2: Creating Customer Accounts (Level 2)

Identifiers, Keywords, and Types Lab 3-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Creating the CustomerClass

In this task, you create the Customer class.

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

3. Declare a public constructor that takes two parameters (f and l) thatpopulate the object instance variables.

4. Declare two public accessors for the object instance variables; themethods getFirstName and getLastName return the appropriateinstance variable.

5. Declare the getAccount method to retrieve the account instancevariable.

6. Declare the setAccount method to assign the account instancevariable.

Task 2 – Copying the TestBankingClass

In this task, you copy the TestBanking.java file from theresources/03_types/exercise2directory into the com.mybank.testsource package of the BankPrj project.

Task 3 – Compiling the TestBankingClass

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

Page 66: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 66/276

Exercise2: Creating Customer Accounts (Level 2)

Lab 3-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 4 – Running the TestBankingProgram

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

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

Page 67: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 67/276

Exercise2: Creating Customer Accounts (Level 3)

Identifiers, Keywords, and Types Lab 3-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Creating Customer Accounts (Level 3)

In this exercise you will expand the Banking project by adding aCustomer class. These are the Level 3 instructions, which provideadditional 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”

PreparationNo preparation is needed for this exercise.

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

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/03_types/exercise2 directory.

Page 68: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 68/276

Exercise2: Creating Customer Accounts (Level 3)

Lab 3-12 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Creating the CustomerClass

In this task, you create the Customer class.

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

private String firstName;private String lastName;private Account account;

3. Declare a public constructor that takes two parameters (f and l) thatpopulate the object instance variables.

public Customer(String f, String l) {firstName = f;lastName = l;

}

4. Declare two public accessors for the object instance variables; the

methods getFirstName and getLastName return the appropriateinstance variable.

public String getFirstName() {return firstName;

}public String getLastName() {return lastName;

}

5. Declare the getAccount method to retrieve the account instancevariable.

public Account getAccount() {return account;

}

6. Declare the setAccount method to assign the account instancevariable.

public void setAccount(Account acct) {account = acct;

}

Page 69: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 69/276

Exercise2: Creating Customer Accounts (Level 3)

Identifiers, Keywords, and Types Lab 3-13Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 2 – Copying the TestBankingClass

In this task, you copy the TestBanking.java file from theresources/03_types/exercise2directory into the com.mybank.testsource package of the BankPrj project.

Task 3 – Compiling the TestBankingClass

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

Task 4 – Running the TestBankingProgram

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

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

Page 70: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 70/276

Exercise Summary

Lab 3-14 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 71: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 71/276

Lab 4-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 4

ExpressionsandFlowControl

Objectives

Upon completion of this lab, you should be able to:

●   Use a simple for loop

●   Using conditional statements in business logic

●   (Optional) Use nested loops to implement a string search operation

Page 72: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 72/276

Exercise1: Using LoopsandBranching Statements

Lab 4-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Using Loops and Branching Statements

In this exercise, you will use a simple integer loop and branchingstatements to play a fictitious game of  foo bar baz.

Create a program that loops from 1–50 and prints each value on aseparate line. Also print foo for every multiple of three, bar for everymultiple of five, and baz for every multiple of seven. For example:

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

123 foo45 bar6 foo7 baz89 foo10 bar1112 foo1314 baz15 foo bar16

and so on.

This exercise contains the following sections:

●   “Task 1 – Creating the FooBarBaz Class”

●   “Task 2 – Compiling the FooBarBaz Class”

●   “Task 3 – Running the FooBarBaz Program”

Page 73: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 73/276

Exercise1: Using Loops and Branching Statements

Expressions and Flow Control Lab 4-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

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: 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 LoopProject project in the

exercises/04_stmts/exercise1 directory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/04_stmts/exercise1 directory.

Task 1 – Creating the FooBarBazClass

Complete the following steps:1. Open the LoopProject project in the

exercises/04_stmts/exercise1 directory.

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

Page 74: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 74/276

Exercise1: Using LoopsandBranching Statements

Lab 4-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 2 – Compiling the FooBarBazClass

In this task, you compile the FooBarBaz program.

Task 3 – Running the FooBarBazProgram

In this task, you run the FooBarBaz program.

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

Hints

These hints might help you to solve this exercise:

●   Use the System.out.print method to print a string or valuewithout printing a new line character. You can use multiple printmethods to print a single line of text. You can use a single printlnmethod, with no arguments, to print a new line character.

●   The % operator calculates an integer remainder.

Page 75: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 75/276

Exercise 2: UsingConditional Statements in the AccountClass (Level 1)

Expressions and Flow Control Lab 4-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Using Conditional Statements in the AccountClass (Level 1)

In this exercise, you modify the withdraw method to return a boolean

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 andwithdraw methods; these methods must now return a boolean value toindicate the success (true) or failure (false) of the operation.

Figure 4-1   UML Class Diagram of Banking Project

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.

com.mybank.domain

Account

+getBalance():double

+withdraw(amt:double):boolean

+deposit(amt:double):boolean

«constructors»

«methods»

+Account(initBalance:double)

-balance : double-firstName : String

+getFirstName():String

+getAccount():Account

-lastName : String

+getLastName():String

+Customer(f:String, l:String)

+setAccount(acct:Account):void

1

-account : Account

Customer

«constructors»

«methods»

has-a

Page 76: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 76/276

Exercise2: Using Conditional Statements in the AccountClass (Level 1)

Lab 4-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Tool Reference – Tool references used in this exercise:

●   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: Executing Java Programs

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

12

3

Demonstration – The demonstration for this exercise can be found in thedemos/04_stmts/exercise2 directory.

Task 1 – Modifying the Account Class

In this task, you modify the Account class source file. This class mustsatisfy the UML diagram in Figure 4-1. In particular, the deposit andwithdraw methods must return a boolean value as described previouslyin this exercise.

Task 2 – Deleting the Current TestBanking Class

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

Task 3 – Copying the TestBankingClass

In this task, you copy the new version of the TestBanking.javafile fromthe resources/04_stmts/ directory into the com.mybank.test packageof the BankPrj project.

Task 4 – Compiling the TestBankingClass

In this task, you compile the TestBanking class.

Page 77: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 77/276

Exercise 2: UsingConditional Statements in the AccountClass (Level 1)

Expressions and Flow Control Lab 4-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 5 – Running the TestBankingProgram

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

Creating the customer Jane Smith.Creating her account with a 500.00 balance.Withdraw 150.00: trueDeposit 22.50: trueWithdraw 47.62: trueWithdraw 400.00: falseCustomer [Smith, Jane] has a balance of 324.88

Page 78: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 78/276

Exercise2: Using Conditional Statements in the AccountClass (Level 2)

Lab 4-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Using Conditional Statements in the AccountClass (Level 2)

In this exercise, you will modify the withdrawmethod to return a 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”

●   “Task 5 – Running the TestBanking Program”

Preparation

There is no preparation required for this exercise.

Tool Reference – Tool references used in this exercise:

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

1

23

Demonstration – The demonstration for this exercise can be found in thedemos/04_stmts/exercise2 directory.

Page 79: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 79/276

Exercise 2: UsingConditional Statements in the AccountClass (Level 2)

Expressions and Flow Control Lab 4-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Modifying the AccountClass

In this task, you complete the following steps to modify the Accountclass:

1. Modify the depositmethod. 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 thewithdrawal is less than the current balance. If this is the case, thenthe 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

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

Task 3 – Copying the TestBankingClass

In this task, you copy the new version of the TestBanking.javafile fromthe resources/04_stmts/ directory into the com.mybank.test packageof the BankPrj project.

Task 4 – Compiling the TestBankingClass

In this task, you compile the TestBanking class.

Task 5 – Running the TestBankingProgram

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

Creating the customer Jane Smith.Creating her account with a 500.00 balance.Withdraw 150.00: trueDeposit 22.50: trueWithdraw 47.62: trueWithdraw 400.00: falseCustomer [Smith, Jane] has a balance of 324.88

Page 80: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 80/276

Exercise2: Using Conditional Statements in the AccountClass (Level 3)

Lab 4-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Using Conditional Statements in the AccountClass (Level 3)

In this exercise, you will modify the withdraw method to return a

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”

●   “Task 5 – Running the TestBanking Program”

Preparation

There is no preparation required for this exercise.

Tool Reference – Tool references used in this exercise:

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

1

23

Demonstration – The demonstration for this exercise can be found in thedemos/04_stmts/exercise2 directory.

Page 81: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 81/276

Exercise 2: UsingConditional Statements in the AccountClass (Level 3)

Expressions and Flow Control Lab 4-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Modifying the AccountClass

In this task, you complete the following steps to modify the Accountclass:

1. Modify the depositmethod. 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 thewithdrawal is less than the current balance. If this is the case, thenthe withdraw operation is successful and must return true;

otherwise the operation fails and the method must return false.public boolean withdraw(double amt) {

  boolean result = false; // assume operation failure  if ( amt <= balance ) {  balance = balance - amt;  result = true; // operation succeeds  }  return result;  }

Task 2 – Deleting the Current TestBanking Class

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

Task 3 – Copying the TestBankingClass

In this task, you copy the new version of the TestBanking.javafile fromthe resources/04_stmts/ directory into the com.mybank.test package

of the BankPrj project.

Task 4 – Compiling the TestBankingClass

In this task, you compile the TestBanking class.

Page 82: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 82/276

Exercise2: Using Conditional Statements in the AccountClass (Level 3)

Lab 4-12 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 5 – Running the TestBankingProgram

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

Creating the customer Jane Smith.Creating her account with a 500.00 balance.Withdraw 150.00: trueDeposit 22.50: trueWithdraw 47.62: trueWithdraw 400.00: falseCustomer [Smith, Jane] has a balance of 324.88

Page 83: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 83/276

Exercise3: Using Nested Loops (Advanced)

Expressions and Flow Control Lab 4-13Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 3: Using Nested Loops (Advanced)

In this exercise, you use nested loops to implement a string searchoperation.

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 exercisesare optional and should only be attempted if you completed all of theprevious exercises for this module.

Preparation

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: 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 AdvancedLoopProject project in theexercises/04_stmts/exercise3 directory.

1

23

Demonstration – The demonstration for this exercise can be found in thedemos/04_stmts/exercise3 directory.

Page 84: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 84/276

Exercise3: Using Nested Loops (Advanced)

Lab 4-14 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Writing the isSubStringMethod

In this task, you open the AdvancedLoopProject project in theexercises/04_stmts/exercise3 directory, open theTestIsSubString class, and write the isSubString method. The

method searches for a specific string within another string; the methodmust return true if the former exists in the latter string. For example:isSubString("cat", "The cat in the hat.") is true, butisSubString("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

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

Task 2 – Compiling the TestIsSubStringClass

In this task, you compile the TestIsSubString class.

Task 3 – Running the TestIsSubStringProgram

In this task, you run the TestIsSubString program. The output of theprogram should be similar to the example shown in ‘‘Task 1 – Writing theisSubString Method’’ on page L4-14.

Page 85: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 85/276

Exercise3: Using Nested Loops (Advanced)

Expressions and Flow Control Lab 4-15Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Hints

These hints might help you to solve this exercise.

●   Use the charAt(int index)method in the String class to retrieve

a specific character from a string; the index starts with zero. Forexample. "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.

Page 86: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 86/276

Exercise Summary

Lab 4-16 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 87: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 87/276

Lab 5-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 5

 Arrays

Objectives

Upon completion of this lab, you should be able to:

●   Declare, create, and manipulate one-dimensional primitive arrays

●   Use an array to represent a one-to-many object relationship

Page 88: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 88/276

Exercise 1 – Using Primitive Arrays (Level 2)

Lab 5-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1 – Using Primitive Arrays (Level 2)

In this exercise, you declare, create, and manipulate one-dimensionalarrays of primitive types.

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

There is no preparation 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 ArrayProject project in theexercises/05_arrays/exercise1 directory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/05_arrays/exercise1 directory.

Task 1 – Creating the TestArraysClassComplete the following steps:

1. Open the ArrayProject project in theexercises/05_arrays/exercise1 directory.

Page 89: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 89/276

Exercise 1 – Using Primitive Arrays (Level 2)

 Arrays Lab 5-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

2. Create the TestArrays class with the following characteristics:

Class Name: TestArrays

Project: ArrayProject

Location: Source Packages

Package: default package

3. Add a main method. In the main method, declare two variablescalled array1 and array2. They should be of type int[] (array of int).

4. Using the curly-brace notation, {}, initialize array1 to the first eightprime numbers: 2, 3, 5, 7, 11, 13, 17, and 19.

5. Display the contents of array1. You might want to use theprintArray method (see ‘‘Hint’’ on page L5-4) to display theseinteger arrays.

6. Assign the array2 variable equal to the array1. Modify the evenindexed element in array2 to be equal to the index value (forexample, array2[0] = 0; and array2[2] = 2; and so on). Printout array1.

Task 2 – Compiling the TestArraysClass

In this task, you compile the TestArrays class.

Task 3 – Running the TestArraysProgram

In this task, you run the TestArrays program. The output should besimilar 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?

Page 90: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 90/276

Exercise 1 – Using Primitive Arrays (Level 2)

Lab 5-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Hint

The printArray support method might help you to solve this exercise, asfollows:

public static void printArray(int[] array) {System.out.print(’<’);for ( int i = 0; i < array.length; i++ ) {// print an elementSystem.out.print(array[i]);// print a comma delimiter if not the last elementif ( (i + 1) < array.length ) {System.out.print(", ");

}}System.out.print(’>’);

}

Note – You can also use the java.util.Arrays.toString method togenerate a string representation of an array. For example:System.out.println(Arrays.toString(array1));

Page 91: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 91/276

Exercise 1 – Using Primitive Arrays (Level 3)

 Arrays Lab 5-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1 – Using Primitive Arrays (Level 3)

In this exercise, you declare, create, and manipulate one-dimensionalarrays of primitive types.

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

There is no preparation 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 exercises/05_arrays/exercise1directory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/05_arrays/exercise1 directory.

Task 1 – Creating the TestArraysClassComplete the following steps:

1. Open the ArrayProject project in theexercises/05_arrays/exercise1 directory.

Page 92: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 92/276

Exercise 1 – Using Primitive Arrays (Level 3)

Lab 5-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

2. Create the TestArrays class with the following characteristics:

Class Name: TestArrays

Project: ArrayProject

Location: Source Packages

Package: default package

3. Add a main method. In the main() method, declare two variablescalled array1 and array2. They should be of type int[] (array of int).

public class TestArrays {public static void main(String[] args) {int[] array1;

  int[] array2;// insert code here

}

}

4. Using the curly-brace notation, {}, initialize array1 to the first eightprime numbers: 2, 3, 5, 7, 11, 13, 17, and 19.

int[] array1 = { 2, 3, 5, 7, 11, 13, 17, 19 };  int[] array2;

5. Display the contents of array1. You might want to use theprintArray method (see ‘‘Hint’’ on page L5-4) to display theseinteger arrays.

System.out.print("array1 is ");

  printArray(array1);  System.out.println();

6. Assign the array2 variable equal to the array1. Modify the evenindexed element in array2 to be equal to the index value (forexample, array2[0] = 0; and array2[2] = 2; and so on). Printout 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();

Page 93: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 93/276

Exercise 1 – Using Primitive Arrays (Level 3)

 Arrays Lab 5-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 2 – Compiling the TestArraysClass

In this task, you compile the TestArrays class.

Task 3 – Running the TestArraysProgram

In this task, you run the TestArrays program. The output should besimilar to the following:

array1 is <2, 3, 5, 7, 11, 13, 17, 19>array1 is <0, 3, 2, 7, 4, 13, 6, 19>

Page 94: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 94/276

Exercise2 – UsingArrays to Represent One-to-Many Associations (Level 1)

Lab 5-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

In this exercise, you use arrays to implement the association between a

 bank and its multiple customers.

Figure 5-1 shows the UML class diagram of the Banking Project. Yourassignment is to create the Bank class. A bank object keeps track of anassociation between itself and its customers. You implement thisone-to-many association with an array of customer objects. You will alsoneed to keep an integer instance variable that keeps track of how manycustomers currently exist in the bank.

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”

com.mybank.domain

-customers : Customer[]

+addCustomer(f:String, l:String)

+getCustomer(index:int):Customer

-numberOfCustomers : int

+getNumOfCustomers():int

+Bank()

0..*

Bank

«constructors»

«methods»

serves

Customer Account1has-a

Page 95: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 95/276

Exercise 2 – UsingArrays to Represent One-to-Many Associations (Level 1)

 Arrays Lab 5-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

There is no preparation for this exercise.

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

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/05_arrays/exercise2 directory.

Task 1 – Creating the BankClass

In this task, you create the Bank class that must satisfy the UML diagramin Figure 5-1 on page L5-8. The class has the following characteristics:

Class Name: Bank

Project: BankPrj

Location: Source Packages

Package: com.mybank.domain

Task 2 – Deleting the Current TestBankingClass

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

Page 96: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 96/276

Exercise2 – UsingArrays to Represent One-to-Many Associations (Level 1)

Lab 5-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 3 – Copying the TestBankingClass

In this task, you copy the TestBanking.java file from theresources/05_arrays directory to the com.mybank.test sourcepackage of the BankPrj project.

Task 4 – Compiling the TestBankingClass

In this task, you compile the TestBanking class.

Task 5 – Running the TestBankingProgram

In this task, you run the TestBanking program. The output should be

similar to the following:

Customer [1] is Simms, JaneCustomer [2] is Bryant, OwenCustomer [3] is Soley, TimCustomer [4] is Soley, Maria

Page 97: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 97/276

Exercise 2 – UsingArrays to Represent One-to-Many Associations (Level 2)

 Arrays Lab 5-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

In this exercise, you use arrays to implement the association between a

 bank and 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”

●   “Task 5 – Running the TestBanking Program”

Preparation

There is no preparation for this exercise.

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

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/05_arrays/exercise2 directory.

Page 98: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 98/276

Exercise2 – UsingArrays to Represent One-to-Many Associations (Level 2)

Lab 5-12 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Creating the BankClass

Complete the following steps:

1. Create the Bank class with the following characteristics:

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 keepstrack of the next customers array index).

3. Add a public constructor that initializes the customers array with

some appropriate maximum size (at least bigger than five).4. Add the addCustomer method. This method must construct a new

Customer object from the parameters (first name and last name) andplace it on the customers array. It must also increment thenumberOfCustomers instance variable.

5. Add the getNumOfCustomers accessor method, which returns thenumberOfCustomers instance variable.

6. Add the getCustomer method. This method returns the customerassociated with the given index parameter.

Task 2 – Deleting the Current TestBankingClass

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

Task 3 – Copying the TestBankingClass

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

resources/05_arrays directory to the com.mybank.test sourcepackage of the BankPrj project.

Task 4 – Compiling the TestBankingClass

In this task, you compile the TestBanking class.

Page 99: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 99/276

Exercise 2 – UsingArrays to Represent One-to-Many Associations (Level 2)

 Arrays Lab 5-13Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 5 – Running the TestBankingProgram

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

Customer [1] is Simms, JaneCustomer [2] is Bryant, OwenCustomer [3] is Soley, TimCustomer [4] is Soley, Maria

Page 100: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 100/276

Exercise2 – UsingArrays to Represent One-to-Many Associations (Level 3)

Lab 5-14 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

In this exercise, you use arrays to implement the association between a

 bank and 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”

●   “Task 5 – Running the TestBanking Program”

Preparation

There is no preparation for this exercise.

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

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/05_arrays/exercise2 directory.

Page 101: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 101/276

Exercise 2 – UsingArrays to Represent One-to-Many Associations (Level 3)

 Arrays Lab 5-15Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Creating the BankClass

Complete the following steps:

1. Create the Bank class with the following characteristics:

Class Name: Bank

Project: BankPrj

Location: Source Packages

Package: com.mybank.domain

package com.mybank.domain;public class Bank {// insert code here

}

2. Add two instance variables to the Bank class: customers (an array of Customer objects) and numberOfCustomers (an integer that keepstrack of the next customers array index).

public class Bank {private Customer[] customers;

  private int numberOfCustomers;// insert methods here

}

3. Add a public constructor that initializes the customers array withsome appropriate maximum size (at least bigger than five).

public Bank() {  customers = new Customer[10];  numberOfCustomers = 0;  }

4. Add the addCustomer method. This method must construct a newCustomer object from the parameters (first name, last name) andplace it on the customers array. It must also increment thenumberOfCustomers 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 thenumberOfCustomers instance variable.

public int getNumOfCustomers() {  return numberOfCustomers;  }

Page 102: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 102/276

Exercise2 – UsingArrays to Represent One-to-Many Associations (Level 3)

Lab 5-16 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

6. Add the getCustomer method. This method returns the customerassociated with the given index parameter.

public Customer getCustomer(int customer_index) {  return customers[customer_index];  }

Task 2 – Deleting the Current TestBankingClass

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

Task 3 – Copying the TestBankingClass

In this task, you copy the TestBanking.java file from theresources/05_arrays directory to the com.mybank.test sourcepackage of the BankPrj project.

Task 4 – Compiling the TestBankingClass

In this task, you compile the TestBanking class.

Task 5 – Running the TestBankingProgram

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

Customer [1] is Simms, JaneCustomer [2] is Bryant, OwenCustomer [3] is Soley, TimCustomer [4] is Soley, Maria

Page 103: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 103/276

Exercise Summary

 Arrays Lab 5-17Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 104: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 104/276

Page 105: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 105/276

Lab 6-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 6

ClassDesign

Objectives

Upon completion of this lab, you should be able to:

●   Create subclasses with inheritance and overriding of methods

●   Create a heterogeneous collection and use polymorphism

Page 106: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 106/276

Exercise1: Creating Bank Account Subclasses (Level 1)

Lab 6-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Creating Bank Account Subclasses (Level 1)

In this exercise, you create two subclasses of the Account class in theBanking project: SavingsAccount and CheckingAccount. These accounttypes have the following business rules:

●   A savings account gains interest. The bank permits customers tostore money in a savings account and, on a monthly basis, thesavings 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 willpermit a fixed amount of  overdraft protection. This protection enablesthe customer’s balance to drop below zero, but not below theamount of overdraft protection. The account’s overdraft amount is

decremented as it is used.

Figure 6-1 shows the UML class diagram for a design that satisfies the business rules described above.

Figure 6-1   Two Subclasses of the Account Class

com.mybank.domain

Account

+getBalance():double

+withdraw(amt:double):boolean

+deposit(amt:double):boolean

«constructors»

«methods»

#Account(initBalance:double)

#balance : double

CheckingAccount

+withdraw(amt:double):boolean

«constructors»

«methods»

+CheckingAccount(initBalance:double,

-overdraftAmount : double

SavingsAccount

«constructors»

+SavingsAccount(initBalance:double,

-interestRate : double

interestRate:double) overdraft:double)

+CheckingAccount(initBalance:double)

Page 107: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 107/276

Exercise 1: Creating Bank Account Subclasses (Level 1)

Class Design Lab 6-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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”

●   “Task 6 – Compiling the TestBanking Class”

●   “Task 7 – Running the TestBanking Program”

Preparation

There is no preparation for this exercise.

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

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/06_class1/exercise1 directory.

Page 108: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 108/276

Exercise1: Creating Bank Account Subclasses (Level 1)

Lab 6-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Modifying the AccountClass

In this task, you modify the Account class in the com.mybank.domainsource package of the BankPrj project. This class must satisfy the UMLdiagram 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 SavingsAccountClass

In this task, you create the SavingsAccount class source file in thecom.mybank.domain source package of the BankPrj project with thefollowing characteristics:

Class Name: SavingsAccount

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 andthe business rules defined in the introduction to ‘‘Exercise 1: CreatingBank Account Subclasses (Level 1)’’ on page L6-2.

Task 3 – Creating the CheckingAccountClass

In this task, you create the CheckingAccount class source file in thecom.mybank.domain source package of the BankPrj project with thefollowing 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 andthe business rules defined in the introduction to ‘‘Exercise 1: CreatingBank Account Subclasses (Level 1)’’ on page L6-2.

Page 109: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 109/276

Exercise 1: Creating Bank Account Subclasses (Level 1)

Class Design Lab 6-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 4 – Deleting the Current TestBankingClass

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

Task 5 – Copying the TestBankingClass

In this task, you copy the TestBanking.java file from theresources/06_class1 directory into the com.mybank.test sourcepackage of the BankPrj project. The new TestBanking class setsCheckingAccount and SavingsAccount objects to differentcustomers.

Task 6 – Compiling the TestBankingClass

In this task, you compile the TestBanking class.

Task 7 – Running the TestBankingProgram

In this task, you run the TestBanking program. The output should besimilar 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 overdraftprotection.Creating the customer Tim Soley.Creating his Checking Account with a 500.00 balance and 500.00 inoverdraft 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: trueDeposit 22.50: trueWithdraw 47.62: trueWithdraw 400.00: falseCustomer [Simms, Jane] has a balance of 324.88

Page 110: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 110/276

Exercise1: Creating Bank Account Subclasses (Level 1)

Lab 6-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Retrieving the customer Owen Bryant with his checking account with nooverdraft protection.Withdraw 150.00: trueDeposit 22.50: trueWithdraw 47.62: true

Withdraw 400.00: falseCustomer [Bryant, Owen] has a balance of 324.88

Retrieving the customer Tim Soley with his checking account that hasoverdraft protection.Withdraw 150.00: trueDeposit 22.50: trueWithdraw 47.62: trueWithdraw 400.00: trueCustomer [Soley, Tim] has a balance of 0.0

Retrieving the customer Maria Soley with her joint checking account withhusband Tim.Deposit 150.00: trueWithdraw 750.00: falseCustomer [Soley, Maria] has a balance of 150.0

 Jane’s savings account and Owen’s checking account behavefundamentally as a basic bank account. But Tim and Maria’s jointchecking account has 500.00 worth of overdraft protection. Tim’stransactions dip into that protection and therefore his ending balanceis 0.00. His account’s overdraft protection level is 424.88. Finally, Maria

deposits 150.00 into this joint account; raising the balance from 0.00to 150.00. Then she tries to withdraw 750.00, which fails because neitherthe balance nor the overdraft protection can cover that requested amount.

Page 111: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 111/276

Exercise 1: Creating Bank Account Subclasses (Level 2)

Class Design Lab 6-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Creating Bank Account Subclasses (Level 2)

In this exercise, you create two subclasses of the Account class in theBanking project: SavingsAccount and CheckingAccount.

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”

●   “Task 6 – Compiling the TestBanking Class”

●   “Task 7 – Running the TestBanking Program”

Preparation

There is no preparation for this exercise.

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

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/06_class1/exercise1 directory.

Page 112: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 112/276

Exercise1: Creating Bank Account Subclasses (Level 2)

Lab 6-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Modifying the AccountClass

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

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 SavingsAccountClass

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

Complete the following steps:

1. Create the SavingsAccount class source file in thecom.mybank.domain source package of the BankPrj project withthe following characteristics:

Class Name: SavingsAccount

Project: BankPrj

Extends: Account

Location: Source PackagesPackage: com.mybank.domain

2. Add the interestRate instance variable to the SavingsAccountclass.

3. Add a public constructor that takes two arguments: initBalanceand interestRate. Pass the initBalance parameter to the superconstructor. Save the interestRate parameter to the instancevariable.

Page 113: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 113/276

Exercise 1: Creating Bank Account Subclasses (Level 2)

Class Design Lab 6-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 3 – Creating the CheckingAccountClass

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

Complete the following steps:

1. Create the CheckingAccount class source file in thecom.mybank.domain source package of the BankPrj project withthe following characteristics:

Class Name: CheckingAccount

Project: BankPrj

Extends: Account

Location: Source Packages

Package: com.mybank.domain

2. Add the overdraftAmount instance variable to theCheckingAccount class.

3. Add a public constructor that takes two arguments: initBalanceand overdraftAmount. Pass the initBalance parameter to thesuper constructor. Save the overdraftAmount parameter to theinstance variable.

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

5. Override the withdraw method to use the overdraftAmountvariable. Here is the pseudo-code for the withdraw method:

if balance < amountthenoverdraftNeeded = amount - balanceif overdraftAmount < overdraftNeededthen transaction failselse

balance = 0decrement overdraftAmount by overdraftNeeded

elsedecrement balance by amount

Page 114: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 114/276

Exercise1: Creating Bank Account Subclasses (Level 2)

Lab 6-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 4 – Deleting the Current TestBankingClass

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

Task 5 – Copying the TestBankingClass

In this task, you copy the TestBanking.java file from theresources/06_class1 directory into the com.mybank.test sourcepackage of the BankPrj project. The new TestBanking class setsCheckingAccount and SavingsAccount objects to differentcustomers.

Task 6 – Compiling the TestBankingClass

In this task, you compile the TestBanking class.

Task 7 – Running the TestBankingProgram

In this task, you run the TestBanking program. The output should besimilar 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 overdraftprotection.Creating the customer Tim Soley.Creating his Checking Account with a 500.00 balance and 500.00 inoverdraft 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: trueDeposit 22.50: trueWithdraw 47.62: trueWithdraw 400.00: falseCustomer [Simms, Jane] has a balance of 324.88

Page 115: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 115/276

Exercise 1: Creating Bank Account Subclasses (Level 2)

Class Design Lab 6-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Retrieving the customer Owen Bryant with his checking account with nooverdraft protection.Withdraw 150.00: trueDeposit 22.50: trueWithdraw 47.62: true

Withdraw 400.00: falseCustomer [Bryant, Owen] has a balance of 324.88

Retrieving the customer Tim Soley with his checking account that hasoverdraft protection.Withdraw 150.00: trueDeposit 22.50: trueWithdraw 47.62: trueWithdraw 400.00: trueCustomer [Soley, Tim] has a balance of 0.0

Retrieving the customer Maria Soley with her joint checking account withhusband Tim.Deposit 150.00: trueWithdraw 750.00: falseCustomer [Soley, Maria] has a balance of 150.0

Page 116: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 116/276

Exercise1: Creating Bank Account Subclasses (Level 3)

Lab 6-12 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Creating Bank Account Subclasses (Level 3)

In this exercise, you will create two subclasses of the Account class in theBanking project: SavingsAccount and CheckingAccount.

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”

●   “Task 6 – Compiling the TestBanking Class”

●   “Task 7 – Running the TestBanking Program”

Preparation

There is no preparation for this exercise.

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

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/06_class1/exercise1 directory.

Page 117: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 117/276

Exercise 1: Creating Bank Account Subclasses (Level 3)

Class Design Lab 6-13Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Modifying the AccountClass

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

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

Task 2 – Creating the SavingsAccountClass

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

Complete the following steps:

1. Create the SavingsAccount class source file in thecom.mybank.domain source package of the BankPrj project withthe following characteristics:

Class Name: SavingsAccountProject: BankPrj

Extends: Account

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

private double interestRate;

Page 118: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 118/276

Exercise1: Creating Bank Account Subclasses (Level 3)

Lab 6-14 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

3. Add a public constructor that takes two arguments: initBalanceand interestRate. Pass the initBalance parameter to the superconstructor. Save the interestRate parameter to the instancevariable.

public SavingsAccount(double initBalance, double interestRate) {

  super(initBalance);  this.interestRate = interestRate;  }

Task 3 – Creating the CheckingAccountClass

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

Complete the following steps:1. Create the CheckingAccount class source file in the

com.mybank.domain source package of the BankPrj project withthe following characteristics:

Class Name: CheckingAccount

Project: BankPrj

Extends: Account

Location: Source Packages

Package: com.mybank.domainpackage com.mybank.domain;public class CheckingAccount extends Account {// insert code here

}

2. Add the overdraftAmount instance variable to theCheckingAccount class.

private double overdraftAmount;

3. Add a public constructor that takes two arguments: initBalanceand overdraftAmount. Pass the initBalance parameter to the

super constructor. Save the overdraftAmount parameter to theinstance variable.

public CheckingAccount(double initBalance, double overdraftAmount) {  super(initBalance);  this.overdraftAmount = overdraftAmount;  }

Page 119: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 119/276

Exercise 1: Creating Bank Account Subclasses (Level 3)

Class Design Lab 6-15Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

4. Add a second public constructor that takes only one argument:initBalance. Call the first constructor with the initBalanceparameter and use the default value 0.0 for the overdraftAmountparameter.

public CheckingAccount(double initBalance) {

  this(initBalance, 0.0);}

5. Override the withdraw method to use the overdraftAmountvariable.

public boolean withdraw(double amount) {  boolean result = true;  if ( balance < amount ) {  double overdraftNeeded = amount - balance;  if ( overdraftAmount < overdraftNeeded ) {  result = false;

  } else {  balance = 0.0;  overdraftAmount -= overdraftNeeded;  }  } else {

balance -= amount;  }  return result;  }

Task 4 – Deleting the Current TestBankingClass

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

Task 5 – Copying the TestBankingClass

In this task, you copy the TestBanking.java file from theresources/06_class1 directory into the com.mybank.test source

package of the BankPrj project. The new TestBanking class setsCheckingAccount and SavingsAccount objects to differentcustomers.

Page 120: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 120/276

Exercise1: Creating Bank Account Subclasses (Level 3)

Lab 6-16 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 6 – Compiling the TestBankingClass

In this task, you compile the TestBanking class.

Task 7 – Running the TestBankingProgram

In this task, you run the TestBanking program. The output should besimilar 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 overdraftprotection.Creating the customer Tim Soley.

Creating his Checking Account with a 500.00 balance and 500.00 inoverdraft 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: trueDeposit 22.50: trueWithdraw 47.62: trueWithdraw 400.00: falseCustomer [Simms, Jane] has a balance of 324.88

Retrieving the customer Owen Bryant with his checking account with nooverdraft protection.Withdraw 150.00: trueDeposit 22.50: trueWithdraw 47.62: trueWithdraw 400.00: falseCustomer [Bryant, Owen] has a balance of 324.88

Retrieving the customer Tim Soley with his checking account that hasoverdraft protection.Withdraw 150.00: trueDeposit 22.50: trueWithdraw 47.62: trueWithdraw 400.00: trueCustomer [Soley, Tim] has a balance of 0.0

Page 121: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 121/276

Exercise 1: Creating Bank Account Subclasses (Level 3)

Class Design Lab 6-17Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Retrieving the customer Maria Soley with her joint checking account withhusband Tim.Deposit 150.00: trueWithdraw 750.00: false

Customer [Soley, Maria] has a balance of 150.0

Page 122: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 122/276

Exercise2: Creating a Heterogeneous Collection of Customer Accounts (Level 1)

Lab 6-18 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Creating a Heterogeneous Collection of Customer Accounts (Level 1)

In this exercise, you create a heterogeneous array to represent the

aggregation of customers to accounts. That is, a given customer can haveseveral 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 Customerobject may now have more than one account and these accounts may beof different types, subclasses of the Account class.

Figure 6-2   Customer With One or More Different Accounts

Your job is to modify the Customer class to support a heterogeneouscollection of  Account objects.

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”

●   “Task 5 – Running the TestReport Program”

com.mybank.domain

0..*serves Customer Account0..*has-aBank

CheckingAccountSavingsAccount

Page 123: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 123/276

Exercise 2: Creating a HeterogeneousCollection of Customer Accounts (Level 1)

Class Design Lab 6-19Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

There is no preparation required for this exercise.

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

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

directory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/06_class1/exercise2 directory.

Task 1 – Modifying the CustomerClass

In this task, you modify the Customer class in the com.mybank.domainsource package of the BankPrj project. Modify the Customer class tohandle the association with multiple accounts, just as you did in theExercise 2 of Lab 5. It must include the public methods:addAccount(Account), getAccount(int), and getNumOfAccounts().

Task 2 – Copying and Completing the CustomerReportClass

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

project.

2. Copy the CustomerReport.java file from theresources/06_class1 directory into the com.mybank.reportsource package of the BankPrj project.

Page 124: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 124/276

Exercise2: Creating a Heterogeneous Collection of Customer Accounts (Level 1)

Lab 6-20 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

3. Complete the CustomerReport.java code. You will find comment blocks that start and end with /*** ... ***/. These commentsindicate the location in the code that you must supply.

Task 3 – Copying the TestReportClass

In this task, you copy the TestReport.java file from theresources/06_class1 directory into the com.mybank.test sourcepackage of the BankPrj project.

Task 4 – Compiling the TestReportClass

In this task, you compile the TestReport class.

Task 5 – Running the TestReportProgram

In this task, you run the TestReport program. The output should besimilar to the following:

CUSTOMERS REPORT  ================

Customer: Simms, Jane

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

Customer: Bryant, Owen  Checking Account: current balance is 200.0

Customer: Soley, Tim  Savings Account: current balance is 1500.0  Checking Account: current balance is 200.0

Customer: Soley, Maria

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

Page 125: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 125/276

Exercise 2: Creating a HeterogeneousCollection of Customer Accounts (Level 2)

Class Design Lab 6-21Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Creating a Heterogeneous Collection of Customer Accounts (Level 2)

In this exercise, you create a heterogeneous array to represent the

aggregation of customers to accounts. That is, a given customer can haveseveral 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”

●   “Task 5 – Running the TestReport Program”

Preparation

There is no preparation required for this exercise.

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

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

123

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

demos/06_class1/exercise2 directory.

Page 126: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 126/276

Exercise2: Creating a Heterogeneous Collection of Customer Accounts (Level 2)

Lab 6-22 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Modifying the CustomerClass

In this task, you modify the Customer class in the com.mybank.domainsource package of the BankPrj project. Modify the Customer class tohandle 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 (anarray of  Account objects) and numberOfAccounts (an integer thatkeeps track of the next accounts array index). This replaces thesingle account reference variable, which should be removed.

2. Modify the constructor to initialize the accounts array.

3. Add the addAccountmethod. This method takes a single parameter,an Account object, and stores it in the accounts array. It must alsoincrement the numberOfAccounts instance variable. This methodreplaces the setAccount method, which should be removed.

4. Add the getNumOfAccounts accessor method, which returns thenumberOfAccounts instance variable.

5. Add the getAccount method. This method returns the accountassociated with the given indexparameter. This method replaces theprevious getAccount method, which should be removed.

Task 2 – Copying and Completing the CustomerReportClass

Complete the following steps:

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

2. Copy the CustomerReport.java file from theresources/06_class1 directory into the com.mybank.report

source package of the BankPrj project.

Page 127: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 127/276

Exercise 2: Creating a HeterogeneousCollection of Customer Accounts (Level 2)

Class Design Lab 6-23Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

3. Complete the CustomerReport.java code. You will find comment blocks that start and end with /*** ... ***/. These commentsindicate the location in the code that you must supply.

a. Use the instanceof operator to test what type of account thisis 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 TestReportClass

In this task, you copy the TestReport.java file from theresources/06_class1 directory into the com.mybank.test sourcepackage of the BankPrj project.

Task 4 – Compiling the TestReportClass

In this task, you compile the TestReport class.

Task 5 – Running the TestReportProgram

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

Page 128: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 128/276

Exercise2: Creating a Heterogeneous Collection of Customer Accounts (Level 3)

Lab 6-24 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Creating a Heterogeneous Collection of Customer Accounts (Level 3)

In this exercise, you create a heterogeneous array to represent the

aggregation of customers to accounts. That is, a given customer can haveseveral 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”

●   “Task 5 – Running the TestReport Program”

Preparation

There is no preparation required for this exercise.

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

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

123

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

demos/06_class1/exercise2 directory.

Page 129: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 129/276

Exercise 2: Creating a HeterogeneousCollection of Customer Accounts (Level 3)

Class Design Lab 6-25Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Modifying the CustomerClass

In this task, you modify the Customer class in the com.mybank.domainsource package of the BankPrj project. Modify the Customer class tohandle 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 (anarray of  Account objects) and numberOfAccounts (an integer thatkeeps track of the next accounts array index). This replaces thesingle account reference variable, which should be removed.

private Account[] accounts;  private int numberOfAccounts;

2. Modify the constructor to initialize the accounts array.

public Customer(String f, String l) {  firstName = f;  lastName = l;  // initialize accounts array  accounts = new Account[10];  numberOfAccounts = 0;  }

3. Add the addAccountmethod. This method takes a single parameter,

an Account object, and stores it in the accounts array. It must alsoincrement the numberOfAccounts instance variable. This methodreplaces the setAccount method, which should be removed.

public void addAccount(Account acct) {  int i = numberOfAccounts++;  accounts[i] = acct;  }

4. Add the getNumOfAccounts accessor method, which returns thenumberOfAccounts instance variable.

public int getNumOfAccounts() {

  return numberOfAccounts;  }

5. Add the getAccount method. This method returns the accountassociated with the given indexparameter. This method replaces theprevious getAccount method, which should be removed.

public Account getAccount(int account_index) {  return accounts[account_index];  }

Page 130: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 130/276

Exercise2: Creating a Heterogeneous Collection of Customer Accounts (Level 3)

Lab 6-26 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 2 – Copying and Completing the CustomerReportClass

Complete the following steps:

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

2. Copy the CustomerReport.java file from theresources/06_class1 directory into the com.mybank.reportsource package of the BankPrj project.

3. Complete the CustomerReport.java code. You will find comment blocks that start and end with /*** ... ***/. These commentsindicate the location of the code that you must supply.

a. Use the instanceof operator to test what type of account this

is and set account_type to an appropriate value, such asSavings Account or Checking Account.

if ( account instanceof SavingsAccount ) {  account_type = "Savings Account";  } else if ( account instanceof CheckingAccount ) {  account_type = "Checking Account";  } else {  account_type = "Unknown Account Type";  }

 b. Print out the type of account and the balance.

System.out.println(" " + account_type + ": current balance is "  + account.getBalance());

Task 3 – Copying the TestReportClass

In this task, you copy the TestReport.java file from theresources/06_class1 directory into the com.mybank.test sourcepackage of the BankPrj project.

Task 4 – Compiling the TestReportClass

In this task, you compile the TestReport class.

Page 131: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 131/276

Exercise 2: Creating a HeterogeneousCollection of Customer Accounts (Level 3)

Class Design Lab 6-27Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 5 – Running the TestReportProgram

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

Page 132: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 132/276

Exercise3: Creating a BatchProgram (Advanced)

Lab 6-28 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 3: Creating a Batch Program (Advanced)

In this exercise, you create a batch program to accumulate interest foreach savings account on a monthly basis.

Note – This is an advanced exercise. This exercise is optional and shouldonly be attempted if you completed all of the previous exercises for thismodule.

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

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”

SavingsAccount

«constructors»

+SavingsAccount(initBalance:double,

-interestRate : double

interestRate:double)

+accumulateInterest():void

«methods»

CustomerReport

+generateReport():void

«methods»

TestBatch

+setBank(bank:Bank):void

-bank : Bank

AccumulateSavingsBatch

+doBatch():void

«methods»

+setBank(bank:Bank):void

-bank : Bank

Page 133: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 133/276

Exercise3: Creating a BatchProgram (Advanced)

Class Design Lab 6-29Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

There is no preparation required for this exercise.

Tool Reference – Tool references used in this exercise:●   Java Development: Java Classes: Creating Java Classes

●   Java Development: Java Classes: 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.

Task 1 – Modifying the SavingsAccountClass

A savings account gains interest. The bank permits customers to storemoney in a savings account and, on a monthly basis, the savings accountwill accumulate based on the following formula: balance = balance +(balance * (interestRate / 12)).

In this task, you add theaccumulateInterest

 method to perform thisoperation.

Task 2 – Creating the AccumulateSavingsBatchClass

Complete the following steps:

1. Create the AccumulateSavingsBatch class with the followingcharacteristics:

Class Name: AccumulateSavingsBatch

Project: BankPrj

Location: Source Packages

Package: com.mybank.batch

The class must conform to the specification defined in Figure 6-3 onpage L6-28.

2. Add an instance variable bank of the type Bank.

Page 134: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 134/276

Exercise3: Creating a BatchProgram (Advanced)

Lab 6-30 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

3. Add a setBank method to set the method parameter to the bankinstance variable.

4. Add a doBatch method using the following hints:

for each Customer in the Bank dofor each Account in the Customer doif the Account is a SavingsAccount,then call the accumulateInterest method

Task 3 – Copying the TestBatchClass

In this task, you copy the TestBatch.java file from theresources/06_class1 directory into the com.mybank.test sourcepackage of the BankPrj project.

Task 4 – Compiling the TestBatchClass

In this task, you compile the TestBatch class.

Task 5 – Running the TestBatchProgram

In this task, you run the TestBatch program. The output should besimilar to the following:

CUSTOMERS REPORT  ================

Customer: Simms, Jane  Savings Account: current balance is 500.0  Checking Account: current balance is 200.0

Customer: Bryant, Owen  Checking Account: current balance is 200.0

Customer: Soley, Tim  Savings Account: current balance is 1500.0  Checking Account: current balance is 200.0

Customer: Soley, Maria  Checking Account: current balance is 200.0  Savings Account: current balance is 150.0

Page 135: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 135/276

Exercise3: Creating a BatchProgram (Advanced)

Class Design Lab 6-31Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

 ACCUMULATE SAVINGS BATCH EXECUTED

  CUSTOMERS REPORT  ================

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

Customer: Soley, Maria  Checking Account: current balance is 200.0  Savings Account: current balance is 150.625

Page 136: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 136/276

Exercise Summary

Lab 6-32 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 137: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 137/276

Lab 7-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 7

 AdvancedClassFeatures

Objectives

Upon completion of this lab, you should be able to:

●   Apply static class members to resolve a design decision.

●   Create abstract classes and interfaces, and explore the polymorphicproperties of these types of components

Page 138: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 138/276

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

Lab 7-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

In this exercise, you apply static class members to resolve a designdecision. The Banking Project currently uses a concrete class to representthe 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 tocontain different sets of customers.

The design team has decided to make the Bank class a utility class. Autility 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 programthese changes to the Bank class and to all of the classes that use the Bankclass.

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”

com.mybank.domain

-customers : Customer[]

+addCustomer(f:String, l:String)

+getCustomer(index:int):Customer

-numberOfCustomers : int

+getNumOfCustomers():int

-Bank()

0..*

Bank

«constructors»

«methods»

serves

Customer Account1has-a

Page 139: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 139/276

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

 Advanced Class Features Lab 7-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/07_class2/exercise1 directory.

Task 1 – Modifying the BankClass

In this task, you open the BankPrj project in the projects directory,and modify the Bank class in the com.mybank.domain source package of the BankPrj project. All the members (both instance variables andmethods) should be changed to static, as shown in Figure 7-1 onpage L7-2. Also, move the original variable initialization code from theconstructor to either a static block or on the static variable declarations.

Task 2 – Modifying the CustomerReportClass

In this task, you modify the CustomerReport class source file in thecom.mybank.report source package of the BankPrj project. The updatedCustomerReport class uses the Bank class as a utility class.

Page 140: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 140/276

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

Lab 7-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 3 – Deleting the Current TestReportClass

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

Task 4 – Copying the TestReportClass

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

Task 5 – Compiling the TestReportClass

In this task, you compile the TestReport class.

Task 6 – Running the TestReportProgram

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

Page 141: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 141/276

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

 Advanced Class Features Lab 7-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

In this exercise, you apply static class members to resolve a designdecision. The Banking Project currently uses a concrete class to representthe 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 tocontain different sets of customers.

The design team has decided to make the Bank class a utility class. Autility 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 jobis to program these changes to the Bank class and to all of the classes thatuse the Bank 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”

Preparation

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

Page 142: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 142/276

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

Lab 7-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

123

Demonstration – The demonstration for this exercise can be found in thedemos/07_class2/exercise1 directory.

Task 1 – Modifying the BankClass

In this task, you modify the Bank class in the com.mybank.domain sourcepackage of the BankPrj project. All the members (both instance variablesand methods) should be changed to static, as shown in Figure 7-1 onpage L7-2.

Complete the following steps:

1. Open theBankPrj

 project in theprojects

 directory if you haveclosed it.

2. Open the Bank class in the com.mybank.domain source package of the BankPrj project.

3. Change all instance variables to static.

4. Move the original variable initialization code from the constructor toeither a static block or on the static variable declarations.

5. Change the constructor to be private and remove the body of theconstructor.

6. Change all methods to static.

Task 2 – Modifying the CustomerReportClass

In this task, you modify the CustomerReport class source file in thecom.mybank.report source package of the BankPrj project. The updatedCustomerReport class uses the Bank class as a utility class.

Complete the following steps:

1. Remove the bank instance variable and the getBank and setBankmethods.

2. Modify the generateReportmethod to use the static methods fromthe new Bank utility class design.

Page 143: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 143/276

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

 Advanced Class Features Lab 7-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 3 – Deleting the Current TestReportClass

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

Task 4 – Copying the TestReportClass

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

Task 5 – Compiling the TestReportClass

In this task, you compile the TestReport class.

Task 6 – Running the TestReportProgram

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

Page 144: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 144/276

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

Lab 7-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

In this exercise, you apply static class members to resolve a designdecision. The Banking Project currently uses a concrete class to representthe 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 tocontain different sets of customers.

The design team has decided to make the Bank class a utility class. Autility 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 jobis to program these changes to the Bank class and to all of the classes thatuse the Bank 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”

Preparation

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

Page 145: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 145/276

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

 Advanced Class Features Lab 7-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

123

Demonstration – The demonstration for this exercise can be found in thedemos/07_class2/exercise1 directory.

Task 1 – Modifying the BankClass

In this task, you modify the Bank class in the com.mybank.domain sourcepackage of the BankPrj project. All the members (both instance variablesand methods) should be changed to static, as shown in Figure 7-1 onpage L7-2.

Complete the following steps:

1. Open theBankPrj

 project in theprojects

 directory if you haveclosed it.

2. Open the Bank class in the com.mybank.domain source package of the BankPrj project.

3. Change all instance variables to static.

private static Customer[] customers;  private static int numberOfCustomers;

4. Move the original variable initialization code from the constructor toeither a static block or on the static variable declarations.

static {  customers = new Customer[10];  numberOfCustomers = 0;  }

5. Change the constructor to be private and remove the body of theconstructor.

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];  }

Page 146: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 146/276

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

Lab 7-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 2 – Modifying the CustomerReportClass

In this task, you modify the CustomerReport class source file in thecom.mybank.report source package of the BankPrj project. The updatedCustomerReport class uses the Bank class as a utility class.

Complete the following steps:

1. Remove the bank instance variable and the getBank and setBankmethods.

2. Modify the generateReportmethod to use the static methods fromthe new Bank utility class design.

public void generateReport() {

  // Print report header

  System.out.println("CUSTOMERS REPORT");  System.out.println("================");

  // For each customer...  for ( int cust_idx = 0;  cust_idx < Bank.getNumOfCustomers();  cust_idx++ ) {  Customer customer = Bank.getCustomer(cust_idx);

// and so on...}

}

Task 3 – Deleting the Current TestReportClass

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

Task 4 – Copying the TestReportClass

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

Page 147: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 147/276

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

 Advanced Class Features Lab 7-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 5 – Compiling the TestReportClass

In this task, you compile the TestReport class.

Task 6 – Running the TestReportProgram

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

Page 148: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 148/276

Exercise2: Working With InterfacesandAbstract Classes (Level 1)

Lab 7-12 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Working With Interfaces and Abstract Classes(Level 1)

In this exercise, you create abstract classes and interfaces, and explore the

polymorphic properties of these types of components. You create ahierarchy of animals that is rooted in an abstract class Animal. Several of the animal classes implement an interface called Pet. Figure 7-2 shows aUML class diagram of the animal classes that you create.

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”

Animal

+walk():void

+eat():void 

«constructors»

«methods»

#Animal(legs:int)

#legs : int

Fish

+getName():String

«constructors»

«methods»

+Fish()

-name : String

Cat

«constructors»

+Cat(n:String)

-name : String

Pet

+getName():String

+setName(n:String):void

+play()

«interface»

+setName(n:String):void

+play():void

{abstract}

+Cat()

+walk():void

+eat():void

+getName():String

«methods»

+setName(n:String):void

+play():void

+eat():void

Spider

«constructors»

+Spider()

«methods»+eat():void

Page 149: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 149/276

Exercise2: Working With InterfacesandAbstract Classes (Level 1)

 Advanced Class Features Lab 7-13Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

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

exercises/07_class2/exercise2 directory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/07_class2/exercise2 directory.

Task 1 – Creating the Pet Interface

Complete the following steps:1. Open the InterfaceProject project in the

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

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

Page 150: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 150/276

Exercise2: Working With InterfacesandAbstract Classes (Level 1)

Lab 7-14 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 2 – Creating the Animal Classes

Complete the following steps:

1. Create the Animal class with the following characteristics:

Class Name: Animal

Project: InterfaceProject

Location: Source Packages

Package: default package

The Animal class must satisfy the UML diagram in Figure 7-1 onpage L7-2. The action methods (walk and eat) print a statement tostandard output that reflects the animal. For example, the walk methodfor the Animal class might say something similar to This animal walks

on 4 legs, where 4 is the value of the legs instance variable.2. Create the Spider, Cat, and Fish classes in the Source Packages of 

the InterfaceProject project to satisfy the UML diagram inFigure 7-1 on page L7-2.

Task 3 – Creating the TestAnimalsClass

Complete the following steps:

1. In this task, you create the TestAnimals class with the followingcharacteristics:

Class Name: TestAnimals

Project: InterfaceProject

Location: Source Packages

Package: default package

2. Add the main method to create and manipulate instances of theclasses 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();

Page 151: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 151/276

Exercise2: Working With InterfacesandAbstract Classes (Level 1)

 Advanced Class Features Lab 7-15Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Experiment by:

●   Calling the methods in each object

●   Casting objects

●   Using polymorphism

●   Using super to call superclass methods

Task 4 – Compiling the TestAnimalsClass

In this task, you compile the TestAnimals class.

Task 5 – Running the TestAnimalsProgram

In this task, you run the TestAnimals program.

Page 152: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 152/276

Exercise2: Working With InterfacesandAbstract Classes (Level 2)

Lab 7-16 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Working With Interfaces and Abstract Classes(Level 2)

In this exercise, you create abstract classes and interfaces, and explore the

polymorphic properties of these types of components. You create ahierarchy of animals that is rooted in an abstract class Animal. Several of the animal classes will implement an interface called Pet. Use Figure 7-2on page L7-12 as a reference. You experiment with variations of theseanimals, 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”

●   “Task 4 – Compiling the TestAnimals Class”

●   “Task 5 – Running the TestAnimals Program”

Preparation

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

exercises/07_class2/exercise2 directory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/07_class2/exercise2 directory.

Page 153: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 153/276

Exercise2: Working With InterfacesandAbstract Classes (Level 2)

 Advanced Class Features Lab 7-17Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Creating the Pet Interface

Complete the following steps:

1. Open the InterfaceProject project in the

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

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

Task 2 – Creating the Animal Classes

Complete the following steps:

1. Create the abstract Animal class.

a. Create the Animal class with the following characteristics:

Class Name: Animal

Project: InterfaceProjectLocation: Source Packages

Package: default package

 b. Declare a protected integer instance variable called legs, whichrecords the number of legs for this animal.

c. Define a protected constructor that initializes the legs instancevariable.

d. Declare an abstract method eat.

e. Declare a concrete method walk that prints out somethingabout how the animals walks (include the number of legs).

Page 154: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 154/276

Exercise2: Working With InterfacesandAbstract Classes (Level 2)

Lab 7-18 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

2. Create the Spider class.

a. Create the Spider class with the following characteristics:

Class Name: Spider

Project: InterfaceProject

Extends: Animal

Location: Source Packages

Package: default package

 b. Define a no-arg constructor that calls the superclassconstructor to specify that all spiders have eight legs.

c. Implement the eat method.

3. Create the Cat class.

a. Create the Cat class with the following characteristics:

Class Name: Cat

Project: InterfaceProject

Extends: Animal

Implements: Pet

Location: Source Packages

Package: default package

 b. This class must include a String instance variable to store the

name of the pet.c. Define a constructor that takes one String parameter that

specifies the cat’s name. This constructor must also call thesuperclass constructor to specify that all cats have four legs.

d. Define another constructor that takes no parameters. Have thisconstructor call the previous constructor (using the thiskeyword) 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

Page 155: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 155/276

Exercise2: Working With InterfacesandAbstract Classes (Level 2)

 Advanced Class Features Lab 7-19Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Implements: Pet

Location: Source Packages

Package: default package

 b. This class must include a String instance variable to store the

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 supermethod and they print a message that fish do not walk

f. Implement the eat method.

Task 3 – Creating the TestAnimalsClass

Complete the following steps:

1. In this task, you create the TestAnimals class with the followingcharacteristics:

Class Name: TestAnimals

Project: InterfaceProject

Location: Source Packages

Package: default package2. .Add the main method to create and manipulate instances of the

classes you created previously.

Start with:

Fish d = new Fish();Cat c = new Cat("Fluffy"); Animal a = new Fish(); Animal e = new Spider();Pet p = new Cat();

Experiment by:●   Calling the methods in each object

●   Casting objects

●   Using polymorphism

●   Using super to call superclass methods

Page 156: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 156/276

Exercise2: Working With InterfacesandAbstract Classes (Level 2)

Lab 7-20 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 4 – Compiling the TestAnimalsClass

In this task, you compile the TestAnimals class.

Task 5 – Running the TestAnimalsProgram

In this task, you run the TestAnimals program.

Page 157: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 157/276

Exercise2: Working With InterfacesandAbstract Classes (Level 3)

 Advanced Class Features Lab 7-21Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Working With Interfaces and Abstract Classes(Level 3)

In this exercise, you create a hierarchy of animals that is rooted in an

abstract class Animal. Several of the animal classes implement an interfacecalled Pet. Use Figure 7-2 on page L7-12 as a reference. You experimentwith 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”

●   “Task 4 – Compiling the TestAnimals Class”

●   “Task 5 – Running the TestAnimals Program”

Preparation

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: 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 InterfaceProject project in theexercises/07_class2/exercise2 directory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/07_class2/exercise2 directory.

Page 158: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 158/276

Exercise2: Working With InterfacesandAbstract Classes (Level 3)

Lab 7-22 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Creating the Pet Interface

Complete the following steps:

1. Open the InterfaceProject project in the

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

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

public interface Pet {public String getName();public void setName(String n);public void play();

}

Task 2 – Creating the Animal Classes

Complete the following steps:

1. Create the Animal class.

a. Create the Animal class with the following characteristics:

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, whichrecords the number of legs for this animal.

protected int legs;

c. Define a protected constructor that initializes the legs instancevariable.

Page 159: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 159/276

Exercise2: Working With InterfacesandAbstract Classes (Level 3)

 Advanced Class Features Lab 7-23Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

protected Animal(int legs) {this.legs = legs;

}

d. Declare an abstract method eat.

public abstract void eat();

e. Declare a concrete method walk that prints out somethingabout 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:

Class Name: Spider

Project: InterfaceProjectExtends: Animal

Location: Source Packages

Package: default package

 b. The Spider class extends the Animal class.

public class Spider extends Animal {// more code here

}

c. Define a no-arg constructor that calls the superclassconstructor to specify that all spiders have eight legs.

public Spider() {super(8);

}

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

Page 160: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 160/276

Exercise2: Working With InterfacesandAbstract Classes (Level 3)

Lab 7-24 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Location: Source Packages

Package: default package

 b. This class must include a String instance variable to store thename of the pet.

private String name;c. Define a constructor that takes one String parameter that

specifies the cat’s name. This constructor must also call thesuperclass 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 thisconstructor call the previous constructor (using the this

keyword) and pass an empty string as the argument.

public Cat() {this("");

}

e. Implement the Pet interface methods.

public String getName() {return name;

}public void setName(String n) {name = n;

}public void play() {System.out.println(name + " likes to play with string.");

}

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

Page 161: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 161/276

Exercise2: Working With InterfacesandAbstract Classes (Level 3)

 Advanced Class Features Lab 7-25Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Location: Source Packages

Package: default package

 b. This class must include a String instance variable to store thename of the pet.

private String name;c. Define a no-arg constructor that calls the superclass

constructor to specify that fish do not have legs.

public Fish() {  super(0); // this line must be here  }

d. Implement the Pet interface methods.

public void setName(String name) {  this.name = name;  }  public String getName() {  return name;  }  public void play() {  System.out.println("Fish swim in their tanks all day.");  }

e. Override the walk method. This method should call the supermethod and they print a message that fish do not walk

public void walk() {  super.walk();

  System.out.println("Fish, of course, can’t walk; they swim.");  }

f. Implement the eat method.

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

Task 3 – Creating the TestAnimalsClass

Complete the following steps:

1. In this task, you create the TestAnimals class with the followingcharacteristics:

Class Name: TestAnimals

Project: InterfaceProject

Page 162: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 162/276

Exercise2: Working With InterfacesandAbstract Classes (Level 3)

Lab 7-26 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Location: Source Packages

Package: default package

2. Add the main method to create and manipulate instances of theclasses you created previously.

Here is a sample test program:public class TestAnimals {  public static void main(String[] args) {  Fish f = new Fish();  Cat c = new Cat("Fluffy");  Animal a = new Fish();  Animal e = new Spider();  Pet p = new Cat();

  // Demonstrate different implementations of an interface  f.play();  c.play();

  // Demonstract virtual method invocation  e.eat();  e.walk();

  // Demonstrate calling super methods  a.walk();  }}

Task 4 – Compiling the TestAnimalsClass

In this task, you compile the TestAnimals class.

Task 5 – Running the TestAnimalsProgram

In this task, you run the TestAnimals program.

Page 163: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 163/276

Exercise Summary

 Advanced Class Features Lab 7-27Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 164: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 164/276

Page 165: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 165/276

Lab 8-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 8

ExceptionsandAssertions

Objectives

Upon completion of this lab, you should be able to create an applicationexception and apply the declare-or-handle rule to the account classes.

Page 166: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 166/276

Exercise: Creating Your Own Exception (Level 1)

Lab 8-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise: Creating Your Own Exception (Level 1)

In this exercise, you create an OverdraftException that is thrown by thewithdraw method in the Account class. In the previous design, thedeposit and withdrawmethods return a Boolean flag to indicate whetherthe 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 anyindication 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 UMLparlance, the «send» dependency indicates that the method on the sourceoperation (the withdraw method) may throw an OverdraftException.

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”

com.mybank.domain

Account

+getBalance():double

+withdraw(amt:double):void

+deposit(amt:double):void

«constructors»

«methods»

#Account(initBalance:double)

#balance : double

CheckingAccount

+withdraw(amt:double):boid

«constructors»

«methods»

+CheckingAccount(initBalance:double,

-overdraftAmount : double

overdraft:double)

+CheckingAccount(initBalance:double)

Exception

+getMessage():String

«constructors»

«methods»

+Exception(msg:String)

OverdraftException

+getDeficit():double

«constructors»

«methods»

+OverdraftException(msg:String,

-deficit : double

deficit:double)

«exception»

«exception»

{from java.lang}

«send»

«send»

Page 167: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 167/276

Exercise: Creating Your Own Exception (Level 1)

Exceptions and Assertions Lab 8-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

●   “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”

●   “Task 7 – Running the TestBanking Program”

Preparation

There is no preparation required for this exercise.

Tool Reference – Tool references used in this exercise:

●   Java Development: Java Classes: Creating Java Classes

●   Java Development: 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 projectsdirectory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/08_except/exercise1 directory.

Page 168: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 168/276

Exercise: Creating Your Own Exception (Level 1)

Lab 8-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Creating the OverdraftExceptionClass

In this task, you create the OverdraftException class in thecom.mybank.domain source package of the BankPrj project with thefollowing 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.

Task 2 – Modifying the AccountClass

In this task, you modify the Account class source file in thecom.mybank.domain source package of the BankPrj project. This classmust satisfy the UML diagram in Figure 8-1 on page L8-2. In particular,the deposit and withdraw methods should not return a boolean flag.

Task 3 – Modifying the CheckingAccountClass

In this task, you modify the CheckingAccount class source file in thecom.mybank.domain source package of the BankPrj project. This classmust satisfy the UML diagram in Figure 8-1 on page L8-2.

Task 4 – Deleting the Current TestBankingClass

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

Task 5 – Copying the TestBankingClass

In this task, you copy the TestBanking.java file from theresources/08_except directory to the com.mybank.test sourcepackage of the BankPrj project.

Page 169: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 169/276

Exercise: Creating Your Own Exception (Level 1)

Exceptions and Assertions Lab 8-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 6 – Compiling the TestBankingClass

In this task, you compile the TestBanking class.

Task 7 – Running the TestBankingProgram

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

Customer [Simms, Jane] has a checking balance of 200.0 with a 500.00overdraft protection.Checking Acct [Jane Simms] : withdraw 150.00Checking Acct [Jane Simms] : deposit 22.50Checking Acct [Jane Simms] : withdraw 147.62Checking Acct [Jane Simms] : withdraw 470.00

Exception: Insufficient funds for overdraft protection Deficit: 470.0Customer [Simms, Jane] has a checking balance of 0.0

Customer [Bryant, Owen] has a savings balance of 200.0Savings Acct [Owen Bryant] : withdraw 100.00Savings Acct [Owen Bryant] : deposit 25.00Savings Acct [Owen Bryant] : withdraw 175.00Exception: Insufficient funds Deficit: 50.0Customer [Bryant, Owen] has a savings balance of 125.0

Page 170: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 170/276

Exercise: Creating Your Own Exception (Level 2)

Lab 8-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise: Creating Your Own Exception (Level 2)

In this exercise, you create an OverdraftException that is thrown by thewithdraw method in the Account class.

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”

●   “Task 6 – Compiling the TestBanking Class”

●   “Task 7 – Running the TestBanking Program”

Preparation

There is no preparation required for this exercise.

Tool Reference – Tool references used in this exercise:

●   Java Development: Java Classes: Creating Java Classes

●   Java Development: 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 projectsdirectory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/08_except/exercise1 directory.

Page 171: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 171/276

Exercise: Creating Your Own Exception (Level 2)

Exceptions and Assertions Lab 8-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Creating the OverdraftExceptionClass

Complete the following steps:

1. Create the OverdraftException class in the

com.mybank.domain source package of the BankPrj project withthe following characteristics:

Class Name: OverdraftException

Project: BankPrj

Extends: Exception

Location: Source Packages

Package: com.mybank.domain

2. Add a private instance variable called deficit that holds a double.

3. Add a public constructor that takes two arguments: message anddeficit. The message parameter should be passed to the superclassconstructor. The deficit parameter initializes the deficit instancevariable.

4. Add a public accessor called getDeficit.

Task 2 – Modifying the AccountClass

In this task, you modify the Account class source file in the

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

Complete the following steps:

1. Modify the deposit method so that it does not return a value (thatis, void). This operation should never fail, so it does not need tothrow any exceptions.

2. Modify the withdrawmethod so that it does not return a value (thatis, 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 requestedsubtracted by the current balance).

Page 172: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 172/276

Exercise: Creating Your Own Exception (Level 2)

Lab 8-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 3 – Modifying the CheckingAccountClass

In this task, you modify the CheckingAccount class source file in thecom.mybank.domain source package of the BankPrj project. Modify thewithdrawmethod so that it does not return a value (that is, void). Declare

that this method throws the OverdraftException. Modify the code tothrow an exception when the overdraftProtection amount is notsufficient to cover the deficit; use the message Insufficient funds foroverdraft protection for this exception.

Task 4 – Deleting the Current TestBankingClass

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

Task 5 – Copying the TestBankingClass

In this task, you copy the TestBanking.java file from theresources/08_except directory to the com.mybank.test sourcepackage of the BankPrj project.

Task 6 – Compiling the TestBankingClass

In this task, you compile the TestBanking class.

Task 7 – Running the TestBankingProgram

In this task, you run the TestBanking program.

The output should be similar to the output listed on page L8-5.

Page 173: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 173/276

Exercise: Creating Your Own Exception (Level 3)

Exceptions and Assertions Lab 8-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise: Creating Your Own Exception (Level 3)

In this exercise, you create an OverdraftException that is thrown by thewithdraw method in the Account class.

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”

●   “Task 6 – Compiling the TestBanking Class”

●   “Task 7 – Running the TestBanking Program”

Preparation

There is no preparation required for this exercise.

Tool Reference – Tool references used in this exercise:

●   Java Development: Java Classes: Creating Java Classes

●   Java Development: 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 projectsdirectory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/08_except/exercise1 directory.

Page 174: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 174/276

Exercise: Creating Your Own Exception (Level 3)

Lab 8-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Creating the OverdraftExceptionClass

Complete the following steps:

1. Create the OverdraftException class in the

com.mybank.domain source package of the BankPrj project withthe following characteristics:

Class Name: OverdraftException

Project: BankPrj

Extends: Exception

Location: Source Packages

Package: com.mybank.domain

package com.mybank.domain;public class OverdraftException extends Exception {// insert code here

}

2. Add a private instance variable called deficit that holds a double.

private final double deficit;

3. Add a public constructor that takes two arguments: message anddeficit. The message parameter should be passed to the superclassconstructor. The deficit parameter initializes the deficit instancevariable.

public OverdraftException(String msg, double deficit) {

  super(msg);  this.deficit = deficit;  }

4. Add a public accessor called getDeficit.

public double getDeficit() {  return deficit;  }

Page 175: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 175/276

Exercise: Creating Your Own Exception (Level 3)

Exceptions and Assertions Lab 8-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 2 – Modifying the AccountClass

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

Complete the following steps:

1. Modify the deposit method so that it does not return a value (thatis, void). This operation should never fail, so it does not need tothrow any exceptions.

public void deposit(double amt) {  balance = balance + amt;  }

2. Modify the withdrawmethod so that it does not return a value (thatis, void). Declare that this method throws the OverdraftException.

Modify the code to throw a new exception that specifiesInsufficient funds and the deficit (the amount requestedsubtracted by the current balance).

public void withdraw(double amt) throws OverdraftException {  if ( amt <= balance ) {  balance = balance - amt;  } else {  throw new OverdraftException("Insufficient funds", amt - balance);  }  }

Task 3 – Modifying the CheckingAccountClass

Using a text editor, modify the CheckingAccount class source file in thesrc/com/mybank/domain/ directory. This class must satisfy the UMLdiagram 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. Modifythe 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 themessage No overdraft protection for this exception. Second, theoverdraftProtection amount is not sufficient to cover the deficit; usethe message Insufficient funds for overdraft protection for thisexception.

Page 176: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 176/276

Exercise: Creating Your Own Exception (Level 3)

Lab 8-12 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

public void withdraw(double amount) throws OverdraftException {  if ( balance < amount ) {

double overdraftNeeded = amount - balance;  if ( overdraftAmount < overdraftNeeded ) {

throw new OverdraftException("Insufficient funds for overdraft

protection", overdraftNeeded);

  } else {balance = 0.0;

  overdraftAmount -= overdraftNeeded;  }  } else {

balance = balance - amount;  }  }

Task 4 – Deleting the Current TestBankingClass

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

Task 5 – Copying the TestBankingClass

In this task, you copy the TestBanking.java file from theresources/08_except directory to the com.mybank.test sourcepackage of the BankPrj project.

Task 6 – Compiling the TestBankingClass

In this task, you compile the TestBanking class.

Task 7 – Running the TestBankingProgram

In this task, you run the TestBanking program.

The output should be similar to the output listed on page L8-5.

Page 177: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 177/276

Exercise Summary

Exceptions and Assertions Lab 8-13Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 178: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 178/276

Page 179: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 179/276

Lab 9-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 9

Collections andGenericsFramework

Objectives

Upon completion of this lab, you should be able to:

●   Use a generic collection to manage a one-to-many association

Page 180: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 180/276

Exercise1: Using Collections to Represent Association (Level 1)

Lab 9-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Using Collections to Represent Association(Level 1)

In this exercise, you use generic collections to represent class associations

in the Bank project domain model.

In your previous design, arrays were used to implement multiplicity inthe relationships between the bank and its customers, and betweencustomers and their accounts. This design has several significantlimitations; the most significant is that the array, after it is created, has afixed size. The Collections API was created to solve this and otherlimitations.

Figure 9-1 shows the domain model of the Bank project with the classassociations: a bank serves many customers, and a customer has many

accounts. Figure 9-1 also shows the detailed design for Bank andCustomer classes that use a generic List to maintain these links.

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

-customers : List<Customer>

+addCustomer(f:String, l:String)

+getCustomer(index:int):Customer

+getNumOfCustomers():int

-Bank()

Bank

«constructors»

«methods»

-accounts : List<Account>

+addAccount(acct:Account)

+getAccount(index:int):Account

+getNumOfAccounts():int

+Customer(f:String, l:String)

Customer

«constructors»

«methods»

-firstName : String

-lastName : String

com.mybank.domain

0..*servesCustomer Account0..*has-aBank

CheckingAccountSavingsAccount

Page 181: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 181/276

Exercise1: Using Collections to Represent Association (Level 1)

Collections and Generics Framework Lab 9-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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”

Preparation

There is no preparation for this exercise.

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 BankPrj project in the projectsdirectory.

12

3

Demonstration – The demonstration for this exercise can be found in thedemos/09_collections/exercise directory.

Task 1 – Modifying the BankClass

In this task, you modify the Bank class source file in thecom.mybank.domain source package of the BankPrj project. This classmust satisfy the UML diagram in Figure 9-1 on page L9-2.

Task 2 – Modifying the CustomerClassIn this task, you modify the Customer class source file in thecom.mybank.domain source package of the BankPrj project. This classmust satisfy the UML diagram in Figure 9-1 on page L9-2.

Page 182: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 182/276

Exercise1: Using Collections to Represent Association (Level 1)

Lab 9-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 3 – Compiling the TestReportClass

In this task, you compile the TestReport class.

Task 4 – Running the TestReport Program

In this task, you run the TestReport program. The output should besimilar to the following:

CUSTOMERS REPORT================

Customer: Simms, JaneSavings Account: current balance is 500.0Checking Account: current balance is 200.0

Customer: Bryant, OwenChecking Account: current balance is 200.0

Customer: Soley, TimSavings Account: current balance is 1500.0Checking Account: current balance is 200.0

Customer: Soley, MariaSavings Account: current balance is 150.0

Page 183: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 183/276

Exercise1: Using Collections to Represent Association (Level 2)

Collections and Generics Framework Lab 9-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Using Collections to Represent Association(Level 2)

In this exercise, you use generic collections to represent class associations

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”

Preparation

Thereis nopreparationfor thisexercise.   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 BankPrj project in the projectsdirectory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/09_collections/exercise directory.

Task 1 – Modifying the BankClass

In this task, you modify the Bank class source file in thecom.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 instancevariable.

Page 184: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 184/276

Exercise1: Using Collections to Represent Association (Level 2)

Lab 9-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

2. Modify the static block to initialize the customers instance variableto 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.

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

Task 2 – Modifying the CustomerClass

In this task, you modify the Customer class source file in thecom.mybank.domain source package of the BankPrj project.

Complete the following steps:

1. Modify the declaration for the accounts instance variable to be of 

type List<Account>, and drop the numberOfAccounts instancevariable.

2. Modify the constructor to initialize the accounts instance variable to be a new ArrayList object.

3. Modify the addAccount method to use the add method.

4. Modify the getAccount method to use the get method.

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

Task 3 – Compiling the TestReportClass

In this task, you compile the TestReport class.

Task 4 – Running the TestReportProgram

In this task, you run the TestReport program. The output should besimilar to the following:

CUSTOMERS REPORT================

Customer: Simms, JaneSavings Account: current balance is 500.0Checking Account: current balance is 200.0

Customer: Bryant, OwenChecking Account: current balance is 200.0

Page 185: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 185/276

Exercise1: Using Collections to Represent Association (Level 2)

Collections and Generics Framework Lab 9-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Customer: Soley, TimSavings Account: current balance is 1500.0Checking Account: current balance is 200.0

Customer: Soley, MariaSavings Account: current balance is 150.0

Page 186: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 186/276

Exercise1: Using Collections to Represent Association (Level 3)

Lab 9-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Using Collections to Represent Association(Level 3)

In this exercise, you use generic collections to represent class associations

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”

Preparation

There is no preparation for this exercise.

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 BankPrj project in the projectsdirectory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/09_collections/exercise directory.

Page 187: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 187/276

Exercise1: Using Collections to Represent Association (Level 3)

Collections and Generics Framework Lab 9-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Modifying the BankClass

In this task, you modify the Bank class source file in thecom.mybank.domain source package of the BankPrj project.

Complete the following steps:

1. Add the two import statements to include the collections classes youwill 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 instancevariable.

private static List<Customer> customers;

3. Modify the static block to initialize the customers instance variableto be a new ArrayList object.

static {  customers = new ArrayList<Customer>(10);  }

4. Modify the addCustomer method to use the add method.

public static void addCustomer(String f, String l) {  customers.add(new Customer(f, l));  }

5. Modify the getCustomer method to use the get method.

public static Customer getCustomer(int customer_index) {  return customers.get(customer_index);  }

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

public static int getNumOfCustomers() {  return customers.size();  }

Task 2 – Modifying the CustomerClass

In this task, you modify the Customer class source file in thecom.mybank.domain source package of the BankPrj project.

Complete the following steps:

Page 188: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 188/276

Exercise1: Using Collections to Represent Association (Level 3)

Lab 9-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

1. Add the two import statements to include the collections classes youwill use in the Bank class.

import java.util.List;import java.util.ArrayList;

2. Modify the declaration for the accounts instance variable to be of type List<Account>, and drop the numberOfAccounts instancevariable.

private List<Account> accounts;

3. Modify the constructor to initialize the accounts instance variable to be a new ArrayList object.

public Customer(String f, String l) {  firstName = f;  lastName = l;  // initialize accounts instance variable

  accounts = new ArrayList<Account>(10);  }

4. Modify the addAccount method to use the add method.

public void addAccount(Account acct) {  accounts.add(acct);  }

5. Modify the getAccount method to use the get method.

public Account getAccount(int account_index) {  return accounts.get(account_index);  }

6. Modify the getNumOfAccounts method to use the size method.

public int getNumOfAccounts() {  return accounts.size();  }

Task 3 – Compiling the TestReportClass

In this task, you compile the TestReport class.

Page 189: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 189/276

Exercise1: Using Collections to Represent Association (Level 3)

Collections and Generics Framework Lab 9-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 4 – Running the TestReportProgram

In this task, you run the TestReport program. The output should besimilar to the following:

CUSTOMERS REPORT================

Customer: Simms, Jane  Savings Account: current balance is 500.0  Checking Account: current balance is 200.0

Customer: Bryant, Owen  Checking Account: current balance is 200.0

Customer: Soley, Tim

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

Customer: Soley, Maria  Checking Account: current balance is 200.0  Savings Account: current balance is 150.0

Page 190: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 190/276

Exercise Summary

Lab 9-12 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 191: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 191/276

Lab 10-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 10

I/OFundamentals

There are no exercises for this module.

Page 192: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 192/276

Page 193: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 193/276

Lab 11-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 11

ConsoleI/OandFileI/O

Objectives

Upon completion of this lab, you should be able to:

●   Read a data file using the Scanner API

●   Use a generic collection to manage a one-to-many association

Page 194: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 194/276

Exercise 1: Reading a Data File (Level 1)

Lab 11-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Reading a Data File (Level 1)

In this exercise, you create a class that reads customer and account datafrom a flat file.

Figure 11-1 shows the UML diagram for the DataSource class that youcreate for the TestReport program.

Figure 11-1   The DataSource Class Loads Customer Data From a FlatFile

Code 11-1 shows an example of the format of the customer data file. Thefirst line contains an integer, which determines the number of customersin the data file. A customer record contains the first name, last name, andthe number of accounts, separated by tab characters. Each account recordcontains 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>

TestReport

DataSource

-dataFile : File

CustomerReport

«constructors»

+DataSource(dataFilePath:String)

+loadData():void

«methods» IOException«exception»

{from java.io}«send»

test.dat

{from com.mybank.data}

«read»

Page 195: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 195/276

Exercise 1: Reading a Data File (Level 1)

Console I/O and File I/O Lab 11-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Code 11-2 shows an example of the format of the customer data file. Thisdata file contains four customer records. The first is for Jane Simms; Janehas two bank accounts. The first account is a savings account, with aninitial balance of 500.00 and an interest rate of 5 percent (0.05). The secondaccount is a checking account with an initial balance of 200.00 and

overdraft protection of 400.00.

Code 11-2  Example Test Data File

4

Jane Simms 2S 500.00 0.05C 200.00 400.00

Owen Bryant 1C 200.00 0.00

Tim Soley 2S 1500.00 0.05C 200.00 0.00

Maria Soley 1S 150.00 0.05

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”

●   “Task 6 – Compiling the TestReport Class”

●   “Task 7 – Running the BankPrj Project”

Page 196: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 196/276

Exercise 1: Reading a Data File (Level 1)

Lab 11-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

There is no preparation for this exercise.

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

1

23

Demonstration – The demonstration for this exercise can be found in thedemos/11_fileio/exercise directory.

Task 1 – Creating a dataDirectory

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_fileiodirectory into the data directory.

Page 197: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 197/276

Exercise 1: Reading a Data File (Level 1)

Console I/O and File I/O Lab 11-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 3 – Creating the DataSourceClass

In this task, you create the DataSource class in the com.mybank.datasource package of the BankPrj project with the following characteristics:

Class Name: DataSourceProject: BankPrj

Location: Source Packages

Package: com.mybank.data

The class must satisfy the UML diagram in Figure 11-1 on page L11-2. TheloadData method must use Bank utility methods (addCustomer andgetCustomer) to populate the customers recorded in the data file.Furthermore, the Customer class has the addAccount method to add theaccounts from the data file.

Task 4 – Deleting Unnecessary Classes

In this task, you delete the following Java classes that are no longer used:

TestReportTestAccountTestAccount2TestBatchTestBanking

Task 5 – Copying the TestReportClass

In this task, you copy the TestReport class from theresources/11_fileio directory to the com.mybank.test sourcepackage of the BankPrj project.

Task 6 – Compiling the TestReportClass

In this task, you compile the TestReport class. If there are compilationerrors, make necessary changes to the class and recompile it.

Page 198: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 198/276

Exercise 1: Reading a Data File (Level 1)

Lab 11-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 7 – Running the BankPrjProject

In this task, you set the TestReport class as the main class of theBankPrj project, and run the BankPrj project with an argumentdata/test.dat.

Tool Reference – Java Development: Java Application Projects: SettingArguments

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

Tool Reference – Java Development: Java Application Projects: Setting theMain Class

2. Set the main class of the BankPrj project tocom.mybank.test.TestReport.

Tool Reference – Java Development: Java Application Projects: RunningProjects

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

Reading data file: ../data/test.datCUSTOMERS REPORT

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

Customer: Simms, Jane

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

Customer: Bryant, Owen  Checking Account: current balance is 200.0

Customer: Soley, Tim  Savings Account: current balance is 1500.0  Checking Account: current balance is 200.0

Customer: Soley, Maria  Savings Account: current balance is 150.0

Page 199: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 199/276

Exercise 1: Reading a Data File (Level 2)

Console I/O and File I/O Lab 11-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Reading a Data File (Level 2)

In this exercise, you create a class that reads customer and account datafrom a flat file.

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”

●   “Task 6 – Compiling the TestReport Class”

●   “Task 7 – Running the BankPrj Project”

Preparation

There is no preparation for this exercise.

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

Page 200: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 200/276

Exercise 1: Reading a Data File (Level 2)

Lab 11-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

123

Demonstration – The demonstration for this exercise can be found in thedemos/11_fileio/exercise directory.

Task 1 – Creating a dataDirectory

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_fileiodirectory into the data directory.

Task 3 – Creating the DataSourceClass

Complete the following steps:

1. Create the DataSource class in the com.mybank.data sourcepackage of the BankPrj project with the following characteristics:

Class Name: DataSource

Project: BankPrj

Location: Source Packages

Package: com.mybank.data

2. Add the dataFile instance variable to the DataSource class.

3. Add a public constructor that takes a string argument dataFilePathand initializes the dataFile instance variable.

4. Add a public method, loadData, that populates the Bank customerobjects and each customer’s account objects. Here is the pseudo-codefor this method:

read <number-of-customers>for each customer recordread <first-name> and <last-name>add customer to Bankread <number-of-accounts>for each accountread <account-type-code>switch on <account-type-code>

Page 201: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 201/276

Exercise 1: Reading a Data File (Level 2)

Console I/O and File I/O Lab 11-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Savings:read <initial-balance> and <interest-rate)create account and add account to customer

Checking:read <initial-balance> and <overdraft-amount)

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:

TestReportTestAccountTestAccount2TestBatch

TestBanking

Task 5 – Copying the TestReportClass

In this task, you copy the TestReport class from theresources/11_fileio directory to the com.mybank.test sourcepackage of the BankPrj project.

Task 6 – Compiling the TestReportClass

In this task, you compile the TestReport class. If there are compilationerrors, make necessary changes to the class and recompile it.

Task 7 – Running the BankPrjProject

In this task, you set the TestReport class as the main class of theBankPrj project, and run the BankPrj project with an argumentdata/test.dat.

Tool Reference – Java Development: Java Application Projects: SettingArguments

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

Page 202: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 202/276

Exercise 1: Reading a Data File (Level 2)

Lab 11-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Tool Reference – Java Development: Java Application Projects: Setting theMain Class

2. Set the main class of the BankPrj project tocom.mybank.test.TestReport.

Tool Reference – Java Development: Java Application Projects: RunningProjects

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

Reading data file: ../data/test.datCUSTOMERS REPORT

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

Customer: Simms, Jane

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

Customer: Bryant, Owen  Checking Account: current balance is 200.0

Customer: Soley, Tim  Savings Account: current balance is 1500.0  Checking Account: current balance is 200.0

Customer: Soley, Maria

  Savings Account: current balance is 150.0

Page 203: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 203/276

Exercise 1: Reading a Data File (Level 3)

Console I/O and File I/O Lab 11-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Reading a Data File (Level 3)

In this exercise, you create a class that reads customer and account datafrom a flat file.

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”

●   “Task 6 – Compiling the TestReport Class”

●   “Task 7 – Running the BankPrj Project”

Preparation

There is no preparation for this exercise.

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

Page 204: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 204/276

Exercise 1: Reading a Data File (Level 3)

Lab 11-12 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

123

Demonstration – The demonstration for this exercise can be found in thedemos/11_fileio/exercise directory.

Task 1 – Creating a dataDirectory

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.

4. Select Other in the Categories pane.

5. Select Folder in the File Types pane.

6. Click Next.

7. Enter data for the folder name.

8. Click Finish.

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.

Task 3 – Creating the DataSourceClass

Complete the following steps:

1. Create the DataSource class in the com.mybank.data sourcepackage 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 herepublic class DataSource {// insert code here

Page 205: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 205/276

Exercise 1: Reading a Data File (Level 3)

Console I/O and File I/O Lab 11-13Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

}

2. Add an import statement to import necessary class names:

import com.mybank.domain.*;import java.io.File;import java.io.IOException;

import java.util.Scanner;

3. Add the dataFile instance variable to the DataSource class.

private File dataFile;

4. Add a public constructor that takes a string argument dataFilePathand initializes the dataFile instance variable.

public DataSource(String dataFilePath) {  this.dataFile = new File(dataFilePath);  }

Page 206: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 206/276

Exercise 1: Reading a Data File (Level 3)

Lab 11-14 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

5. Add a public method, loadData, that populates the Bank customerobjects and each customer’s account objects, shown as follows:

public void loadData() throws IOException {  // Data source variables  Scanner input = new Scanner(dataFile);

  // 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  int numOfAccounts = input.nextInt();

  while ( numOfAccounts-- > 0 ) {  // Create a specific type of account  char accountType = input.next().charAt(0);  switch ( accountType ) {  // Savings account  case ’S’: {  float initBalance = input.nextFloat();  float interestRate = input.nextFloat();  customer.addAccount(new SavingsAccount(initBalance,  interestRate));  break;

  }  // Checking account  case ’C’: {  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  }

Page 207: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 207/276

Exercise 1: Reading a Data File (Level 3)

Console I/O and File I/O Lab 11-15Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 4 – Deleting Unnecessary Classes

In this task, you delete the following Java classes that are no longer used:

TestReport

TestAccountTestAccount2TestBatchTestBanking

Task 5 – Copying the TestReportClass

In this task, you copy the TestReport class from theresources/11_fileio directory to the com.mybank.test sourcepackage of the BankPrj project.

Task 6 – Compiling the TestReportClass

In this task, you compile the TestReport class. If there are compilationerrors, make necessary changes to the class and recompile it.

Task 7 – Running the BankPrjProject

In this task, you set the TestReport class as the main class of theBankPrj project, and run the BankPrj project with an argumentdata/test.dat.

Tool Reference – Java Development: Java Application Projects: SettingArguments

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

Tool Reference – Java Development: Java Application Projects: Setting theMain Class

2. Set the main class of the BankPrj project tocom.mybank.test.TestReport.

Tool Reference – Java Development: Java Application Projects: RunningProjects

Page 208: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 208/276

Exercise 1: Reading a Data File (Level 3)

Lab 11-16 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

Reading data file: ../data/test.datCUSTOMERS REPORT

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

Customer: Simms, Jane  Savings Account: current balance is 500.0  Checking Account: current balance is 200.0

Customer: Bryant, Owen  Checking Account: current balance is 200.0

Customer: Soley, Tim  Savings Account: current balance is 1500.0  Checking Account: current balance is 200.0

Customer: Soley, Maria  Savings Account: current balance is 150.0

Page 209: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 209/276

Exercise Summary

Console I/O and File I/O Lab 11-17Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 210: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 210/276

Page 211: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 211/276

Lab 12-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 12

BuildingJavaGUIsUsingtheSwingAPI

Objectives

Upon completion of this lab, you should be able to:

●   Create a GUI for the ChatRoom project

●   (Optional) Create a GUI for the Banking project

Page 212: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 212/276

Exercise1: Creating theChatClientGUI Part 1 (Level 1)

Lab 12-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Creating the ChatClientGUI Part 1 (Level 1)

In this exercise, you create a GUI for a  chat room application. You use acomplex layout to position properly several GUI components in a frame.

Figure 12-1 shows the GUI design that you will attempt to achieve.

Figure 12-1   GUI Layout for the ChatClient Application

As shown in Figure 12-1, there are four components in this GUI. The maincomponent 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”

Send Button Component

Quit Button Component

The JTextArea Component

The JTextField Component

Page 213: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 213/276

Exercise1: Creating theChatClientGUI Part 1 (Level 1)

Building Java GUIs Using the Swing API Lab 12-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

There is no preparation for this exercise.

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

For this exercise, you first create the ChatRoomPrj project in theprojects directory, and then work in this project for all the followingexercises that are part of the ChatRoomPrj project.

123

Demonstration – The demonstration for this exercise can be found in thedemos/12_gui/exercise1 directory.

Task 1 – Creating the ChatClientClass

In this task, you create the ChatClient class in the source package of theChatRoomPrj project implement the GUI design in Figure 12-1 onpage 12-2.

Complete the following steps:

1. Create the ChatRoomPrj Java Application Project with thefollowing 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 theChatRoomPrj project with the following characteristics:

Class Name: ChatClient

Page 214: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 214/276

Exercise1: Creating theChatClientGUI Part 1 (Level 1)

Lab 12-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Project: ChatRoomPrj

Location: Source Packages

Package: default package

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

Task 2 – Compiling the ChatClientClass

In this task, you compile the ChatClient class.

Task 3 – Running the ChatClientProgram

In this task, you run the ChatClient program. You should see the GUIshown in Figure 12-1 on page 12-2. If your GUI does not look exactly likethe figure, then edit the code to tweak the design to match this figure.

Task 4 – Terminating the Running ChatClientProgram

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

Process

In this task, you terminate the running ChatClient program.

Page 215: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 215/276

Exercise1: Creating theChatClientGUI Part 1 (Level 2)

Building Java GUIs Using the Swing API Lab 12-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Creating the ChatClientGUI Part 1 (Level 2)

In this exercise, you create a GUI for a  chat room application. You use acomplex layout to properly position several GUI components in a frame.

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

There is no preparation for this exercise.

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

For this exercise, you first create the ChatRoomPrj project in theprojects directory, and then work in this project for all the followingexercises that are part of the ChatRoomPrj project.

1

23

Demonstration – The demonstration for this exercise can be found in thedemos/12_gui/exercise1 directory.

Page 216: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 216/276

Exercise1: Creating theChatClientGUI Part 1 (Level 2)

Lab 12-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Creating the ChatClientClass

In this task, you create the ChatClient class in the source package of theChatRoomPrj project implement the GUI design in Figure 12-1 onpage 12-2.

Complete the following steps:

1. Create the ChatRoomPrj Java Application Project with thefollowing 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 with the following characteristics:

Class Name: ChatClient

Project: ChatRoomPrj

Location: Source Packages

Package: default package

3. Add four instance variables to the ChatClient class to hold the GUIcomponents.

4. Add a public constructor that initializes each of the four GUIcomponent instance variables: The text area should be 10 rows talland 50 columns wide, the text field should be 50 columns wide, thesend button should have the word Send in the display, and the quit button should display a similar label.

5. Create a launchFrame method that constructs the layout of thecomponents. Feel free to use nested panels and any layout managersthat will help you construct the layout in the GUI design shownabove.

6. Create the main method. This method instantiates a newChatClient object and then calls the launchFrame method.

Task 2 – Compiling the ChatClientClass

In this task, you compile the ChatClient class.

Page 217: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 217/276

Exercise1: Creating theChatClientGUI Part 1 (Level 2)

Building Java GUIs Using the Swing API Lab 12-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 3 – Running the ChatClientProgram

In this task, you run the ChatClient program. You should see the GUIshown in Figure 12-1 on page 12-2. If your GUI does not look exactly likethe figure, then edit the code to tweak the design to match this figure.

Task 4 – Terminating the Running ChatClientProgram

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

In this task, you terminate the running ChatClient program.

Page 218: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 218/276

Exercise 1: Creating the ChatClient GUI Part 1 (Level 3)

Lab 12-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Creating the ChatClient GUI Part 1 (Level 3)

In this exercise, you create a GUI for a  chat room application. You use acomplex layout to properly position several GUI components in a frame.

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

There is no preparation for this exercise.

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

For this exercise, you first create the ChatRoomPrj project in theprojects directory, and then work in this project for all the followingexercises that are part of the ChatRoomPrj project.

1

23

Demonstration – The demonstration for this exercise can be found in thedemos/12_gui/exercise1 directory.

Page 219: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 219/276

Exercise 1: Creating the ChatClient GUI Part 1 (Level 3)

Building Java GUIs Using the Swing API Lab 12-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Creating the ChatClientClass

In this task, you create the ChatClient class in the source package of theChatRoomPrj project implement the GUI design in Figure 12-1 onpage 12-2.

Complete the following steps:

1. Create the ChatRoomPrj Java Application Project with thefollowing 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 with the following characteristics:

Class Name: ChatClient

Project: ChatRoomPrj

Location: Source Packages

Package: default package

3. Import the java.awt   and javax.swing   packages.

import java.awt.*;import javax.swing.*;public class ChatClient {// insert code here

}

4. Add four instance variables to the ChatClient class to hold the GUIcomponents.

private JTextArea output;  private JTextField input;  private JButton sendButton;  private JButton quitButton;

5. Add a public constructor that initializes each of the four GUIcomponent instance variables: The text area should be 10 rows talland 50 columns wide, the text field should be 50 columns wide, thesend 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");

Page 220: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 220/276

Exercise 1: Creating the ChatClient GUI Part 1 (Level 3)

Lab 12-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

  quitButton = new JButton("Quit");  }

6. Create a launchFrame method, which constructs the layout of thecomponents. Feel free to use nested panels and any layout managersthat will help you construct the layout in the GUI design shown

above.public void launchFrame() {

  JFrame frame = new JFrame("Chat Room");

  // Use the Border Layout for the frame  frame.setLayout(new BorderLayout());

  frame.add(output, BorderLayout.WEST);  frame.add(input, BorderLayout.SOUTH);

  // Create the button panel  JPanel p1 = new JPanel();

p1.setLayout(new GridLayout(2,1));  p1.add(sendButton);  p1.add(quitButton);

  // Add the button panel to the center  frame.add(p1, BorderLayout.CENTER);

  frame.pack();  frame.setVisible(true);

  }7. Create the main method. This method instantiates a new

ChatClient object and then calls the launchFrame method.

public static void main(String[] args) {  ChatClient c = new ChatClient();  c.launchFrame();  }

Task 2 – Compiling the ChatClientClass

In this task, you compile the ChatClient class.

Page 221: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 221/276

Exercise 1: Creating the ChatClient GUI Part 1 (Level 3)

Building Java GUIs Using the Swing API Lab 12-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 3 – Running the ChatClientProgram

In this task, you run the ChatClient program. You should see the GUIshown in Figure 12-1 on page 12-2. If your GUI does not look exactly likethe figure, then edit the code to tweak the design to match this figure.

Task 4 – Terminating the Running ChatClientProgram

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

In this task, you terminate the running ChatClient program.

Page 222: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 222/276

Exercise 2: Creating the Bank ATM GUI Part 1 (Advanced)

Lab 12-12 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Creating the Bank ATM GUI Part 1(Advanced)

In this exercise, you create an automated teller machine (ATM) GUI for

the Bank project. You use a complex layout to properly position severalGUI components in a frame.

Note – This is an advanced exercise. It is optional and should only beattempted if you have already completed the previous exercise for thismodule.

Figure 12-2 shows the GUI design that you will attempt to achieve.

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”

Message JTextField Component

Data Entry JTextField Component

Output JTextArea Component

 Action Button Panel

Key Pad Panel

Page 223: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 223/276

Exercise 2: Creating the Bank ATM GUI Part 1 (Advanced)

Building Java GUIs Using the Swing API Lab 12-13Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

There is no preparation for this exercise.

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

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

directory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/12_gui/exercise2 directory.

Task 1 – Copying the ATMClientClass

Complete the following steps:

1. Create the com.mybank.gui source package in the BankPrj project.

2. Copy the ATMClient.java template file from theresources/12_gui directory into the com.mybank.gui sourcepackage of the BankPrj project. This template code provides themain method, which initializes a set of bank customers and thenlaunches the ATM GUI.

Page 224: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 224/276

Exercise 2: Creating the Bank ATM GUI Part 1 (Advanced)

Lab 12-14 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 2 – Modifying the ATMClientClass

In this task, you modify the ATMClient to implement the ATM GUIscreen, shown in Figure 12-2 on page 12-12. The GUI components musthave the following characteristics:

●   The Message text field must have a width of 75 characters (calledcolumns 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 itmust be read-only. The user will use the key pad buttons to enterdata which will be displayed in the Data Entry field. This action will be coded in the next module.

●   The Output text area must have a width of 75 characters and a height(called rows in the API) of 10 characters and it must be read-only.

Note – In this exercise, you will only be creating the layout of the ATMscreen. You will not be creating the code to make the buttons respond touser actions; you will do that in the next module.

Task 3 – Compiling the ATMClientClass

In this task, you compile the ATMClient class.

Task 4 – Running the ATMClientProgram

Complete the following steps:

1. Set the main class of the BankPrj project tocom.mybank.gui.ATMClient.

2. Run the BankPrj project. You should see the GUI shown inFigure 12-2 on page 12-12.

Page 225: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 225/276

Exercise 2: Creating the Bank ATM GUI Part 1 (Advanced)

Building Java GUIs Using the Swing API Lab 12-15Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Hints

These hints might help you to solve this exercise.

●   Use the setEnabled(false) method to make a component

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 1in the columns parameters of the GridLayout(int rows, intcolumns) constructor.

Page 226: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 226/276

Exercise Summary

Lab 12-16 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 227: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 227/276

Lab 13-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 13

HandlingGUI-GeneratedEvents

Objectives

Upon completion of this lab, you should be able to:

●   Create the GUI event handlers for the ChatRoom project

●   (Optional) Create the GUI event handlers for the Banking project

Page 228: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 228/276

Exercise1: Creating theChatClientGUI Part 2 (Level 1)

Lab 13-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Creating the ChatClientGUI Part 2 (Level 1)

In this exercise, you implement the basic event handlers for the  chat roomapplication. At this stage in the development of the ChatClientGUI, youneed to create the following event listeners:

●   Create an ActionListener that copies the text from the input textfield into the output text area when the send button is pressed.

●   Create an ActionListener that copies the text from the input textfield into the output text area when the Enter key is pressed in theinput text field.

●   Create an ActionListener that will quit the program when the Quit button is pressed. (Hint – Use System.exit(0).)

●   Create a WindowListener that will quit the program when the closewidget is pressed on the frame.

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

There is no preparation for this exercise.

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/13_events/exercise1 directory.

Page 229: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 229/276

Exercise1: Creating theChatClientGUI Part 2 (Level 1)

Handling GUI-Generated Events Lab 13-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Modifying the ChatClientClass

In this task, you modify the ChatClient class in the source package of theChatRoomPrj project. This class must implement event listeners listed inthe introduction to this exercise.

Task 2 – Compiling the ChatClientClass

In this task, you compile the ChatClient class.

Task 3 – Running the ChatClientProgram

In this task, you run the ChatClient program. Test the behavior of the

event listeners you added.

Hints

Use the following hints during this exercise:

●   Have the listeners (inner classes) access the instance variables of their containing class to refer to the components like the output textarea and the input text field. Remember that you made thecomponents instance variables in the previous lab.

●   Remember to import the java.awt.event package.

●   To get the text from a JTextArea or JTextField, you can use thegetText method; to set the text, use either the setText or appendmethod.

Page 230: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 230/276

Exercise1: Creating theChatClientGUI Part 2 (Level 2)

Lab 13-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Creating the ChatClientGUI Part 2 (Level 2)

In this exercise, you implement the basic event handlers for the  chat roomapplication. At this stage in the development of the ChatClientGUI, youneed to create the event listeners listed in ‘‘Exercise 1: Creating theChatClient 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

There is no preparation for this exercise.

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/13_events/exercise1 directory.

Task 1 – Modifying the ChatClientClass

In this task, you modify the ChatClient class in the source package of theChatRoomPrj project. This class must implement event listeners listed inthe introduction to ‘‘Exercise 1: Creating the ChatClient GUI Part 2 (Level1)’’ on page L13-2.

Page 231: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 231/276

Exercise1: Creating theChatClientGUI Part 2 (Level 2)

Handling GUI-Generated Events Lab 13-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Complete the following steps:

1. Import the java.awt.event package.

2. Add the ActionListener for the Send button. This listener mustextract the text from the text field and display that text in the text

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 exitthe ChatClient program. Use an inner class for this listener.

5. Add the ActionListener for the Quit button. This listener must exitthe ChatClient program. Use an anonymous inner class for thislistener.

Task 2 – Compiling the ChatClientClass

In this task, you compile the ChatClient class.

Task 3 – Running the ChatClientProgram

In this task, you run the ChatClient program. Test the behavior of theevent listeners you added.

Page 232: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 232/276

Exercise1: Creating theChatClientGUI Part 2 (Level 3)

Lab 13-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 1: Creating the ChatClientGUI Part 2 (Level 3)

In this exercise, you implement the basic event handlers for the  chat roomapplication. At this stage in the development of the ChatClientGUI, youneed 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”

Preparation

There is no preparation for this exercise.

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/13_events/exercise1 directory.

Task 1 – Modifying the ChatClientClass

In this task, you modify the ChatClient class in the source package of theChatRoomPrj project. This class must implement event listeners listed inthe introduction to ‘‘Exercise 1: Creating the ChatClient GUI Part 2 (Level1)’’ on page L13-2.

1. Import the java.awt.event package.

import java.awt.event.*;public class ChatClient {// your code here

}

Page 233: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 233/276

Exercise1: Creating theChatClientGUI Part 2 (Level 3)

Handling GUI-Generated Events Lab 13-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

2. Add the ActionListener for the Send button. This listener mustextract the text from the text field and display that text in the textarea. Use an inner class for this listener.

private void launchFrame() {// GUI component initalization code here

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("");  }  }

3. Add the ActionListener for the text field. Can you use the samelistener in Step 2?

private void launchFrame() {// GUI component initalization code hereinput.addActionListener(new SendHandler());// more code

}

In this solution, the SendHandler inner class was reused to reduceredundant code.

4. Add the WindowListener to the GUI frame. This listener must exitthe ChatClient program. Use an inner class for this listener.

private void launchFrame() {// GUI component initalization code hereframe.addWindowListener(new CloseHandler());// more code

}

private class CloseHandler extends WindowAdapter {  public void windowClosing(WindowEvent e) {  System.exit(0);

  }  }

Page 234: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 234/276

Exercise1: Creating theChatClientGUI Part 2 (Level 3)

Lab 13-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

5. Add the ActionListener for the Quit button. This listener must exitthe ChatClient program. Use an anonymous inner class for thislistener.

private void launchFrame() {// GUI component initalization code here

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.How could you have satisfied both listener interfaces using theCloseHandler

 class?

Task 2 – Compiling the ChatClientClass

In this task, you compile the ChatClient class.

Task 3 – Running the ChatClientProgram

In this task, you run the ChatClient program. Test the behavior of theevent listeners you added.

Page 235: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 235/276

Exercise 2: Creating the Bank ATM GUI Part 2 (Advanced)

Handling GUI-Generated Events Lab 13-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise 2: Creating the Bank ATM GUI Part 2(Advanced)

In this exercise, you modify the ATMClient class in the BankPrj project

 by adding necessary event handling capabilities.

Note – This is an advanced exercise. It is optional and should only beattempted if you have already completed the previous exercise for thismodule.

The simulated ATM must behave in this manner:

1. The ATM screen is displayed.

At this stage, the Action buttons must be disabled and the followingtext must be displayed in the Output text area: Enter yourcustomer ID into the key pad and press the ENTERbutton.

2. The user enters the ID using the key pad buttons. Each number isdisplayed in the Data Entry text field.

When the ENTER button is selected, the application retrieves thespecified customer object and displays the following text in theOutput text area: Welcome   FIRST-NAME LAST-NAME  if the customerwas found; otherwise, the following text is displayed: Customer ID

was not found. Finally, if the customer was found, then the Action buttons are enabled.

3. The user selects one of the Action buttons.

If the action is either deposit or withdraw, then the user is promptedto enter the amount. The user can then enter the amount by clickingthe key pad buttons which (again) places digits in the Data Entrytext field. When the ENTER button is selected, the program executesthe action with the amount entered in the Data Entry text field.Finally, the result of the operation must be displayed in the Outputtext 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”

Page 236: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 236/276

Exercise 2: Creating the Bank ATM GUI Part 2 (Advanced)

Lab 13-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

There is no preparation for this exercise.

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/13_events/exercise2 directory.

Task 1 – Modifying the ATMClientClass

In this task, you modify the ATMClient class in the source package of theBankPrj project. This class must rely on necessary event listeners toimplemented the required behavior.

Task 2 – Compiling the ATMClientClass

In this task, you compile the ATMClient class.

Task 3 – Running the BankPrjProject

In this task, you run the BankPrj project.

Page 237: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 237/276

Exercise 2: Creating the Bank ATM GUI Part 2 (Advanced)

Handling GUI-Generated Events Lab 13-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

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

Page 238: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 238/276

Exercise Summary

Lab 13-12 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 239: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 239/276

Lab 14-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 14

GUI-BasedApplications

Objectives

Upon completion of this lab, you should be able to add menus to the GUIfor the ChatRoom project.

Page 240: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 240/276

Exercise: Creating theChatClientGUI, Part 3 (Level 1)

Lab 14-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise: Creating the ChatClientGUI, Part 3 (Level 1)

In this exercise, you enhance the GUI for a  chat room application. Youcomplete the GUI for the ChatClient by adding a JComboBoxcomponent, a JScrollPane component, and two menus.

Figure 14-1 shows the GUI design that you will attempt to achieve.

Figure 14-1   GUI Layout for the ChatClient Application

You need to add four features to the existing GUI:

●   Add the user name JComboBox component under the Send and Quit buttons. This component enables you to select a name that is postedwith every chat line that you enter. You must alter the Send buttonand JTextField listeners to write the username to the output

JTextArea component. Add several user name options includingyour full name and a few nicknames, such as  1337dud3 or  Java Geek .

●   Put the JTextArea component into a JScrollPane component. Adda vertical scroll bar but no horizontal scroll bar. Auto scroll the textto the bottom of the JTextArea as the user adds text to the text chatwindow.

●   Add the File menu. This menu must include a Quit menu item thatterminates the program when selected.

●   Add the Help menu. This menu must include an About menu itemthat pops up a simple dialog box, which displays a comment aboutthe 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”

Page 241: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 241/276

Exercise: Creating theChatClientGUI, Part 3 (Level 1)

GUI-Based Applications Lab 14-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

There is no preparation for this exercise.

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/14_guiapps/exercise1 directory.

Task 1 – Modifying the ChatClientClass

In this task, you modify the ChatClient class in the source package of theChatRoomPrj project. This class must implement the GUI design inFigure 14-1 on page L14-2.

Task 2 – Compiling the ChatClientClass

In this task, you compile the ChatClient class.

Task 3 – Running the ChatClientProgram

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 likethe figure, then edit the code to tweak the design to match this figure.

Page 242: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 242/276

Exercise: Creating theChatClientGUI, Part 3 (Level 2)

Lab 14-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise: Creating the ChatClientGUI, Part 3 (Level 2)

In this exercise, you enhance the GUI for a  chat room application. Youcomplete the GUI for the ChatClient by adding a JComboBox componentand 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

There is no preparation for this exercise.

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.

123

Demonstration – The demonstration for this exercise can be found in thedemos/14_guiapps/exercise1 directory.

Task 1 – Modifying the ChatClientClass

In this task, you modify the ChatClient class in the source package of theChatRoomPrj project. This class must implement the GUI design inFigure 14-1 on page L14-2.

Complete the following steps:

Page 243: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 243/276

Exercise: Creating theChatClientGUI, Part 3 (Level 2)

GUI-Based Applications Lab 14-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

1. Add the user name JComboBox component under the Send and Quit buttons. This component enables you to select a name that is postedwith every chat line that you enter. Add several user name optionsincluding your full name and a few nicknames, such as  1337dud3 or

 Java Geek .

2. Enhance the listeners for the Send button and JTextField to writethe user name to the output JTextArea component.

3. Put the JTextArea component into a JScrollPane component. Adda vertical scroll bar but no horizontal scroll bar. Auto scroll the textto the bottom of the JTextArea as the user adds text to the text chatwindow.

4. Add the File menu. This menu must include a Quit menu item thatterminates the program when selected.

5. Add the Help menu. This menu must include an About menu item

that pops up a simple dialog box, which displays a comment aboutthe program and about you, the developer.

Task 2 – Compiling the ChatClientClass

In this task, you compile the ChatClient class.

Task 3 – Running the ChatClientProgram

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 likethe figure, then edit the code to tweak the design to match this figure.

Page 244: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 244/276

Exercise: Creating theChatClientGUI, Part 3 (Level 3)

Lab 14-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise: Creating the ChatClientGUI, Part 3 (Level 3)

In this exercise, you enhance the GUI for a  chat room application. Youcomplete the GUI for the ChatClient by adding a JComboBox componentand 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

There is no preparation for this exercise.

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.

123

Demonstration – The demonstration for this exercise can be found in thedemos/14_guiapps/exercise1 directory.

Task 1 – Modifying the ChatClientClass

In this task, you modify the ChatClient class in the source package of theChatRoomPrj project. This class must implement the GUI design inFigure 14-1 on page L14-2.

Complete the following steps:

Page 245: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 245/276

Exercise: Creating theChatClientGUI, Part 3 (Level 3)

GUI-Based Applications Lab 14-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

1. Add the user name JComboBox component under the Send and Quit buttons. This component enables you to select a name that is postedwith every chat line that you enter. Add several user name optionsincluding your full name and a few nicknames, such as  1337dud3 or

 Java Geek .

public class ChatClient {// existing code hereprivate JComboBox usernames;// existing code herepublic ChatClient() {

  // more GUI components initializedusernames = new JComboBox();usernames.addItem("Jane Doe");usernames.addItem("1337dud3");usernames.addItem("Java Geek");

}

public void launchFrame() {  // existing code here  // Create the button panel  JPanel p1 = new JPanel();

p1.setLayout(new GridLayout(3,1));  p1.add(sendButton);  p1.add(quitButton);

p1.add(usernames);  // existing code here}// existing code here

}

2. Add the aboutDialog instance variable of typejavax.swing.JDialog to the ChatClient class.

3. Add the frame instance variable of type javax.swing.JFrame tothe ChatClient class.

4. Modify the declaration and initialization of the frame variable in thelaunchFrame method to the following:

frame = new JFrame("Chat Room");

5. Enhance the listeners for the Send button and JTextField to writethe 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("");  }

Page 246: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 246/276

Exercise: Creating theChatClientGUI, Part 3 (Level 3)

Lab 14-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

  }

6. Add a JScrollPane component to the project and add theJTextArea component to the a JScrollPane. Add a vertical scroll bar but no horizontal scroll bar.

// Add declarationprivate JScrollPane textPane;// existing code here

// Put JTextArea into JScrollPane and define scroll barstextPane = new JScrollPane(output,

ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

// existing code here

// Add JScrollPane to Layoutframe.add(textPane, BorderLayout.WEST);

7. Auto scroll the text to the bottom of the JTextArea as the user addstext to the text chat window.

// Add to SendHandler to enable AutoScrolloutput.setCaretPosition(output.getDocument().getLength()-1);

8. Add the File menu. This menu must include a Quit menu item thatterminates the program when selected.

public void launchFrame() {// existing code here

// Create menu bar and File menu  JMenuBar mb = new JMenuBar();  JMenu file = new JMenu("File");  JMenuItem quitMenuItem = new JMenuItem("Quit");  quitMenuItem.addActionListener(new ActionListener() {  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 itemthat pops up a simple dialog box, that displays a comment about theprogram and about you, the developer.

public void launchFrame() {

Page 247: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 247/276

Exercise: Creating theChatClientGUI, Part 3 (Level 3)

GUI-Based Applications Lab 14-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

// 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());  help.add(aboutMenuItem);  mb.add(help);

// existing code here}

  private class AboutHandler implements ActionListener {  public void actionPerformed(ActionEvent e) {  // Create the aboutDialog when it is requested  if ( aboutDialog == null ) {

aboutDialog = new AboutDialog(frame, "About", true);

  }  aboutDialog.setVisible(true);  }  }

  private class AboutDialog extends JDialog implements ActionListener{  public AboutDialog(Frame parent, String title, boolean modal) {  super(parent,title,modal);

add(new JLabel("The ChatClient is a neat tool that allows you

to talk " +  "to other ChatClients via aChatServer"),BorderLayout.NORTH);  JButton b = new JButton("OK");  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 ChatClientClass

In this task, you compile the ChatClient class.

Page 248: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 248/276

Exercise: Creating theChatClientGUI, Part 3 (Level 3)

Lab 14-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 3 – Running the ChatClientProgram

In this task, you run the ChatClient program. You should see the GUIshown in Figure 14-1 on page L14-2. If your GUI does not look exactly likethe figure, then edit the code to tweak the design to match this figure.

Page 249: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 249/276

Exercise Summary

GUI-Based Applications Lab 14-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 250: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 250/276

Page 251: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 251/276

Lab 15-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 15

Threads

Objectives

Upon completion of this lab, you should be able to create a simplemultithreaded application.

Page 252: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 252/276

Exercise: Using Multithreaded Programming (Level 1)

Lab 15-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise: Using Multithreaded Programming (Level 1)

In this exercise, you become familiar with the concepts of multithreading by writing a multithreaded program.

The purpose of this lab is to create three threads and run them at the sametime. While they are running, they print out their names to the standardoutput stream. By observing what is printed, you can observe how thethreads run and in what order.

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

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: 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 ThreadProject project in theexercises/15_threads directory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/15_threads directory.

Page 253: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 253/276

Exercise: Using Multithreaded Programming (Level 1)

Threads Lab 15-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Creating the PrintMeClass

Complete the following steps:

1. Open the ThreadProject project in the exercises/15_threads

directory.2. Create a PrintMe class in the source package of the

ThreadProject with the following characteristics:

Class Name: PrintMe

Project: ThreadProject

Implements: Runnable

Location: Source Packages

Package: default package

The class implements the Runnable interface. The runmethod of the classperforms the following actions 10 times: Print the name of the currentthread and then sleep for 2 seconds.

Task 2 – Creating the TestThreeThreadsClass

In this task, you create a TestThreeThreads class in the source packageof the ThreadProject with the following characteristics:

Class Name: TestThreeThreadsProject: ThreadProject

Location: Source Packages

Package: default package

The main method of the class creates three threads using the PrintMerunnable class. Give each thread a unique name using the setNamemethod. Start each thread.

Task 3 – Compiling the TestThreeThreadsClass

In this task, you compile the TestThreeThreads class.

Page 254: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 254/276

Exercise: Using Multithreaded Programming (Level 1)

Lab 15-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 4 – Running the TestThreeThreadsProgram

In this task, you run the TestThreeThreads program. You should seeoutput similar to this:

T3 - MoeT2 - CurlyT1 - LarryT1 - LarryT3 - MoeT2 - CurlyT1 - LarryT3 - MoeT2 - CurlyT1 - LarryT3 - Moe

T2 - CurlyT1 - LarryT3 - MoeT2 - CurlyT1 - LarryT3 - MoeT2 - CurlyT1 - LarryT3 - MoeT2 - CurlyT1 - Larry

T3 - MoeT2 - CurlyT1 - LarryT3 - MoeT2 - CurlyT1 - LarryT3 - MoeT2 - Curly

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

?

!

Discussion – Can you explain the behavior of your program?

Page 255: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 255/276

Exercise: Using Multithreaded Programming (Level 2)

Threads Lab 15-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise: Using Multithreaded Programming (Level 2)

In this exercise, you become familiar with the concepts of multithreading by writing a multithreaded program.

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

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: 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 ThreadProject project in theexercises/15_threads directory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/15_threads directory.

Page 256: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 256/276

Exercise: Using Multithreaded Programming (Level 2)

Lab 15-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 1 – Creating the PrintMeClass

Complete the following steps:

1. Open the ThreadProject project in the exercises/15_threads

directory.2. Create the PrintMe class with the following characteristics:

Class Name: PrintMe

Project: ThreadProject

Implements: Runnable

Location: Source Packages

Package: default package

This class must implement the Runnable interface.

3. Create the runmethod to loop the following 10 times: Print the nameof the current thread and then sleep for 2 seconds.

Task 2 – Creating the TestThreeThreadsClass

In this task, you create a TestThreeThreads class in the source packageof the ThreadProject project.

Complete the following steps:

1. Create the TestThreeThreads class with the followingcharacteristics:

Class Name: TestThreeThreads

Project: ThreadProject

Location: Source Packages

Package: default package

2. Create the main method.

a. Create three Thread objects and pass an instance of thePrintMe class to each constructor.

 b. Give each thread a unique name using the setName method.

c. Start each thread.

Page 257: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 257/276

Exercise: Using Multithreaded Programming (Level 2)

Threads Lab 15-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 3 – Compiling the TestThreeThreadsClass

In this task, you compile the TestThreeThreads class.

Task 4 – Running the TestThreeThreadsProgram

In this task, you run the TestThreeThreads program. You should seeoutput similar to that shown in ‘‘Task 4 – Running the TestThreeThreadsProgram’’ on page L15-4.

Page 258: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 258/276

Exercise: Using Multithreaded Programming (Level 3)

Lab 15-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise: Using Multithreaded Programming (Level 3)

In this exercise, you become familiar with the concepts of multithreading by writing a multithreaded program.

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

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: 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 ThreadProject project in theexercises/15_threads directory.

123

Demonstration – The demonstration for this exercise can be found in thedemos/15_threads directory.

Task 1 – Creating the PrintMeClass

Complete the following steps:

1. Open the ThreadProject project in the exercises/15_threadsdirectory.

Page 259: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 259/276

Exercise: Using Multithreaded Programming (Level 3)

Threads Lab 15-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

2. Create the PrintMe class with the following characteristics:

Class Name: PrintMe

Project: ThreadProject

Implements: Runnable

Location: Source Packages

Package: default package

This class must implement the Runnable interface.

class PrintMe implements Runnable {// more code here

}

3. Create the runmethod to loop the following 10 times: Print the nameof the current thread and then sleep for 2 seconds.

public void run() {  for(int x = 0; x < 10; x++) {  System.out.println(Thread.currentThread().getName());  try {

Thread.sleep(2000);  } catch(Exception e) {}  }  }

Task 2 – Creating the TestThreeThreadsClass

In this task, you create a TestThreeThreads class in the source packageof the ThreadProject project.

Complete the following steps:

1. Create the TestThreeThreads class with the followingcharacteristics:

Class Name: TestThreeThreads

Project: ThreadProject

Location: Source Packages

Package: default package

public class TestThreeThreads {// more code here

}

Page 260: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 260/276

Exercise: Using Multithreaded Programming (Level 3)

Lab 15-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

2. Create the main method.

a. Create three Thread objects and pass an instance of thePrintMe class to each constructor.

public static void main(String[] args) {  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");  t3.setName("T3 - Moe");

c. Start each thread.

t1.start();  t2.start();  t3.start();

Task 3 – Compiling the TestThreeThreadsClass

In this task, you compile the TestThreeThreads class.

Task 4 – Running the TestThreeThreadsProgram

In this task, you run the TestThreeThreads program. You should seeoutput similar to that shown in ‘‘Task 4 – Running the TestThreeThreadsProgram’’ on page L15-4.

Page 261: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 261/276

Exercise Summary

Threads Lab 15-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 262: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 262/276

Page 263: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 263/276

Lab 16-1Copyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Lab 16

Networking

Objectives

Upon completion of this lab, you should be able to build a GUI client toconnect to a remote server by using Transmission ControlProtocol/Internet Protocol (TCP/IP).

Page 264: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 264/276

Exercise: Creating a Socket Client (Level 1)

Lab 16-2 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise: Creating a Socket Client (Level 1)

In this exercise, you write the code to connect the chat room client with thechat server.

The chat server is responsible for sending messages received from oneclient to all connected clients (including the original sender). Figure 16-1shows an architecture diagram of several clients attached to the singlechat server. In this scenario, Simon types This is cool! into themessage JTextField component. Simon’s client then prepends his nameSimon: onto the message and sends it to the server over the outputstream (Step 1). The server receives the message and then forwards themessage to each attached client (Steps 2–4); the order of the forwardedmessages is unimportant.

Figure 16-1   The Chat Server Sends Any Message to All Attached Clients

client: PC/Win95

Simonserver 

ChatClient

client: SparcSol9

Debbie

ChatClient

client: PC/WinXP

 Asok

ChatClient

“Simon: This is cool!”1

2

3

4

“Simon: This is cool!”

“Simon: This is cool!”

“Simon: This is cool!”

ChatServer 

Page 265: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 265/276

Exercise: Creating a Socket Client (Level 1)

Networking Lab 16-3Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

The chat client (your application) must be modified to perform two behaviors: It must send the user’s messages to the server, and it mustdisplay the messages it receives from the server to the output JTextAreacomponent. Figure 16-2 shows a detailed design for the elements of theChatClient application. You will add the doConnect method to the

ChatClient class to initiate the socket connection to the chat server.

Figure 16-2   Detailed Design of the ChatClient Application

This exercise contains the following sections:

●   “Task 1 – Modifying the ChatClient Class”

●   “Task 2 – Compiling the ChatClient Class”

●   “Task 3 – Running the ChatRoomPrj Project”

RemoteReader

Runnable

+run():void

«interface»

-serverIn : BufferedReader

-doConnect():void

ChatClient

«methods»

-serverOut : PrintWriter

The RemoteReader is a nested classthat reads messages from the serverIninstance variable in the ChatClient.

SendHandler

+actionPerformed(e:ActionEvent):void

«methods»

The SendHandler is a nested classthat sends messages to the serverOutinstance variable in the ChatClient.

server 

ChatServer 

Page 266: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 266/276

Exercise: Creating a Socket Client (Level 1)

Lab 16-4 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Preparation

There is no preparation for this exercise.

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/16_network directory.

Task 1 – Modifying the ChatClientClass

In this task, you modify the ChatClient class in the source package of the

ChatRoomPrj project. Implement the client-server communication basedon the detailed design in Figure 16-2 on page L16-3.

Task 2 – Compiling the ChatClientClass

In this task, you compile the ChatClient class.

Task 3 – Running the ChatRoomPrjProject

Complete the following steps:

1. Set the main class of the ChatRoomPrj project to ChatClient.

Tool Reference – Java Development: Java Application Projects: SettingVM Options

2. Set the following system properties to the ChatRoomPrj project:

Page 267: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 267/276

Exercise: Creating a Socket Client (Level 1)

Networking Lab 16-5Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

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 outputtext area will display a message from the server with a secretpassphrase. When you send that passphrase to the server, you thentrigger an event on the server that plays a gong. This event willindicate that your application is working correctly.

Good luck and have fun!

Page 268: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 268/276

Exercise: Creating a Socket Client (Level 2)

Lab 16-6 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise: Creating a Socket Client (Level 2)

In this exercise, you write the code to connect the chat room client with thechat server.

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

There is no preparation for this exercise.

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/16_network directory.

Task 1 – Modifying the ChatClientClass

In this task, you modify the ChatClient class in the source package of theChatRoomPrj project. Implement the client-server communication basedon the detailed design in Figure 16-2 on page L16-3.

Complete the following steps:

1. Import the java.net and java.io packages.

Page 269: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 269/276

Exercise: Creating a Socket Client (Level 2)

Networking Lab 16-7Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

2. Add instance variables to hold the input and output streams for thesocket connection. You might need additional instance variables,depending on your implementation.

3. Add the doConnectmethod to initiate the TCP/IP socket connectionto 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.

4. Modify the launchFrame method to call the doConnect method.

5. Modify the SendHandler nested class to send the message text (andthe user name) to the socket output stream. Delete the code thatdisplayed the message to the output text area.

6. Create the RemoteReadernested class that implements the Runnableinterface. The run method must read a line at a time from the socketinput stream in an infinite loop.

Task 2 – Compiling the ChatClientClass

In this task, you compile the ChatClient class.

Task 3 – Running the ChatRoomPrjProject

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

Page 270: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 270/276

Exercise: Creating a Socket Client (Level 2)

Lab 16-8 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

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

3. Run the ChatRoomPrj project.

If your program connects to the server successfully, then the output

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

Good luck and have fun!

Page 271: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 271/276

Exercise: Creating a Socket Client (Level 3)

Networking Lab 16-9Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise: Creating a Socket Client (Level 3)

In this exercise, you will write the code to connect the chat room client withthe chat server.

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

There is no preparation for this exercise.

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

123

Demonstration – The demonstration for this exercise can be found in thedemos/16_network directory.

Task 1 – Modifying the ChatClientClass

In this task, you modify the ChatClient class in the source package of theChatRoomPrj project. Implement the client-server communication basedon the detailed design in Figure 16-2 on page L16-3.

Page 272: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 272/276

Exercise: Creating a Socket Client (Level 3)

Lab 16-10 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Complete the following steps:

1. Import the java.net and java.io packages.

import java.net.*;import java.io.*;

2. Add instance variables to hold the input and output streams for thesocket connection. You might need additional instance variables,depending on your implementation.

public class ChatClient {// existing code hereprivate Socket connection = null;

  private BufferedReader serverIn = null;  private PrintStream serverOut = null;// existing code here

}

3. Add the doConnectmethod to initiate the TCP/IP socket connectionto the server. Ask your instructor for the hostname (or IP address)and port number of the server application.

private void doConnect() {

a. Initialize server IP and port information.

// Initialize server IP and port information  String serverIP = System.getProperty("serverIP", "127.0.0.1");  String serverPort = System.getProperty("serverPort", "2000");

Note – You could have hard coded the server IP address and port numberin the Socket constructor call below. The code for this step demonstrateshow to make these values dynamic at runtime. The system properties,serverIP and serverPort, can be assigned on the java command usingthe -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.

Page 273: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 273/276

Exercise: Creating a Socket Client (Level 3)

Networking Lab 16-11Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

serverOut = new PrintStream(connection.getOutputStream());

e. Launch the reader thread.

Thread t = new Thread(new RemoteReader());  t.start();

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 heredoConnect();

}5. Modify the SendHandler nested class to send the message text (and

the user name) to the socket output stream. Delete the code thatdisplayed the message to the output text area.

private class SendHandler implements ActionListener {  public void actionPerformed(ActionEvent e) {  String text = input.getText();  text = usernames.getSelectedItem() + ": " + text + "\n";

serverOut.print(text);  input.setText("");

  } // END of actionPerformed method  } // END of SendHandler nested class

6. Create the RemoteReadernested class that implements the Runnableinterface. The run method must read a line at a time from the socketinput 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

Page 274: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 274/276

Exercise: Creating a Socket Client (Level 3)

Lab 16-12 Java™ Programming LanguageCopyright 2008Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Task 2 – Compiling the ChatClientClass

In this task, you compile the ChatClient class.

Task 3 – Running the ChatRoomPrjProject

Complete the following steps:

1. Set the main class of the ChatRoomPrj project to ChatClient.

Tool Reference – Java Development: Java Application Projects: SettingVM Options

2. Set the following system properties to the ChatRoomPrj project:

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

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 outputtext area will display a message from the server with a secretpassphrase. When you send that pass phrase to the server, you thentrigger an event on the server that plays a gong. This event will

indicate that your application is working correctly.

Good luck and have fun!

Page 275: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 275/276

Exercise Summary

Networking Lab 16-13Copyright2008 Sun Microsystems, Inc.All Rights Reserved. Sun Services, RevisionG.2

Exercise Summary

?

!

Discussion – Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercise.

●   Experiences

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Interpretations

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Conclusions

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

●   Applications

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Page 276: Material de Oracle para certificación Java

7/18/2019 Material de Oracle para certificación Java

http://slidepdf.com/reader/full/material-de-oracle-para-certificacion-java 276/276