110
IBM Enterprise IT and Asset Management 7.1: Java for Customization Student Exercises S150-3086-00 May 2009

Ibm enterprise it and asset management 7.1 java for customization exercise

  • Upload
    hal-izi

  • View
    300

  • Download
    2

Embed Size (px)

DESCRIPTION

java training

Citation preview

Page 1: Ibm enterprise it and asset management 7.1 java for customization exercise

IBM Enterprise IT and Asset Management 7.1: Java for CustomizationStudent ExercisesS150-3086-00

May 2009

Page 2: Ibm enterprise it and asset management 7.1 java for customization exercise

Copyright NoticeCopyright © 2009 IBM Corporation, including this documentation and all software. All rights reserved. May only be used pursuant to a Tivoli Systems Software License Agreement, an IBM Soft-ware License Agreement, or Addendum for Tivoli Products to IBM Customer or License Agreement. No part of this publication may be reproduced, transmitted, transcribed, stored in a retrieval system, or translated into any computer language, in any form or by any means, electronic, mechanical, magnetic, optical, chemical, manual, or otherwise, without prior written permission of IBM Corpora-tion. IBM Corporation grants you limited permission to make hardcopy or other reproductions of any machine-readable documentation for your own use, provided that each such reproduction shall carry the IBM Corporation copyright notice. No other rights under copyright are granted without prior writ-ten permission of IBM Corporation. The document is not intended for production and is furnished “as is” without warranty of any kind. All warranties on this document are hereby disclaimed, including the warranties of merchantability and fitness for a particular purpose.Note to U.S. Government Users—Documentation related to restricted rights—Use, duplication or disclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corporation.

TrademarksThe following are trademarks of IBM Corporation or Tivoli Systems Inc.: IBM, Tivoli, AIX, Cross-Site, NetView, OS/2, Planet Tivoli, RS/6000, Tivoli Certified, Tivoli Enterprise, Tivoli Ready, TME. In Den-mark, Tivoli is a trademark licensed from Kjøbenhavns Sommer - Tivoli A/S.Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both.UNIX is a registered trademark of The Open Group in the United States and other countries.C-bus is a trademark of Corollary, Inc. in the United States, other countries, or both.Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.Lotus is a registered trademark of Lotus Development Corporation.PC Direct is a trademark of Ziff Communications Company in the United States, other countries, or both and is used by IBM Corporation under license.ActionMedia, LANDesk, MMX, Pentium, and ProShare are trademarks of Intel Corporation in the United States, other countries, or both.SET and the SET Logo are trademarks owned by SET Secure Electronic Transaction LLC. For fur-ther information, see http://www.setco.org/aboutmark.html.Other company, product, and service names may be trademarks or service marks of others.

NoticesReferences in this publication to Tivoli Systems or IBM products, programs, or services do not imply that they will be available in all countries in which Tivoli Systems or IBM operates. Any reference to these products, programs, or services is not intended to imply that only Tivoli Systems or IBM prod-ucts, programs, or services can be used. Subject to valid intellectual property or other legally pro-tectable right of Tivoli Systems or IBM, any functionally equivalent product, program, or service can be used instead of the referenced product, program, or service. The evaluation and verification of operation in conjunction with other products, except those expressly designated by Tivoli Systems or IBM, are the responsibility of the user. Tivoli Systems or IBM may have patents or pending patent applications covering subject matter in this document. The furnishing of this document does not give you any license to these patents. You can send license inquiries, in writing, to the IBM Director of Licensing, IBM Corporation, North Castle Drive, Armonk, New York 10504-1785, U.S.A.Printed in Ireland.

Page 3: Ibm enterprise it and asset management 7.1 java for customization exercise

• • • ••

I

Table of Contents

Student Exercises for Unit 1 No student exercises are provided for this unit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1

Student Exercises for Unit 2 Exercise 1: Create a Java Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1Exercise 2: Create the HelloWorld Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3Exercise 3: Eclipse Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6Exercise 4: Write the HelloWorld class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7Exercise 5: Build the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7Exercise 6: Run the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8

Student Exercises for Unit 3 Exercise 1: Calculate an Average . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1Exercise 2: Determine a Maximum or Minimum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3Exercise 3: Create the WestToEast Class (Optional) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5Exercise 4: Debug the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7

Student Exercises for Unit 4 Exercise 1: Create the ModAdd Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1Exercise 2: Debug the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3

Student Exercises for Unit 5 Exercise 1: Create the ReverseArgs Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1Exercise 2: Create the Calculator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2Exercise 3: Create the Util Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4Exercise 4: Create the Perform Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5

Student Exercises for Unit 6 Exercise 1: Implement Exception Handing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1Exercise 2: Read and Write to Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1

Student Exercises for Unit 7 Exercise 1: Using an Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-1Exercise 2: Using an Interface and Abstract Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2

Student Exercises for Unit 8 Exercise 1: Determine a Median . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1Exercise 2: Use a LinkedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1Exercise 3: Use an ArrayList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3

Page 4: Ibm enterprise it and asset management 7.1 java for customization exercise

II IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Table of Contents

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Exercise 4: Create a Deck of Cards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3Exercise 5: Create a Hospital . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-5

Student Exercises for Unit 9 Exercise 1: The Producer–Consumer Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-1

Student Exercises for Unit 10 Exercise 1: Create a Serializable Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-1Exercise 2: Serialize an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-1Exercise 3: Deserialize an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2Exercise 4: Using RMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2

Appendix A: Exercise Solutions Unit 1 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1No solutions are provided. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1

Unit 2 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1Unit 3 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2Exercise 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-3

Unit 4 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-4Unit 5 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-5Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-5Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-6Exercise 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-7Exercise 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-8

Unit 6 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-10Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-10Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-11

Unit 7 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-13Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-13Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-14

Unit 8 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-21Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-21Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-22Exercise 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-23Exercise 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-24Exercise 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-26

Unit 9 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-34Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-34

Unit 10 Exercise Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-36Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-36Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-37Exercise 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-38Exercise 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-39

Page 5: Ibm enterprise it and asset management 7.1 java for customization exercise

• • • ••

1-1

Student Exercises for Unit 1

No student exercises are provided for this unit.

Page 6: Ibm enterprise it and asset management 7.1 java for customization exercise

1-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 1

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Page 7: Ibm enterprise it and asset management 7.1 java for customization exercise

• • • ••

2-1

Student Exercises for Unit 2

Exercise 1: Create a Java Project

In this exercise, you will create a Java project that points to the JavaBasics directory. This root directory will contain your source code. Your compiled code will also remain in this directory.

___ 1. Open the Eclipse IDE, if it is not already open.

___ 2. Select the New option or navigate to File > New in the main menu.

___ 3. Select Project.

Page 8: Ibm enterprise it and asset management 7.1 java for customization exercise

2-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 2Exercise 1: Create a Java Project

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 4. Select Java Project and click Next.

___ 5. In the Project name field, type JavaBasics.

___ 6. Select Create project from existing source.

___ 7. Browse for the directory C:\JavaBasics.

Page 9: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 2-3

• • •••

Student Exercises for Unit 2Exercise 2: Create the HelloWorld Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 8. Click Finish.

___ 9. The project named JavaBasics is created and can be accessed from the Package Explorer tab. Expand the project. It is set up with the necessary JRE and .jar files.

Exercise 2: Create the HelloWorld Class

In this exercise you will use the Eclipse IDE to create the HelloWorld class. The HelloWorld class will contain only a main() method with a statement to display the text Hello World! and I am here! to the console.

The HelloWorld class will belong to the exercises.hello package.

The following examples show two possible outlines for the HelloWorld class.

Page 10: Ibm enterprise it and asset management 7.1 java for customization exercise

2-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 2Exercise 2: Create the HelloWorld Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

package exercises.hello;

public class HelloWorld { public static void main(String[] args) { // Display "Hello World! I am here!" to the console }}

// The following is an alternative outline:

package exercises.hello;

public class HelloWorld { public static void main(String[] args) { printHelloWorld(); }

public static void printHelloWorld() { // Display "Hello World! I am here!" to the console }}

___ 1. Click the New drop-down menu, and select Class, or File > New > Class from the main menu to access the New Java Class dialog box.

___ 2. Enter exercises.hello in the Package field.

___ 3. Enter HelloWorld in the Name field.

___ 4. Click the public static void main(String[] args) check box to select it.

Your screen should look like the following example.

Page 11: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 2-5

• • •••

Student Exercises for Unit 2Exercise 2: Create the HelloWorld Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 5. Click Finish.

___ 6. The class file HelloWorld.java is created. The file is listed in the Package Explorer. A skeleton class with main() has been generated and is in the edit window.

Page 12: Ibm enterprise it and asset management 7.1 java for customization exercise

2-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 2Exercise 3: Eclipse Features

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 7. Double-click the HelloWorld.java tab to expand the edit window. Double-click the same tab to toggle back to the package view.

Exercise 3: Eclipse Features

___ 1. Eclipse contains context-sensitive help. To demonstrate this feature, try writing a line of code inside the main() method, such as System.out. After typing System.out, press Ctrl+Space for context-sensitive help.

Page 13: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 2-7

• • •••

Student Exercises for Unit 2Exercise 4: Write the HelloWorld class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 2. Complete a line of code and omit the semicolon on purpose. Eclipse will detect that a missing semicolon is a syntax error, and that line of code will be flagged with a red error symbol.

.

___ 3. Mistype more lines of code to demonstrate some helpful features of Eclipse.

Exercise 4: Write the HelloWorld class

___ 1. Write the HelloWorld class according to the outline illustrated in Exercise 2.

___ 2. Use the System.out.println() method to output text to the console.

___ 3. Save the file.

Exercise 5: Build the Project

___ 1. Right-click the JavaBasics project and select Build Project.

___ 2. If the Project > Build Automatically option is selected, clear the option.

___ 3. After the project is built, the errors are displayed on the Problems tab. Double-click any error. The cursor is placed on the error line.

___ 4. After you fix the error, rebuild the project.

Page 14: Ibm enterprise it and asset management 7.1 java for customization exercise

2-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 2Exercise 6: Run the Application

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Exercise 6: Run the Application

___ 1. Ensure that there are no compile errors after building the project.

___ 2. To run the application, select the HelloWorld.java file on the Package Explorer tab. The file must have a main() to run.

___ 3. Navigate to Run > Run Configurations from the main menu.

___ 4. In the dialog box, select Java Application from the list.

___ 5. Click the New launch configuration icon to create a HelloWorld configuration. The configuration includes the path to the main class.

___ 6. Click Apply.

___ 7. Click Run. Output is sent to the console.

___ 8. Select the Console tab to view the application output.

Page 15: Ibm enterprise it and asset management 7.1 java for customization exercise

• • • ••

3-1

Student Exercises for Unit 3

Exercise 1: Calculate an Average

In this exercise you will write a class to calculate the average of a variable number of arguments.

The average of a set of numeric values is determined by adding all of the values together and dividing the calculated sum by the number of values. For example, the average of 10, 4, 8, 6, 5, 10, and 13 is 8:

(10+4+8+6+5+10+13)/7 = 56/7 = 8

The class must include a main() method. Within the body of the main() method, convert each argument to a numeric data type, calculate the average, and output the result.

___ 1. Select File > New > Package to create the exercises.calc package using the Eclipse IDE.

___ 2. Select the exercises.calc package and right-click to access the context menu.

___ 3. Select New > Class from the context menu and create the Average class. Select the option to include a main() method when creating your class.

___ 4. Within the main() method, write the code to calculate an average of the program arguments.

– The program arguments are stored in the variable args, which is an array of Strings.

– The variable args[0] returns the first argument, args[1] returns the second argument, and so on.

– The variable args.length returns an integer value that represents the number of arguments.

– Use the static method Double.parseDouble(String s) to convert an argument from a String data type to a numeric value.

– The following example shows one possible way to iterate through the arguments: for (String v : args) { System.out.print(v + “ “);}System.out.println();

Page 16: Ibm enterprise it and asset management 7.1 java for customization exercise

3-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 3Exercise 1: Calculate an Average

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 5. Use the System.out.println() method to output the calculated average.

___ 6. Save and compile the Average class.

___ 7. Select the Average file in the Package Explorer. Click Run > Run Configurations from the main menu.

___ 8. Create a new launch configuration.

___ 9. Select the Arguments tab.

___ 10. Type numeric arguments separated by white space to test the class.

Page 17: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 3-3

• • •••

Student Exercises for Unit 3Exercise 2: Determine a Maximum or Minimum

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 11. Run the Average class and verify the results.

Exercise 2: Determine a Maximum or Minimum

In this exercise you will write a class to determine the maximum or minimum of two numeric values.

The class should include a main() method. You will provide three arguments. The first argument is max or min. The second and third arguments are numeric values.

If the first argument is max, print the greater of the numeric arguments to the console. If the first argument is min, print the lesser of the numeric arguments to the console.

___ 1. Right-click the exercises.calc package.

___ 2. Select New > Class from the context menu and create the MaxOrMin class. Select the option to include a main( ) method when creating your class.

___ 3. Within the main() method, write the code to print either the maximum or minimum of the numeric values given as program arguments.

The program arguments are stored in the variable args, which is an array of Strings.

The variable args[0] returns the first argument, args[1] returns the second argument, and so on.

Page 18: Ibm enterprise it and asset management 7.1 java for customization exercise

3-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 3Exercise 2: Determine a Maximum or Minimum

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Hint: The following methods are useful for the exercise:

– Double.parseDouble(String s)

– The equalsIgnoreCase(String s) method from the String class

– The static Math.max() and Math.min( ) methods

___ 4. Use the System.out.println() method to output the maximum or minimum value.

___ 5. Save and compile the MaxOrMin class.

___ 6. Select the MaxOrMin file in the Package Explorer. From the main menu, select Run > Run Configurations.

___ 7. Create a new launch configuration.

___ 8. Select the Arguments tab.

___ 9. Type max or min and two numeric arguments separated by white space to test the class.

Page 19: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 3-5

• • •••

Student Exercises for Unit 3Exercise 3: Create the WestToEast Class (Optional)

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 10. Run the MaxOrMin class and verify the results.

Exercise 3: Create the WestToEast Class (Optional)

Coordinated Universal Time (UTC) is a time standard roughly equivalent to Greenwich Mean Time (GMT). Conversion between time zones is such that the following relationship is true and each side of the equation is equivalent to UTC:

Time in Zone A − UTC Offset for Zone A = Time in Zone B − UTC Offset for Zone B

The equation can be rewritten as:

Time in Zone B = Time in Zone A − UTC Offset for Zone A + UTC Offset for Zone B

Use the following equation to determine what time it is in Los Angeles (UTC offset = −08) when it is 8:30 a.m. in New York City (UTC offset = -5):

Time in Los Angeles = 08:30 − (−05:00) + (−08:00) = 05:30

This exercise demonstrates a class that uses the classes in Java API, and it has enough content for you to try the Eclipse debugging features. An outline for the class WestToEast is partially provided for you. The program imports four Java classes that include data and time functionality. Statements have been provided in the program; you can uncomment them and inspect the output for guidance.

If you have previous Java or other object-oriented programming experience, try to complete the exercise without using the solution. Otherwise, the solution is provided in the Appendix.

Page 20: Ibm enterprise it and asset management 7.1 java for customization exercise

3-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 3Exercise 3: Create the WestToEast Class (Optional)

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

The following example shows a possible outline for the WestToEast class:

package exercises.time;

import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.SimpleTimeZone;

public class WestToEast {

public static void main(String[] args) {

// Base GMT offset: -8:00 SimpleTimeZone zone1 = new SimpleTimeZone(-8 * 60 * 60 * 1000, "America/Los_Angeles"); // Base GMT offset: -5:00 SimpleTimeZone zone2 = new SimpleTimeZone(-5 * 60 * 60 * 1000, "America/New_York");

// Create two GregorianCalendar objects // with the East and West Coast // time zone and the current date and time Calendar calendar1 = new GregorianCalendar(zone1); Calendar calendar2 = new GregorianCalendar(zone2); Date time = new Date(); // Get current Date/Time calendar1.setTime(time); calendar2.setTime(time);

// System.out.println("Hour: " // + calendar1.get(Calendar.HOUR)); // System.out.println("Minute: " // + calendar1.get(Calendar.MINUTE));

// insert your code to calculate the East Coast time // using the calendar1.get(Calendar.HOUR) and // calendar1.get(Calendar.MINUTE) values

// print out the East Coast value to the console

}}

___ 1. Create the WestToEast class in the exercises.time package using the Eclipse IDE.

___ 2. Copy the provided file or the code outline that precedes this exercise.

___ 3. Complete the class following the specifications as outlined.

___ 4. Create variables and use the Calendar.HOUR and Calendar.MINUTE values to calculate the time in New York City, given the time in Los Angeles.

Page 21: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 3-7

• • •••

Student Exercises for Unit 3Exercise 4: Debug the Application

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 5. Use the System.out.println() method to output the calculated value.

___ 6. Save and compile the WestToEast class.

___ 7. Select the WestToEast file in the Package Explorer. From the main menu, select Run > Run Configurations.

___ 8. Run the WestToEast application and verify the results.

Exercise 4: Debug the Application

___ 1. Select the WestToEast class in the Package Explorer.

___ 2. Select Run > Debug Configurations from the main menu.

___ 3. In the dialog box, the WestToEast class is already displayed in the Java Application list.

___ 4. Return to the Main tab, if necessary.

___ 5. Select the Stop in main option.

___ 6. Click Apply.

___ 7. Click Debug.

___ 8. Click Yes if the Confirm Perspective Switch message box is displayed.

___ 9. Eclipse opens the Debug perspective. Debug icons are available within this perspective, in addition to a Variable tab to inspect variable values and a Breakpoint tab. This debug session has stopped the program at the first statement in main().

Page 22: Ibm enterprise it and asset management 7.1 java for customization exercise

3-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 3Exercise 4: Debug the Application

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Familiarize yourself with the available debug icons on the Debug tab. Commonly used icons are:

– Resume: Continue to the next breakpoint.

– Step Into: Step into the method that is called.

– Step Over: Execute current statement and move to the next statement.

– Step Return: Perform remaining statements in method and return to calling method.

– Terminate: Halt the execution of the program.

___ 10. Right-click the outer edge of the WestToEast file and select Toggle Breakpoint to set a breakpoint at a line of code in that file. Breakpoints suspend execution of the program.

___ 11. Switch back to the Java perspective by clicking the Java tab (or navigate to Window > Open Perspective > Java). Open the WestToEast file, if it is not already open.

___ 12. Right-click the outer edge of the WestToEast file and select Toggle Breakpoint to set a breakpoint at a line of code in that file. You can set breakpoints in either the Debug or the Java perspective.

___ 13. Set breakpoints and step through the code using Resume, Step Into, Step Over, and Step Return to familiarize yourself with the debug features.

Page 23: Ibm enterprise it and asset management 7.1 java for customization exercise

• • • ••

4-1

Student Exercises for Unit 4

Exercise 1: Create the ModAdd Class

This exercise involves creating a class named ModAdd that belongs to the package exercises.odd.

• The class ModAdd will receive two numeric arguments.

• Calculate the sum of the odd numbers that are multiples of 3 between those two arguments, including the arguments that define the numeric limits for the calculation.

• Calculate the sum with a for loop and a while loop.

• Use the modulus operator to determine if a number is a multiple of 3 or is an odd number.

– A number is a multiple of 3 if num%3 equals zero.

– A number is a multiple of 2 if num%2 equals zero.

The following example shows a possible outline for the ModAdd class:

package exercises.odd;

public class ModAdd { // main program receives 2 arguments

public static void main(String[] args) { // Check if arguments are given // If not, print error msg and System.exit(1); // // Get arguments and check if valid // Calculate sum using for loop and print total // Calculate sum using while loop and print total //

}

Page 24: Ibm enterprise it and asset management 7.1 java for customization exercise

4-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 4Exercise 1: Create the ModAdd Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 1. Create the ModAdd class using the Eclipse IDE.

___ 2. Write the ModAdd class following the specifications as outlined previously.

___ 3. Save and compile the ModAdd class.

___ 4. The following table contains some example calculations.

Range Odd Numbers that Are Multiples of 3 Calculated Sum

1 to 10 3,9 12

3 to 21 3,9,15,21 48

20 to 50 21,27,33,39,45 165

1 to 100 3,9,21,27,33,39,45,51,57,63,69....... 867

Page 25: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 4-3

• • •••

Student Exercises for Unit 4Exercise 2: Debug the Application

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 5. Select the ModAdd file in the Package Explorer. Click Run > Run Configurations from the main menu.

___ 6. Select the Arguments tab and type program arguments.

___ 7. Run the ModAdd application and verify the results.

Exercise 2: Debug the Application

___ 1. Select the ModAdd class in the Package Explorer.

___ 2. Select Run > Debug Configurations from the main menu.

In the dialog box, the ModAdd is already displayed in the Java Application list.

___ 3. Select the Arguments tab if you want to type a different numeric range for the Program arguments. Click Apply.

___ 4. Return to the Main tab.

___ 5. Select the Stop in main option.

___ 6. Click Apply.

___ 7. Click Debug.

___ 8. Click Yes if the Confirm Perspective Switch message box is displayed.

___ 9. Eclipse opens the Debug perspective. Debug icons are available within this perspective, in addition to a Variable tab to inspect variable values and a Breakpoint tab. This debug session has stopped the program at the first statement in main().

Page 26: Ibm enterprise it and asset management 7.1 java for customization exercise

4-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 4Exercise 2: Debug the Application

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 10. Right-click the outer edge of the ModAdd file and select Toggle Breakpoint to set a breakpoint at a line of code in that file.

___ 11. Switch back to the Java perspective by clicking the Java tab (or click Window > Open Perspective > Java). Open the ModAdd file, if it is not already open.

___ 12. You can set breakpoints in either the Debug or the Java perspective. Set breakpoints and step through the code using Resume, Step Into, Step Over, and Step Return.

Page 27: Ibm enterprise it and asset management 7.1 java for customization exercise

• • • ••

5-1

Student Exercises for Unit 5

Exercise 1: Create the ReverseArgs Class

This exercise involves creating a class named ReverseArgs that belongs to the package exercises.str. You will print out the argument list in reverse.

• The ReverseArgs class will receive two or more arguments.

• The ReverseArgs class will contain a method to reverse the arguments letter by letter.

• The ReverseArgs class will contain a method to reverse the arguments word by word.

The following example shows a possible outline for the ReverseArgs class:

package examples.str;

public class ReverseArgs {

public static void main(String args[]){

if(args.length < 2) { // print usage statement return; }

StringBuilder strArguments = new StringBuilder(); // Build a string using the args[]

reverseArguments(strArguments); System.out.println ("strArguments = " + strArguments);

// return strArguments to its original state reverseArguments(strArguments); System.out.println ("strArguments = " + strArguments);

reverseWords(strArguments); System.out.println ("strArguments = " + strArguments); }

Page 28: Ibm enterprise it and asset management 7.1 java for customization exercise

5-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 5Exercise 2: Create the Calculator Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

public static StringBuilder reverseArguments(StringBuilder s) { // reverse the argument list, letter by letter // Use reverse() to reverse a string return s; }

public static StringBuilder reverseWords(StringBuilder s) { // reverse the argument list word by word return s; }

}

___ 1. Create the ReverseArgs class using the Eclipse IDE.

___ 2. Write the ReverseArgs class following the specifications as outlined in the preceding example.

___ 3. Save and compile the ReverseArgs class.

___ 4. Verify the results.

Exercise 2: Create the Calculator Class

This exercise involves creating a class named Calculator that belongs to the package exercises.calc.

• The class Calculator will receive three arguments: an operator and two operands.

• Calculate the result of the operator and the operands.

• The operator is not case-sensitive, and requires only the portion shown in bold in the preceding table to be a valid operator.

Operator Operands

add operand1 + operand 2

subtract operand1 - operand 2

multiply operand1 * operand 2

divide operand1 / operand 2

Page 29: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 5-3

• • •••

Student Exercises for Unit 5Exercise 2: Create the Calculator Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Examples of valid command-line arguments are:

Add 77 55sub 3 8Subtract 33 22Multi 1 7DIVIDE 33 12

• The String class methods are useful to find the operation.

The following example shows a possible outline for the Calculator class:

package exercises.calc;

public class Calculator { public void add(double o1, double o2) { }

public void sub(double o1, double o2) { }

public void mult(double o1, double o2) { }

public void div(double o1, double o2) { }

public static void main(String[] args) { // Check if 3 arguments are given // Check if operation and operations are valid // If not, print error msg and System.exit(1); // if(operation is "add") add(op1, op2); else if (operation is "sub") sub(op1, op2); ....

}

___ 1. Create the Calculator class using the Eclipse IDE.

___ 2. Write the Calculator class following the specifications as outlined previously.

___ 3. Save and compile the Calculator class.

___ 4. Verify the results.

Page 30: Ibm enterprise it and asset management 7.1 java for customization exercise

5-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 5Exercise 3: Create the Util Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Exercise 3: Create the Util Class

This exercise involves creating a utility class called Util that contains static methods for the add, subtract, multiply, and divide operations. The class belongs to the exercises.util package.

• Overload the methods for each operation to allow for different data types, such as:

public static int add(int op1, int op2){....}public static double add(double op1, double op2){....}

• Example usage statement:

double result = Util.sub(55.3, 22.1);

The following example shows a possible outline for the Util class:

package exercises.util;

public class Util { public static int add(int o1, int o2) { }

public static double add(double o1, double o2) { }

public static int sub(int o1, int o2) { }

public static double sub(double o1, double o2) { } ....}

___ 1. Create the Util class using the Eclipse IDE.

___ 2. Write the Util class following the specifications as outlined previously.

___ 3. Save and compile the Util class.

___ 4. Verify the results.

Page 31: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 5-5

• • •••

Student Exercises for Unit 5Exercise 4: Create the Perform Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Exercise 4: Create the Perform Class

This exercise involves creating a class named Perform that belongs to the package exercises.calc. The Perform class uses the Util class, which is in a different package.

• The class Perform will receive three arguments: an operator and two operands.

• The operands can be integer or double data types. If one operand is a double data type, both are assumed to be of type double.

The following example shows a possible outline for the Perform class:

public class Perform { public static void main(String[] args) { // Check for arguments

// Convert arguments to numeric variables

String num1; String num2;

// Assign operands arguments to Strings and // Check if operands are int or double // int data type does not have a decimal point // double data type has a decimal point

if (num1.indexOf(".") != -1) // string represents a double else // string represents an integer

// place operands into int or double variables

// call the correct operation with the operands // if the operation is add: Util.add(op1, op2); .... }}

___ 1. Create the Perform class using the Eclipse IDE.

___ 2. Write the Perform class following the specifications as outlined previously.

___ 3. Save and compile the Perform class.

___ 4. Verify the results.

Page 32: Ibm enterprise it and asset management 7.1 java for customization exercise

5-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 5Exercise 4: Create the Perform Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Page 33: Ibm enterprise it and asset management 7.1 java for customization exercise

• • • ••

6-1

Student Exercises for Unit 6

Exercise 1: Implement Exception Handing

This exercise involves making a copy of the Perform.java file, renaming it Do.java, and adding exception handling.

• Throw an exception if parameters are not provided or if the operation is invalid.

• Use try-catch blocks to catch exceptions when parsing arguments.

___ 1. Copy the contents of Perform.java and rename the file and class Do.java.

___ 2. Add exception handling to the class.

___ 3. Save and compile the Do.java file.

___ 4. Verify the results with the cases in the following table.

Exercise 2: Read and Write to Text Files

This exercise involves reading and writing to a text file using the FileReader, BufferedReader, FileWriter, and BufferedWriter classes.

A useful class for this exercise is java.util.Scanner, which can be used for parsing fields from a file. Regular expressions in the String class provide a replacement for the deprecated java.util.StringTokenizer class.

Arguments Expected Result at Runtime

No arguments Invalid case

Add 1.0 two.2 Second operand is not a number

abc 2 3 Invalid operation

Sub 77 22 Valid case

Page 34: Ibm enterprise it and asset management 7.1 java for customization exercise

6-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 6Exercise 2: Read and Write to Text Files

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

• A file containing lines of text, some of which are palindromes, has been provided for you. A palindrome is a sentence or word that reads the same from right to left, or left to right. The classic example is Madam, I’m Adam.

• Your code will examine each line of the text file and determine whether the line of text is a palindrome. If the line is a palindrome, then the line will be written to a new file.

• Handle IOException when necessary.

The following example shows a possible outline for the class:

public class Palindromes {

public static void main(String[] args) throws IOException { if (args.length != 2) { System.out.println("Usage: Must have 2 parameters"); System.exit(1); }

File inFile = new File(args[0]); File outFile = new File(args[1]);

boolean exists = inFile.exists(); if (!exists) { System.out.println("File " + inFile.getName()+ does not exist"); System.exit(1); } try { filter4Palindromes(inFile, outFile1); } catch (IOException e) { System.out.println(e); System.exit(1); } }

public static void filter4Palindromes(File in, File out) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(in)); BufferedWriter writer = new BufferedWriter(new FileWriter(out));

// create Strings and StringBuilder objects // to manipulate lines of text

// loop through the lines of // text while reader.readLine()) != null

Page 35: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 6-3

• • •••

Student Exercises for Unit 6Exercise 2: Read and Write to Text Files

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

// if the line is a palindrome then write // the palindrome to the output file

// close the reader // close the writer }

___ 1. Create the Palindromes class using the Eclipse IDE.

___ 2. Write the Palindromes class following the specifications as shown in the outline.

___ 3. Save and compile the Palindromes class.

___ 4. Verify the results.

Page 36: Ibm enterprise it and asset management 7.1 java for customization exercise

6-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 6Exercise 2: Read and Write to Text Files

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Page 37: Ibm enterprise it and asset management 7.1 java for customization exercise

• • • ••

7-1

Student Exercises for Unit 7

Exercise 1: Using an Interface

This exercise uses an interface to demonstrate polymorphism. It involves creating an interface named HowAreYou and writing three classes that implement that interface. Each class will print “How are you?” in its own language.

• Throw an exception if parameters are not provided or if the operation is invalid.

• Use try-catch blocks to catch exceptions when parsing arguments.

___ 1. Using the Eclipse IDE, create an interface named HowAreYou.java that contains a single method named sayHowAreYou().

___ 2. Create three class files that implement the HowAreYou interface, such as:

– EnglishHowAreYou.java

– ItalianHowAreYou.java

– FrenchHowAreYou.java

___ 3. Each of the three classes must implement the sayHowAreYou() method and print “How are you?” to the console in the appropriate language.

___ 4. Create a class named SayHowAreYou that contains main().

___ 5. The SayHowAreYou class contains an instance of the HowAreYou interface, sets the language to the three different implementing classes, and prints “How are you?” to the console in three different languages.

The following example shows a possible outline for the driver class:

package exercises.HowRU;

public class SayHowAreYou {

public HowAreYou howAreYou;

public void setLanguage(HowAreYou howAreYou) { this.howAreYou = howAreYou; }

Page 38: Ibm enterprise it and asset management 7.1 java for customization exercise

7-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 7Exercise 2: Using an Interface and Abstract Classes

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

public void sayHowAreYou() { this.howAreYou.sayHowAreYou(); }

public static void main(String[] args) { SayHowAreYou howru = new SayHowAreYou();

// set the language to English and print out // the message

// set the language to Italian and print out // the message

// set the language to French and print out // the message

}

}

___ 6. Save and compile the classes.

___ 7. Verify the results.

Exercise 2: Using an Interface and Abstract Classes

This exercise involves writing an interface, abstract classes, and their subclasses. Both inheritance and polymorphism are incorporated into the class design of this exercise.

You will create multiple instrument-type objects; each implements its own play() method. How you choose to override the methods in the class hierarchy will determine which play() method is called.

Page 39: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 7-3

• • •••

Student Exercises for Unit 7Exercise 2: Using an Interface and Abstract Classes

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

The following diagram shows the top-level design specification.

The interface is named Instrument and contains three methods:

• mute()

• play()

• tune()

Four abstract classes implement the Instrument interface:

• BowType

• PluckType

• StrikeType

• WindType

Page 40: Ibm enterprise it and asset management 7.1 java for customization exercise

7-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 7Exercise 2: Using an Interface and Abstract Classes

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

In addition to implementing all of the methods contained in the Instrument interface, each of these classes also includes its own constructor and a getName() method.

Multiple subclasses will extend the abstract classes and override the implementation of the abstract class methods.

Each class will inherit all of the functionality of its superclass. In this case, the abstract classes are the superclasses. The abstract classes contain the methods from the Instrument interface, and any additional methods as outlined in the design illustration.

Page 41: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 7-5

• • •••

Student Exercises for Unit 7Exercise 2: Using an Interface and Abstract Classes

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Next you will create the subclasses. The abstract class BowType has three subclasses:

• Violin

• Viola

• Cello

The abstract class PluckType has two subclasses:

• Guitar

• Bass

The abstract class StrikeType has two subclasses:

• Piano

• Drum

The abstract class WindType has one subclass:

• Saxophone

The complete specification is illustrated on the next page.

Page 42: Ibm enterprise it and asset management 7.1 java for customization exercise

7-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 7Exercise 2: Using an Interface and Abstract Classes

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Page 43: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 7-7

• • •••

Student Exercises for Unit 7Exercise 2: Using an Interface and Abstract Classes

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

After all of the subclasses have been created, you will create a Quartet class that contains four instruments and has at least one method: playMusic().

The Quartet class could be written to contain a createStringQuartet method, creating a string quartet that contains two Violin objects, a Viola object, and a Cello object. Another option is to create a jazz quartet with a Saxophone, Piano, Bass, and Drum object. A third option is a rock quartet with two Guitar objects, a Bass object, and a Drum object.

The driver to verify these classes might be implemented like the following main() method:

package exercises.music;

public class MakeMusic {

public static void main(String[] args) {

Quartet qString = new Quartet(); qString.createStringQuartet(); qString.playMusic();

Quartet qJazz = new Quartet(); qJazz.createJazzQuartet(); qJazz.playMusic();

Quartet qRock = new Quartet(); qRock.createRockQuartet(); qJazz.playMusic();

}

}

Page 44: Ibm enterprise it and asset management 7.1 java for customization exercise

7-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 7Exercise 2: Using an Interface and Abstract Classes

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 1. In the exercises.music package, create an interface named Instrument.java that contains three public methods:

– play()

– tune()

– mute()

___ 2. Create four abstract class files that implement the Instrument interface:

– BowType.java

– PluckType.java

– StrikeType.java

– WindType.java

___ 3. Each of the four classes must implement the methods from the Instrument interface in addition to a constructor and a getName() method. The implementation is to print the name of the corresponding class and method to the console.

___ 4. Create eight subclasses:

– The Violin, Viola, and Cello classes extend the abstract class BowType.

– The Guitar and Bass classes extend the abstract class PluckType.

– The Piano and Drum classes extend the abstract class StrikeType.

– The Saxophone class extends the abstract class WindType.

The implementation for each method in the subclasses is to print the name of the corresponding class and method to the console.

___ 5. Create a Quartet class in the same exercises.music package as the other classes created thus far.

___ 6. Add a collection of four instruments to the Quartet class.You can implement the collection with an array or use a collection class.

___ 7. Implement a playMusic() method that loops through the instruments and calls the play() method of each one.

___ 8. Write a driver class that contains a main() method to test your implementation of the class design.

Page 45: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 7-9

• • •••

Student Exercises for Unit 7Exercise 2: Using an Interface and Abstract Classes

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

The following example shows a possible outline for the driver class:

public class MakeMusic {

public static void main(String[] args) {

Quartet qJazz = new Quartet(); qJazz.createJazzQuartet(); qJazz.playMusic();

}

}

___ 9. Save and compile the classes.

___ 10. Verify the results.

Page 46: Ibm enterprise it and asset management 7.1 java for customization exercise

7-10 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 7Exercise 2: Using an Interface and Abstract Classes

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Page 47: Ibm enterprise it and asset management 7.1 java for customization exercise

• • • ••

8-1

Student Exercises for Unit 8

Exercise 1: Determine a Median

In this exercise you will write a class to determine the median of a variable number of arguments. To find the median value, place the values in order and find the middle value. If there is an even number of values, find the middle pair of values and calculate the average of those two values.

___ 1. Create the new class Median in the exercises.calc package.

___ 2. Within the main() method, write the code to calculate the median of the program arguments.

Hint: The java.util.Arrays.sort() method is useful for this exercise.

___ 3. Save and compile the Median class.

___ 4. Run the Median class and verify the results.

Exercise 2: Use a LinkedList

In this exercise you create a class that implements the LinkedList class and uses the ListIterator to print a list in reverse.

• Throw any necessary IO exceptions.

• Use try-catch blocks to catch exceptions.

Page 48: Ibm enterprise it and asset management 7.1 java for customization exercise

8-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 8Exercise 2: Use a LinkedList

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 1. Create a class named LList.java that contains a main() method.

___ 2. The LList.java class takes one parameter, which is the name of a text file. You can create a text file for testing or use the input file from the Palindrome exercise.

___ 3. Write a fillList() method that:

– Reads the input file

– Adds each line as an element to a LinkedList object

– Uses a ListIterator object to traverse the list in reverse

– Prints each line to the console

___ 4. Create an outline for the LList class. For example:

package exercises.list;

public class LList {

public static void main(String[] args) {

// check for input parameter

File inFile = new File(args[0]);

// Verify that the file exists

try { fillList(inFile); } catch (IOException e) { // handle exception }}

public static void fillList(File in) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(in)); LinkedList<String> lst = new LinkedList<String>(); String line = null;

while ((line=reader.readLine()) != null) { lst.add(line); }

System.out.println("Print list in reverse"); // Use a ListIterator object within a for loop and // print the list in reverse }}

Page 49: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-3

• • •••

Student Exercises for Unit 8Exercise 3: Use an ArrayList

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 5. Save and compile the class.

___ 6. Verify the results.

Exercise 3: Use an ArrayList

In this exercise you create a class that implements the ArrayList class and uses the ListIterator to print a list.

___ 1. Create a copy of the LList class and name the copy AList.java.

___ 2. Rewrite AList.java to use an ArrayList class instead of a LinkedList class to store the lines of text from the input file.

___ 3. Use an iterator in the fillList() method to traverse the collection. Print the contents of the collection in a forward direction and in reverse.

___ 4. Save and compile the class.

___ 5. Verify the results.

Exercise 4: Create a Deck of Cards

In this exercise you will write a class to represent a deck of 52 cards. The class should include the following items:

• A constructor that creates the deck of cards and stores it within an appropriate data structure. The deck of cards should contain a sequence of 13 cards in four suits (spades, clubs, hearts, and diamonds).

• A printDeck() method to print the deck of cards.

• A shuffleDeck() method to shuffle the deck of cards.

• A dealFromTop() method to deal five cards from the top of the deck.

• A dealFromBottom() method to deal five cards from the bottom of the deck.

___ 1. Create the new class Deck in the new exercises.cards package.

Hint: The java.util.Collections.shuffle() method is useful for this exercise.

Page 50: Ibm enterprise it and asset management 7.1 java for customization exercise

8-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 8Exercise 4: Create a Deck of Cards

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 2. Create a driver class called ShuffleNDeal in the exercises.cards package. Within the main() method, the following outline can be used:

public class ShuffleNDeal {

public static void main(String[] args) { Deck deck = new Deck();

deck.printDeck(); deck.shuffleDeck(); deck.dealFromTop(4); deck.dealFromBottom(3); deck.shuffleDeck(); deck.dealFromTop(2); }}

___ 3. Save and compile the Deck and ShuffleNDeal classes.

___ 4. Run the ShuffleNDeal class and verify the results.

Page 51: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-5

• • •••

Student Exercises for Unit 8Exercise 5: Create a Hospital

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Exercise 5: Create a Hospital

This exercise shows you how to coordinate and debug multiple classes that interact with each other. You will incorporate all that you have learned so far and create classes that represent a hospital setting. The hospital setting will be composed of different objects. Use the object design outlined in this exercise or create your own.

• The hospital has:

– Doctors

– Patients

– Labs, such as an X-ray lab and a blood lab

• The doctors can:

– Request tests for their patients, such as an X-ray test and a blood test

– Get test results, such as X-ray test results or blood test results

Page 52: Ibm enterprise it and asset management 7.1 java for customization exercise

8-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 8Exercise 5: Create a Hospital

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

In this exercise, try to use:

– Inheritance (is-a relationship)

– Composition (has-a relationship)

– Abstract classes or interfaces

– Polymorphism

– Subclasses

– Private, protected, and public variables and methods

– Collection classes to store lists

– Exception handling

Lab, MedicalTest, and Result are abstract classes. The Hospital class contains an XRayLab and BloodLab object, in addition to a list of Patient and Doctor objects.

The Patient objects contain a reference to their Doctor. The Doctor objects can request tests and get results for their Patient objects.

Page 53: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-7

• • •••

Student Exercises for Unit 8Exercise 5: Create a Hospital

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

The following illustration outlines 13 classes that represent a hospital setting. Classes and their variables and methods are outlined. This class design can be used to create a possible solution, or you may design your own classes to represent a hospital.

Page 54: Ibm enterprise it and asset management 7.1 java for customization exercise

8-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 8Exercise 5: Create a Hospital

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

The Eclipse IDE offers multiple ways to view a class hierarchy, types, and class members. The previous image contains detailed information regarding the class members.

The following graphic details the class hierarchy, specifically the CountyHospital class, which extends Hospital and contains the main( ) method.

The main() method calls helper methods to populate the hospital with doctors and patients, request tests for the labs, run the tests, and get the results.

This graphic also illustrates that Lab, MedicalTest, and Result are all abstract classes, as denoted by the letter A.

You can use the classes presented in the graphics or produce your own class design to represent a hospital setting.

Remember that the purpose of this exercise is to gain experience writing classes that interact with one other. The classes make requests of other objects, and share data while using the public, private, and protected access modifiers.

___ 1. Create the classes necessary to produce a hospital setting as described in the preceding description.

Page 55: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-9

• • •••

Student Exercises for Unit 8Exercise 5: Create a Hospital

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 2. Save and compile the classes.

___ 3. Add print statements to your code and use the debugger to correct programming and logic errors.

___ 4. Verify the results.

– Are lists of doctors and patients being maintained?

– Are tests objects being processed by the lab objects, and are results generated?

– Are the lab requests being maintained and processed?

While verifying the results, the console output might look something like the following example.

Page 56: Ibm enterprise it and asset management 7.1 java for customization exercise

8-10 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 8Exercise 5: Create a Hospital

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Page 57: Ibm enterprise it and asset management 7.1 java for customization exercise

• • • ••

9-1

Student Exercises for Unit 9

Exercise 1: The Producer–Consumer Classes

Threads that execute in parallel and share common resources must be synchronized at certain points to ensure proper functioning of the system.

In this exercise you add code to a partially completed class. The code you add will synchronize the data shared between the Producer and the Consumer classes so that the two classes can work together.

The Producer-Consumer example is often used to illustrate thread synchronization techniques. The Producer-Consumer classes were written to create a practical example.

The Producer and Consumer classes share a common resource: the SharedData class. The Producer class contains an infinite loop that generates integer values in sequence and places those integer values into the SharedData object. The Consumer class contains an infinite loop that reads the integer values from the SharedData object.

The purpose of this exercise is to synchronize the classes so that consecutive integers are not lost and duplicate integers are not retrieved.

The following example shows the contents of the Producer, Consumer, and SharedData classes:

public class Producer implements Runnable{ SharedData data; int interval; int identifier;

public Producer(SharedData data, int id, int interval) { this.data=data; this.interval=interval; this.identifier=id; }

public void run() { int i; for(i=0; ; i++) { data.put(i); System.out.println("Producer "+ identifier+ ": "+i); try {

Page 58: Ibm enterprise it and asset management 7.1 java for customization exercise

9-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 9Exercise 1: The Producer–Consumer Classes

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Thread.sleep((int) (Math.random()*interval)); } catch (InterruptedException e) {System.out.println("Producer error\n");} } }}

public class Consumer implements Runnable{ SharedData data; int interval; int identifier; public Consumer(SharedData data, int id, int interval) { this.data=data; this.interval=interval; this.identifier=id; } public void run() { for(;;) { System.out.println(" Consumer " + identifier + ": "+data.get()); try {

Thread.sleep((int) (Math.random()*interval)); } catch (InterruptedException e) {System.out.println("Consumer error\n");} } }}

public class SharedData { protected int data;

public void put(int data) { this.data=data; }

public int get() { return this.data; }

The ProducerConsumerDriver class acts as the driver and takes the following parameters:

• ProducerNumber is the number of Producer threads.

• ConsumerNumber is the number of Consumer threads.

• producerPriority is the priority that will be assigned to the Producer thread or threads.

Page 59: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-3

• • •••

Student Exercises for Unit 9Exercise 1: The Producer–Consumer Classes

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

• consumerPriority is the priority that will be assigned to the Consumer thread or threads.

• interval is the sleep() interval in milliseconds between consecutive writes or reads from the Producer and Consumer thread or threads.

public class ProducerConsumerDriver {

public static void main(String[] args) { SharedData data; Thread Producers[]; Thread Consumers[]; int ProducerNumber; int ConsumerNumber; int producerPriority; int consumerPriority; int interval;

if (args.length < 5 ) { // print usage to console return; }

ProducerNumber=Integer.parseInt(args[0]); ConsumerNumber=Integer.parseInt(args[1]); producerPriority = Integer.parseInt(args[2])); consumerPriority = Integer.parseInt(args[3]); interval=Integer.parseInt(args[4]);

data = new SharedData();

Producers = new Thread[ProducerNumber]; Consumers = new Thread[ConsumerNumber];

for(int i=0;i<ProducerNumber;i++){ Producers[i]=new Thread (new Producer(data, i, interval)); Producers[i].setPriority(producerPriority); Producers[i].start(); }

for(int i=0;i<ConsumerNumber;i++) { Consumers[i]=new Thread (new Consumer(data, i, interval)); Consumers[i].setPriority(consumerPriority); Consumers[i].start(); } }}

Execution of the ProducerConsumerDriver class with the argument list 1 1 5 5 10 produces the following output:

Page 60: Ibm enterprise it and asset management 7.1 java for customization exercise

9-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 9Exercise 1: The Producer–Consumer Classes

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Producer 0: 0Producer 0: 1Producer 0: 2Producer 0: 3 Consumer 0: 3 Consumer 0: 3Producer 0: 4 Consumer 0: 4Producer 0: 5Producer 0: 6Producer 0: 7Producer 0: 8 Consumer 0: 8 Consumer 0: 8

The output shows that the Consumer reads duplicate integers. The Producer writes consecutive integers and only the last integer is retrieved by the Consumer. Because the SharedData object is unsynchronized, there is no synchronization between the Producer and the Consumer objects.

You can experiment with different arguments, such as 3 3 5 5 10, and inspect the output from more than one Producer and Consumer thread. Without synchronization, integer values are lost and others are read multiple times.

The Producer and Consumer classes contain infinite loops. You must terminate this program manually in the Eclipse IDE by clicking the Terminate button. The Terminate button is the red icon in the Console window.

To synchronize the SharedData class:

• Include a boolean flag to control data access and indicate when an integer has been produced or consumed.

• Use the synchronized keyword to protect code segments that require mutual exclusion. When methods are synchronized, the locking and waiting is handled by Java. Only one thread at a time can be executing the method.

• Implement the wait() and notifyAll() methods.

• Synchronized threads call wait() and notifyAll() when they have modified something so that the waiting thread can recheck the boolean flag. The waiting thread can wait for a condition to change within a while loop.

while (conditionToProceed != true) { wait(); .....}

___ 1. Use the files provided for the Producer, Consumer, and ProducerConsumerDriver classes.

Page 61: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-5

• • •••

Student Exercises for Unit 9Exercise 1: The Producer–Consumer Classes

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 2. Write a SharedData class that ensures that the shared data is synchronized for concurrent access by multiple threads.

The Producer, Consumer, and ProducerConsumerDriver classes shown in the exercise description should remain unchanged but you must modify the unsynchronized SharedData class.

___ 3. Save and compile the file.

___ 4. Verify your results. For a single Consumer and Producer thread, the output should look like the following image.

The Terminate icon, which you must click to stop the program, is highlighted with a circle in the image.

Page 62: Ibm enterprise it and asset management 7.1 java for customization exercise

9-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 9Exercise 1: The Producer–Consumer Classes

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Page 63: Ibm enterprise it and asset management 7.1 java for customization exercise

• • • ••

10-1

Student Exercises for Unit 10

Exercise 1: Create a Serializable Object

In this exercise you create a class that is serializable and write the object to a text file.

• Throw any necessary IO exceptions.

• Use try-catch blocks to catch exceptions.

___ 1. Create a class named SerialObject.java that belongs to the examples.serial package and implements the Serializable interface.

___ 2. Add variables to the SerialObject class. Try adding a transient variable, a primitive, a collection type of object, or any other type of object. For example:

public class SerialObject implements Serializable {

transient int transValue; int value; String stringValue; ArrayList<String> lst;

___ 3. Write a constructor for the SerialObject class that assigns values to the variables to define their state.

Exercise 2: Serialize an Object

___ 1. Create a class named SerializeDriver.java that belongs to the examples.serial package.

___ 2. Create an instance of SerialObject object and assign values to all of the variables.

___ 3. Populate any collection type of objects in the SerialObject object.

___ 4. Using FileOutputStream and ObjectOutputStream objects, write the state of a SerialObject object to a file.

Page 64: Ibm enterprise it and asset management 7.1 java for customization exercise

10-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 10Exercise 3: Deserialize an Object

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Exercise 3: Deserialize an Object

___ 1. Create a class named DeserializeDriver.java that belongs to the examples.serial package.

___ 2. Create a new instance of SerialObject in the DeserializeDriver class.

___ 3. Include code to read the serialized state of a SerialObject object from a file into the new instance of SerialObject in your DeserializeDriver class.

– Use the file to which the serialized state was written in Exercise 2.

– Use FileInputStream and ObjectInputStream objects to read the file.

___ 4. Save and compile your code.

___ 5. Verify that the SerialObject variable values that were written to a file in Exercise 2 mirror the values that have been read into the new instance of SerialObject in the DeserializeDriver class.

Exercise 4: Using RMI

In this exercise, you will compile files using rmic (RMI compiler) and test the programs.

Examine the four source files that have been provided to understand how they interact with each other:

• Hello.java

• HelloRemote.java

• RMIServer.java

• RMIClient.java

An Ant build runs the rmic in Eclipse. Ant is a build tool distributed by the Apache Software Foundation. A build.xml file supplies the necessary parameters to run the rmic using the Ant Build option.

___ 1. If it does not exist in your project, create a package called exercises.helloRemote. Copy the four .java files and the build.xml file into the package directory.

___ 2. Select the build.xml file.

Page 65: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-3

• • •••

Student Exercises for Unit 10Exercise 4: Using RMI

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 3. Right-click the External Tools icon.

___ 4. Select External Tools Configuration.

___ 5. Create a new launch configuration for the build.xml file.

___ 6. Select Browse Workspace for the Base Directory option. Select the project folder.

Page 66: Ibm enterprise it and asset management 7.1 java for customization exercise

10-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 10Exercise 4: Using RMI

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 7. Click the JRE tab to verify that the correct Java SDK is available for use.

Page 67: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-5

• • •••

Student Exercises for Unit 10Exercise 4: Using RMI

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

___ 8. Click Apply and Run.

___ 9. Verify that the class files were built, including the stub class file.

___ 10. Start the server and the client. If the default port number (1099) is in use, supply another port number as a program argument.

___ 11. Verify the output.

Page 68: Ibm enterprise it and asset management 7.1 java for customization exercise

10-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Student Exercises for Unit 10Exercise 4: Using RMI

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Page 69: Ibm enterprise it and asset management 7.1 java for customization exercise

• • • ••

A-1

Appendix A: Exercise Solutions

Unit 1 Exercise Solutions

No solutions are provided.

Unit 2 Exercise Solutions

//// Solution for HelloWorld Exercise//

package exercises.hello;

public class HelloWorld{ public static void main(String[] args) { System.out.print("Hello World!\n"); System.out.println("I am here!"); }}

Unit 3 Exercise Solutions

Exercise 1

package exercises.calc;

public class Average {

public static void main(String[] args) { if (args.length == 0) { System.out.println("No arguments to compute average"); return; }

Page 70: Ibm enterprise it and asset management 7.1 java for customization exercise

A-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 3 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

double total = 0; double value = 0;

/* for(String v: args) { value = Double.parseDouble(v); total += value; System.out.println("Added " + value + " to the total"); }

System.out.println("The sum of the arguments equals = " + total); double average = total/args.length; System.out.println("Calculated average is: " + average);*/

for (int i=0; i<args.length; ++i) { value = Double.parseDouble(args[i]); total += value; System.out.println("Added " + value + " to the total"); }

System.out.println("The sum of the arguments equals = " + total); double average = total/args.length; System.out.println("Calculated average is: " + average);

}}

Exercise 2

package exercises.calc;

public class MaxOrMin {

public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: max|min number number"); return; }

System.out.print("Program arguments: "); for (String v:args) System.out.print(v + " "); System.out.println();

double value1 = Double.parseDouble(args[1]); double value2 = Double.parseDouble(args[2]);

if (value1==value2) { System.out.println("The values are equal."); } else if (args[0].equalsIgnoreCase("max")) { System.out.println("The maximum value is: " +

Page 71: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-3

• • •••

Appendix A: Exercise SolutionsUnit 3 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Math.max(value1,value2)); } else if (args[0].equalsIgnoreCase("min")) {

System.out.println("The minimum value is: " + Math.min(value1,value2));

} else System.out.println("Invalid argument"); }}

Exercise 3

// Solution for WestToEast Exercise

package exercises.time;

import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.SimpleTimeZone;

public class WestToEast {

public static void main(String[] args) {

// Base GMT offset: -8:00 SimpleTimeZone zone1 = new SimpleTimeZone(-8 * 60 * 60 * 1000,

"America/Los_Angeles"); // Base GMT offset: -5:00 SimpleTimeZone zone2 = new SimpleTimeZone(-5 * 60 * 60 * 1000,

"America/New_York");

// Define time period for daylight savings time zone1.setStartRule(Calendar.MARCH, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); zone1.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); zone2.setStartRule(Calendar.MARCH, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); zone2.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);

// Create two GregorianCalendar objects with the East and West // Coast time zone and the current date and time Calendar calendar1 = new GregorianCalendar(zone1); Calendar calendar2 = new GregorianCalendar(zone2);

Date time = new Date(); // Get current Date/Time calendar1.setTime(time); // convert current date/time to West // Coast time zone

Page 72: Ibm enterprise it and asset management 7.1 java for customization exercise

A-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 4 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

calendar2.setTime(time); // convert current date/time to East // Coast time zone // System.out.println("West Coast time: " + calendar1.get(Calendar.HOUR) + ":" + calendar1.get(Calendar.MINUTE));// System.out.println("East Coast time: " + calendar2.get(Calendar.HOUR) + ":" + calendar2.get(Calendar.MINUTE));

int zone1TimeMinutes = (calendar1.get(Calendar.HOUR) * 60) + calendar1.get(Calendar.MINUTE); int zone2TimeMinutes = zone1TimeMinutes - calendar1.get(Calendar.ZONE_OFFSET)/(60*1000)

+ calendar2.get(Calendar.ZONE_OFFSET)/(60*1000); int zone2Hours = zone2TimeMinutes/60; int zone2Mins = zone2TimeMinutes - (zone2Hours*60);

System.out.println("Calculated East Coast time: " + zone2Hours+ " hours and " + zone2Mins + " minutes");

}}

Unit 4 Exercise Solutions

// Solution for ModAdd Exercise

package exercises.odd;

public class ModAdd { public static void main(String[] args) { // two parameters are required if(args.length < 2) { System.out.println("Error: Requires two integer parameters"); return; } // get arguments int from = Integer.parseInt(args[0]); int to = Integer.parseInt(args[1]); // check arguments if(from >= to) { System.out.println("Error: 1st argument must be less than 2nd"); return; }

System.out.println("\nUsing for loop:"); int sum = 0; // for loop

Page 73: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-5

• • •••

Appendix A: Exercise SolutionsUnit 5 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

// iterate for all numbers "from" - "to" for(int i = from; i <= to; i++) { // check if number is multiple of 3 and not even if(i%3 == 0 && i%2 != 0) { sum = sum + i; } } System.out.println("Sum of odd numbers that are multiples of 3 from " + from + " to " + to + " is " + sum);

System.out.println("\nUsing while loop:");

sum = 0; //reinitialize total int i = from; // loop for all number "from" - "to" while( i <= to) { // check if number is multiple of 3 and not even if(i%3 == 0 && i%2 != 0) sum = sum + i; i++; } System.out.println("Sum of odd numbers that are multiples of 3 from " + from + " to " + to + " is " + sum); }}

Unit 5 Exercise Solutions

Exercise 1

package examples.str;

public class ReverseArgs {

public static void main(String args[]){

if(args.length < 2) { System.out.println("Usage: Requires at least two arguments"); return; }

StringBuilder strArguments = new StringBuilder(); // Use either traditional for loop or the enhanced foreach for ( String v : args) { strArguments.append(v + " "); }

Page 74: Ibm enterprise it and asset management 7.1 java for customization exercise

A-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 5 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

reverseArguments(strArguments); System.out.println ("Reversed letter by letter= " + strArguments);

// return strArguments to its original state reverseArguments(strArguments); System.out.println ("Original argument list = " + strArguments);

reverseWords(strArguments); System.out.println ("Reversed word by word = " + strArguments);

}

public static StringBuilder reverseArguments(StringBuilder s) { s = s.reverse(); return s; } public static StringBuilder reverseWords(StringBuilder s) { String str = s.toString(); String[] words = str.split ("\\ ");

s.delete(0, s.length()); for (int i=words.length; i > 0; )

s.append(words[--i] + " ");

return s; }

}

Exercise 2

// Solution for Calculator Exercise package exercises.calc;

public class Calculator{ public void add(double o1, double o2) { double result = o1 + o2; System.out.println(o1 + " + " + o2 + " = " + result); }

public void sub(double o1, double o2) { double result = o1 - o2; System.out.println(o1 + " - " + o2 + " = " + result); }

public void mult(double o1, double o2) { double result = o1 * o2; System.out.println(o1 + " * " + o2 + " = " + result); }

Page 75: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-7

• • •••

Appendix A: Exercise SolutionsUnit 5 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

public void div(double o1, double o2) { double result = o1 / o2; System.out.println(o1 + " / " + o2 + " = " + result); }

public static void main(String[] args) { if(args.length < 3) { System.out.println("Usage: add/sub/mult/div op1 op2"); return; } // get operation and change to uppercase String operation = args[0].toUpperCase(); // get operands double op1 = Double.parseDouble(args[1]); double op2 = Double.parseDouble(args[2]); // create instance of Calculator Calculator calc = new Calculator(); // check for the uppercase operation // and execute the appropriate method if(operation.startsWith("ADD")) { calc.add(op1,op2); } else if (operation.startsWith("SUB")) { calc.sub(op1,op2); } else if (operation.startsWith("MULT")) { calc.mult(op1,op2); } else if (operation.startsWith("DIV")) { calc.div(op1,op2); } else { System.out.println("Error: Invalid operation: " + operation + " It must be add/sub/mult/div"); } }}

Exercise 3

// Solution for Util Exercise

public class Util{ public static double add(double o1, double o2) { double result = o1 + o2; return result;

Page 76: Ibm enterprise it and asset management 7.1 java for customization exercise

A-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 5 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

}

public static int add(int o1, int o2) { int result = o1 + o2; return result; }

public static double sub(double o1, double o2) { double result = o1 - o2; return result; }

public static int sub(int o1, int o2) { int result = o1 - o2; return result; }

public static double mult(double o1, double o2) { double result = o1 * o2; return result; }

public static int mult(int o1, int o2) { int result = o1 * o2; return result; }

public static double div(double o1, double o2) { double result = o1 / o2; return result; }

public static int div(int o1, int o2) { int result = o1 / o2; return result; }

}

Exercise 4

// Solution for Perform Exercise

package exercises.calc;

import exercises.util.*;

public class Perform{ public static void main(String[] args) { if(args.length < 3) { System.out.println("Usage: add/sub/mult/div op1 op2"); return; }

Page 77: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-9

• • •••

Appendix A: Exercise SolutionsUnit 5 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

// Get the operation and convert to uppercase String operation = args[0].toUpperCase(); // get operands double op1 = 0; double op2 = 0; int i1 = 0; int i2 = 0; boolean isDouble = false; if(args[1].indexOf(".") != -1 || args[2].indexOf(".") != -1) { try { op1 = Double.parseDouble(args[1]); op2 = Double.parseDouble(args[2]); isDouble = true; } catch (NumberFormatException e) { e.printStackTrace(); } } else { i1 = Integer.parseInt(args[1]); i2 = Integer.parseInt(args[2]); } double answer = 0; // check operation and execute the proper one if(operation.startsWith("ADD")) { if(isDouble) answer = Util.add(op1,op2); else answer = Util.add(i1,i2); } else if (operation.startsWith("SUB")) { if(isDouble) answer = Util.sub(op1,op2); else answer = Util.sub(i1,i2); } else if (operation.startsWith("MULT")) { if(isDouble) answer = Util.mult(op1,op2); else answer = Util.mult(i1,i2); } else if (operation.startsWith("DIV")) { if(isDouble) answer = Util.div(op1,op2); else answer = Util.div(i1,i2); } else { System.out.println("Error: Invalid operation: " + operation + " It must be add/sub/mult/div"); return; }

Page 78: Ibm enterprise it and asset management 7.1 java for customization exercise

A-10 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 6 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

System.out.println(operation + " " + args[1] + " " + args[2] + " = " + answer); }}

Unit 6 Exercise Solutions

Exercise 1

package exercises.calc;

import exercises.util.*;

public class Do { public static void main(String[] args) throws Exception { if(args.length < 3) { System.out.println("Usage: add/sub/mult/div op1 op2"); throw new Exception("Too few parameters."); } // Get the operation and convert to uppercase String operation = args[0].toUpperCase(); // get operands double op1 = 0; double op2 = 0; int i1 = 0; int i2 = 0; boolean isDouble = false; if(args[1].indexOf(".") != -1 || args[2].indexOf(".") != -1) { try { op1 = Double.parseDouble(args[1]); op2 = Double.parseDouble(args[2]); isDouble = true; } catch (NumberFormatException e) { e.printStackTrace(); throw new Exception("Parameters " + args[1] + " and " + args[2] + " must be numeric"); } } else { i1 = Integer.parseInt(args[1]); i2 = Integer.parseInt(args[2]); } double answer = 0;

Page 79: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-11

• • •••

Appendix A: Exercise SolutionsUnit 6 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

// check operation and execute the proper one if(operation.startsWith("ADD")) { if(isDouble) answer = Util.add(op1,op2); else answer = Util.add(i1,i2); } else if (operation.startsWith("SUB")) { if(isDouble) answer = Util.sub(op1,op2); else answer = Util.sub(i1,i2); } else if (operation.startsWith("MULT")) { if(isDouble) answer = Util.mult(op1,op2); else answer = Util.mult(i1,i2); } else if (operation.startsWith("DIV")) { if(isDouble) answer = Util.div(op1,op2); else answer = Util.div(i1,i2); } else { System.out.println("Error: Invalid operation: " + operation + ". It must be add/sub/mult/div"); throw new Exception("Invalid operation: " + operation); }

System.out.println(operation + " " + args[1] + " " + args[2] + " = " + answer); }}

Exercise 2

package exercises.io;

import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.util.Scanner;

public class Palindromes {

Page 80: Ibm enterprise it and asset management 7.1 java for customization exercise

A-12 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 6 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

public static void main(String[] args) throws IOException { if (args.length != 3) { System.out.println("Usage: Must have 3 parameters"); System.exit(1); }

File inFile = new File(args[0]); File outFile1 = new File(args[1]); File outFile2 = new File(args[2]);

boolean exists = inFile.exists(); if (!exists) { System.out.println("File " + inFile.getName() + "does not exists"); System.exit(1); } try { filter4Palindromes(inFile, outFile1); scan4Palindromes(inFile, outFile2); } catch (IOException e) { System.out.println(e); System.exit(1); } }

public static void filter4Palindromes(File in, File out) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(in)); BufferedWriter writer = new BufferedWriter(new FileWriter(out));

String originalLine = null; String reversedLine = null; String trimmedLine = null; while ((originalLine=reader.readLine()) != null) { trimmedLine = originalLine.replaceAll(" ", ""); StringBuilder sbLine = new StringBuilder(trimmedLine); reversedLine = sbLine.reverse().toString(); if (reversedLine.compareToIgnoreCase(trimmedLine) == 0 ) { writer.write(originalLine); writer.newLine(); // System dependent newline } }

reader.close(); // Close reader to unlock writer.close(); // Close writer to unlock and flush }

public static void scan4Palindromes(File in, File out) throws IOException { Scanner freader = new Scanner(in); // uses Scanner BufferedWriter writer = new BufferedWriter(new FileWriter(out));

String originalLine = null; String reversedLine = null; String trimmedLine = null; while (freader.hasNextLine()) { originalLine = freader.nextLine();

Page 81: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-13

• • •••

Appendix A: Exercise SolutionsUnit 7 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

trimmedLine = originalLine.replaceAll(" ", ""); StringBuilder sbLine = new StringBuilder(trimmedLine); reversedLine = sbLine.reverse().toString(); if (reversedLine.compareToIgnoreCase(trimmedLine) == 0 ) { writer.write(originalLine); writer.newLine(); } }

freader.close(); writer.close(); }}

Unit 7 Exercise Solutions

Exercise 1

The following five files form the solution for Exercise 1:

package exercises.HowRU;

public interface HowAreYou { public void sayHowAreYou();}

package exercises.HowRU;

public class EnglishHowAreYou implements HowAreYou {

public void sayHowAreYou() { System.out.println("How are you?"); }}

package exercises.HowRU;

public class FrenchHowAreYou implements HowAreYou {

public void sayHowAreYou() { System.out.println("Ca va?"); }}

Page 82: Ibm enterprise it and asset management 7.1 java for customization exercise

A-14 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 7 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

package exercises.HowRU;

public class ItalianHowAreYou implements HowAreYou {

public void sayHowAreYou() { System.out.println("Come stai?"); }}

package exercises.HowRU;

public class SayHowAreYou {

public HowAreYou howAreYou;

public void setLanguage(HowAreYou howAreYou) { this.howAreYou = howAreYou; }

public void sayHowAreYou() { this.howAreYou.sayHowAreYou(); }

public static void main(String[] args) { SayHowAreYou howru = new SayHowAreYou(); howru.setLanguage(new EnglishHowAreYou()); howru.sayHowAreYou(); howru.setLanguage(new ItalianHowAreYou()); howru.sayHowAreYou(); howru.setLanguage(new FrenchHowAreYou()); howru.sayHowAreYou(); }}

Exercise 2

The following fifteen files form a possible solution for Exercise 2:

package exercises.music;

public interface Instrument { public void play(); public void tune(); public void mute();}

package exercises.music;

public abstract class BowType implements Instrument { private String name;

Page 83: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-15

• • •••

Appendix A: Exercise SolutionsUnit 7 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

protected BowType(String instrumentName) { System.out.println("Entering BowType constructor"); name = new String(instrumentName); System.out.println("Exiting BowType constructor"); }

protected String getName() { return name; } public void mute() { System.out.println("mute():abstract class BowType for " + getName() ); }

public void play() { System.out.println("play():abstract class BowType for " + getName()); }

public void tune() { System.out.println("tune():abstract class BowType for " + getName()); }}

package exercises.music;

public abstract class PluckType implements Instrument { private String name;

protected String getName() { return name; }

protected PluckType(String instrumentName) { System.out.println("Entering BowType constructor"); name = new String(instrumentName); System.out.println("Exiting BowType constructor"); } public void mute() { System.out.println("mute():abstract class PluckType" + getName()); }

public void play() { System.out.println("play():abstract class PluckType" + getName()); }

public void tune() { System.out.println("tune():abstract class PluckType" + getName()); }}

Page 84: Ibm enterprise it and asset management 7.1 java for customization exercise

A-16 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 7 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

package exercises.music;

public abstract class StrikeType implements Instrument { private String name;

protected StrikeType(String instrumentName) { System.out.println("Entering StrikeType constructor"); name = new String(instrumentName); System.out.println("Exiting StrikeType constructor"); }

protected String getName() { return name; }

public void mute() { System.out.println("mute():abstract class StrikeType" + getName()); }

public void play() { System.out.println("play():abstract class StrikeType" + getName()); }

public void tune() { System.out.println("tune():abstract class StrikeType" + getName()); }}

package exercises.music;

public abstract class WindType implements Instrument { private String name;

protected WindType(String instrumentName) { System.out.println("Entering WindType constructor"); name = new String(instrumentName); System.out.println("Exiting WindType constructor"); }

protected String getName() { return name; } public void mute() { System.out.println("mute():abstract class WindType" + getName()); }

public void play() { System.out.println("play():abstract class WindType" + getName()); }

public void tune() { System.out.println("tune():abstract class WindType" + getName()); }}

Page 85: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-17

• • •••

Appendix A: Exercise SolutionsUnit 7 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

package exercises.music;

public class Bass extends PluckType {

public Bass() { super("Bass"); System.out.println("Exiting Bass constructor"); }

public String getName(){ System.out.println ("The Bass class inherits its name: " + super.getName() + " from its base class"); return super.getName(); }}

package exercises.music;

public class Cello extends BowType {

public Cello() { super("Cello"); System.out.println("Exiting Cello constructor"); }

public String getName(){ System.out.println ("The Cello class inherits its name: " + super.getName() + " from its base class"); return super.getName(); }}

package exercises.music;

public class Drums extends StrikeType {

public Drums() { super("Drums"); System.out.println("Exiting Drums constructor"); }

public String getName(){ System.out.println ("The Drums class inherits its name: " + super.getName() + " from its base class"); return super.getName(); }

}

Page 86: Ibm enterprise it and asset management 7.1 java for customization exercise

A-18 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 7 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

package exercises.music;

public class Guitar extends PluckType {

public Guitar() { super("Guitar"); System.out.println("Exiting Guitar constructor"); }

public String getName(){ System.out.println ("The Guitar class inherits its name: " + super.getName() + " from its base class"); return super.getName(); }}

package exercises.music;

public class Piano extends StrikeType { public Piano() { super("Piano"); System.out.println("Exiting Piano constructor"); }

public String getName(){ System.out.println ("The Piano class inherits its name: " + super.getName() + " from its base class"); return super.getName(); }}

package exercises.music;

public class Saxophone extends WindType {

public Saxophone() { super("Saxophone"); System.out.println("Exiting Saxophone constructor"); }

public String getName(){ System.out.println ("The Saxophone class inherits its name: " + super.getName() + " from its base class"); return super.getName(); }}

Page 87: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-19

• • •••

Appendix A: Exercise SolutionsUnit 7 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

package exercises.music;

public class Viola extends BowType {

public Viola() { super("Viola"); System.out.println("Exiting Viola constructor"); }

public String getName(){ System.out.println ("The Viola class inherits its name: " + super.getName() + " from its base class"); return super.getName(); }

public void play() { System.out.println ("Viola.play() The Viola class overrides BowType.play()"); }}

package exercises.music;

public class Violin extends BowType {

public Violin() { super("Violin"); System.out.println("Exiting Violin constructor"); }

public String getName(){ System.out.println ("The Violin class inherits its name: " + super.getName() + " from its base class"); return super.getName(); }}

package exercises.music;

public class Quartet {

public Instrument[] quartet;

public Quartet() { quartet = new Instrument[4]; } public void createStringQuartet() { quartet[0] = new Violin(); quartet[1] = new Violin(); quartet[2] = new Viola(); quartet[3] = new Cello(); return; }

Page 88: Ibm enterprise it and asset management 7.1 java for customization exercise

A-20 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 7 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

public void createJazzQuartet() { quartet[0] = new Saxophone(); quartet[1] = new Piano(); quartet[2] = new Bass(); quartet[3] = new Drums(); return; } public void createRockQuartet() { quartet[0] = new Guitar(); quartet[1] = new Guitar(); quartet[2] = new Bass(); quartet[3] = new Drums(); return; } public void playMusic() { for (int i = 0; i < 4; i++) quartet[i].play(); }

}

package exercises.music;

public class MakeMusic {

public static void main(String[] args) {

Quartet qString = new Quartet(); qString.createStringQuartet(); qString.playMusic();

// Quartet qJazz = new Quartet();// qJazz.createJazzQuartet();// qJazz.playMusic();

// Quartet qRock = new Quartet();// qRock.createRockQuartet();// qRock.playMusic(); }}

Page 89: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-21

• • •••

Appendix A: Exercise SolutionsUnit 8 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Unit 8 Exercise Solutions

Exercise 1

package exercises.calc;

import java.util.Arrays;import java.util.List;

public class Median {

//To find the Median, place the values //in order and find the middle value. // If there areis an even number of values // find the middle pair of values and // calculate the average of those two values.

public static void main(String[] args) { if (args.length == 0) { System.out.println("No arguments to compute median"); return; }

List<String> lArgs = Arrays.asList(args); System.out.println("Program arguments: " + lArgs);

double[] sortedArray = new double[args.length];

int i = 0;

for (String v:args) sortedArray[i++] = Double.parseDouble(v);

java.util.Arrays.sort(sortedArray);

System.out.print("\nSorted arguments: "); for (double d : sortedArray) System.out.print(d + " ");

int median = (args.length/2); // truncates to an int

if ((args.length%2)!=0 ) { System.out.println("\nThe median value is: " + sortedArray[median]); } else { System.out.println("\nThe median value is: " + (sortedArray[median-1] + sortedArray[median])/2); } }}

Page 90: Ibm enterprise it and asset management 7.1 java for customization exercise

A-22 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 8 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Exercise 2

package examples.list;

import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.util.LinkedList;import java.util.ListIterator;

public class LList {

public static void main(String[] args) {

if (args.length != 1) { System.out.println("Usage: File name "); System.exit(1); }

File inFile = new File(args[0]);

boolean exists = inFile.exists(); if (!exists) { System.out.println("File " + inFile.getName() + "does not exists"); System.exit(1); }

try { fillList(inFile); } catch (IOException e) { System.out.println(e); System.exit(1); } }

public static void fillList(File in) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(in)); LinkedList<String> lst = new LinkedList<String>(); String line = null;

while ((line=reader.readLine()) != null) { lst.add(line); }

reader.close(); System.out.println("Print list using foreach"); for (String s: lst) System.out.println(s);

System.out.println("Print list using listIterator"); for (ListIterator<String> it = lst.listIterator(); it.hasNext();) { System.out.println(it.next()); }

Page 91: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-23

• • •••

Appendix A: Exercise SolutionsUnit 8 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

System.out.println("Print list in reverse using listIterator"); for (ListIterator<String> it = lst.listIterator(lst.size()); it.hasPrevious();) { System.out.println(it.previous()); } }}

Exercise 3

package examples.list;

import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.ListIterator;

public class AList {

public static void main(String[] args) {

if (args.length != 1) { System.out.println("Usage: File name "); System.exit(1); }

File inFile = new File(args[0]);

boolean exists = inFile.exists(); if (!exists) { System.out.println("File " + inFile.getName() + "does not exists"); System.exit(1); }

try { fillList(inFile); } catch (IOException e) { System.out.println(e); System.exit(1); } }

public static void fillList(File in) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(in)); ArrayList<String> lst = new ArrayList<String>(); String line = null;

while ((line=reader.readLine()) != null) { lst.add(line); }

Page 92: Ibm enterprise it and asset management 7.1 java for customization exercise

A-24 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 8 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

reader.close(); System.out.println("Print list using foreach"); for (String s: lst) System.out.println(s);

System.out.println("Print list using listIterator"); for (ListIterator<String> it = lst.listIterator(); it.hasNext();) { System.out.println(it.next()); }

System.out.println("Print list in reverse using listIterator"); for (ListIterator<String> it = lst.listIterator(lst.size()); it.hasPrevious();) { System.out.println(it.previous()); } }}

Exercise 4

public class ShuffleNDeal {

public static void main(String[] args) { Deck deck = new Deck();

deck.printDeck(); deck.shuffleDeck(); deck.dealFromTop(4); deck.dealFromBottom(10); deck.shuffleDeck(); deck.dealFromTop(4); }}

package examples.cards;

import java.util.Collections;import java.util.LinkedList;

public class Deck { private LinkedList<String> cards;

public Deck() { cards = new LinkedList<String>(); String[] suit = {"spades", "hearts","clubs","diamonds"}; String[] rank = {"2","3","4","5","6","7","8","9","10","Jack", "Queen","King","Ace"};

Page 93: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-25

• • •••

Appendix A: Exercise SolutionsUnit 8 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

int k = 0; for (int i = 0; i <=3; ++i) { for (int j = 0; j <=12; ++j){ cards.add(k++, rank[j]+ " of " + suit[i]); } } } public LinkedList<String> getDeck() { return cards; } public void printDeck() { System.out.println("Cards in Deck:" + cards); } public void shuffleDeck() { Collections.shuffle(cards); System.out.println("Cards in Deck:" + cards); } public void dealFromTop(int numberPlayers) { if (numberPlayers>10) { System.out.println("Not enough cards to deal "

+ numberPlayers + " players 5 cards from deck"); return; }

int i = 0, k = 0;

// System.out.print("\n\nDealing from the top....."); while( ++i <= numberPlayers) { System.out.print("\nPlayer " + i + ":"); for (int j = 0; j <= 4; j++) { System.out.print(" " + cards.get(k++)); } } }

public void dealFromBottom(int numberPlayers) { if (numberPlayers>10) { System.out.println("Not enough cards to deal "

+ numberPlayers + " players 5 cards from deck"); return; }

int i = 0, k = 51;

// System.out.print("\n\nDealing from the bottom....."); while( ++i <= numberPlayers) { System.out.print("\nPlayer " + i + ":"); for (int j = 0; j <= 4; j++) { System.out.print(" " + cards.get(k--)); } } }}

Page 94: Ibm enterprise it and asset management 7.1 java for customization exercise

A-26 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 8 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Exercise 5

The following files form a possible solution for Exercise 5:

package exercises.medical;

import java.util.LinkedList;

public class Doctor {

public String name;

public Doctor(String docName) { name = new String(docName); }

public XRayTest requestXRayTest(Patient patient) { XRayTest xTest = new XRayTest(this.name, patient.name); return xTest; }

public BloodTest requestBloodTest(Patient patient) { BloodTest bTest = new BloodTest(this.name, patient.name); return bTest; }

public LinkedList<XRayTest> requestResults(XRayLab lab) { return lab.listOut; }

public LinkedList<BloodTest> requestResults(BloodLab lab) { return lab.listOut; }}

package exercises.medical;

public class Patient { String bloodType; String name; Doctor doctor;

public Patient(String name, Doctor doc) { this.name = new String(name); doctor = doc; }

Page 95: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-27

• • •••

Appendix A: Exercise SolutionsUnit 8 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

public String getName () { return name; }}

package exercises.medical;

public abstract class Lab {

public Lab() { // System.out.println("Lab constructor"); }

public void runTests() { }}

package exercises.medical;

public abstract class MedicalTest { private Patient patient; private Doctor doctor; private boolean testComplete = false;

public MedicalTest(String d, String p){ doctor = new Doctor(d); patient = new Patient(p,doctor); }

public Patient getPatient(){ return this.patient; }

public Doctor getDoctor() { return this.doctor; }

public void performTest() { testComplete = true; }

public void setTestComplete(boolean b) { testComplete = b; }

public boolean isTestComplete() { return testComplete; }}

Page 96: Ibm enterprise it and asset management 7.1 java for customization exercise

A-28 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 8 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

package exercises.medical;

public abstract class Result { public final static String NEG = "negative"; public final static String POS = "positive"; private String result;

public Result() { result = ""; }

public void setResult2Positive() { result = POS; }

public void setResult2Negative() { result = NEG; }

public String getResult(){ return result; }}

package exercises.medical;

import java.util.LinkedList;import java.util.ListIterator;

public class BloodLab extends Lab{

protected LinkedList<BloodTest> listIn; protected LinkedList<BloodTest> listOut; protected LinkedList<BloodTest> listArchive;

public BloodLab() { listIn = new LinkedList<BloodTest>(); listOut = new LinkedList<BloodTest>(); listArchive = new LinkedList<BloodTest>() ; }

public void add2List(BloodTest test) { listIn.add(test); }

public void runTests() { BloodTest aTest;

for (ListIterator<BloodTest> itlistIn = listIn.listIterator(); itlistIn.hasNext();) {

aTest = itlistIn.next();

Page 97: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-29

• • •••

Appendix A: Exercise SolutionsUnit 8 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

System.out.print(" Run blood test for patient: " + aTest.getPatient().name); System.out.println(" (Requested by Doctor " + aTest.getDoctor().name + ")"); // run test and place in listOut aTest.result.setResult2Positive(); listOut.add(aTest); }

listIn.clear(); return; }

public void getTestResults() { BloodTest aTest;

for (ListIterator<BloodTest> itlistOut = listOut.listIterator(); itlistOut.hasNext();) { aTest = itlistOut.next(); System.out.print(" Completed blood test for patient: " + aTest.getPatient().name); System.out.println(" (Requested by Doctor " + aTest.getDoctor().name + ")"); System.out.println(" Test result: " + aTest.result.getResult()); } }

public void archiveTests() {

for (BloodTest x : listOut) { listArchive.add(x); }

listOut.clear(); return; }}

package exercises.medical;

public class BloodResult extends Result {

public BloodResult() { super(); }

Page 98: Ibm enterprise it and asset management 7.1 java for customization exercise

A-30 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 8 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

public String getResult(){ return super.getResult(); }}

package exercises.medical;

public class BloodTest extends MedicalTest { protected String bloodType; public BloodResult result;

public BloodTest(String d, String patient) { super(d, patient); bloodType = new String(""); result = new BloodResult(); }

public BloodResult getResult() { return result; }}

package exercises.medical;

import java.util.LinkedList;import java.util.ListIterator;

public class XRayLab extends Lab{ protected LinkedList<XRayTest> listIn; protected LinkedList<XRayTest> listOut; protected LinkedList<XRayTest> listArchive;

public XRayLab() { listIn = new LinkedList<XRayTest>(); listOut = new LinkedList<XRayTest>(); listArchive = new LinkedList<XRayTest>(); }

public void runTests() {

XRayTest aTest; for (ListIterator<XRayTest> itlistIn = listIn.listIterator(); itlistIn.hasNext();) {

aTest = itlistIn.next(); System.out.print(" Run x-ray test for patient: " + aTest.getPatient().name); System.out.println(" (Requested by Doctor " + aTest.getDoctor().name + ")"); // run test and place in listOut

Page 99: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-31

• • •••

Appendix A: Exercise SolutionsUnit 8 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

aTest.result.setResult2Negative(); listOut.add(aTest); } listIn.clear(); return; }

public void getTestResults() {

for (ListIterator<XRayTest> itlistOut = listOut.listIterator(); itlistOut.hasNext();) { XRayTest aTest = itlistOut.next(); System.out.print(" Completed x-ray test for patient: " + aTest.getPatient().name); System.out.println(" (Requested by Doctor " + aTest.getDoctor().name + ")"); System.out.println(" Test result: " + aTest.result.getResult()); } }

public void add2List(XRayTest t) { listIn.add(t); }

public void archiveTests() {

for (XRayTest x : listOut) { listArchive.add(x); }

listOut.clear(); return; }}

package exercises.medical;

public class XRayResult extends Result {

public XRayResult() { super(); }

public String getResult(){ return super.getResult(); }}

Page 100: Ibm enterprise it and asset management 7.1 java for customization exercise

A-32 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 8 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

package exercises.medical;

public class XRayTest extends MedicalTest { public XRayResult result; public XRayTest(String d, String patient) { super(d, patient); result = new XRayResult(); }

public XRayResult getResult() { return result; }}

package exercises.medical;

import java.util.ArrayList;

public class Hospital {

public XRayLab xLab; public BloodLab bLab; public ArrayList<Doctor> dArray; public ArrayList<Patient> pArray;

public Hospital() { xLab = new XRayLab(); bLab = new BloodLab(); dArray = new ArrayList<Doctor>(); pArray = new ArrayList<Patient>(); }

public void send2Lab(XRayTest t) { xLab.add2List(t); } public void send2Lab(BloodTest t) { bLab.add2List(t); } public XRayResult getResult(XRayTest t) { return t.getResult(); }

public BloodResult getResult(BloodTest t) { return t.getResult(); }}

Page 101: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-33

• • •••

Appendix A: Exercise SolutionsUnit 8 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

package exercises.medical;

public class CountyHospital extends Hospital {

public static void main(String[] args) { CountyHospital hospital = new CountyHospital(); hospital.populateHospital(); hospital.requestTests(); }

public void populateHospital() { Doctor d = new Doctor("Anu P"); dArray.add(d); pArray.add(new Patient("Emma A", d)); pArray.add(new Patient("Ira N", d)); d = new Doctor("Ray B"); dArray.add(d); pArray.add(new Patient("Ivy S", d));

// print out doctor list for (Doctor doc: dArray) System.out.println("Doctor's name: " + doc.name);

// print out patient list for (Patient pat: pArray) System.out.println("Patient's name: "

+ pat.name + " Doctor's name: " + pat.doctor.name);

System.out.println("Completed doctor and patient lists"); }

public void requestTests(){ // send test requests to labs send2Lab(new XRayTest("Anu P", "Emma A")); send2Lab(new XRayTest("Anu P", "Ira N")); send2Lab(new BloodTest("Anu P", "Emma A"));

System.out.println("\nRun test requests in list and get results: "); runTestsAndGetResults();

// System.out.println("\nArchive test requests"); xLab.archiveTests(); bLab.archiveTests();

// send more test requests to labs send2Lab(new XRayTest("Ray B", "Ivy S")); send2Lab(new BloodTest("Ray B", "Ivy S")); System.out.println("\nRun tests in list and get results: "); runTestsAndGetResults(); }

Page 102: Ibm enterprise it and asset management 7.1 java for customization exercise

A-34 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 9 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

public void runTestsAndGetResults() { xLab.runTests(); xLab.getTestResults(); bLab.runTests(); bLab.getTestResults(); }}

Unit 9 Exercise Solutions

Exercise 1

package exercises.synch;

public class ProducerConsumerDriver {

public static void main(String[] args) { SharedData data; Thread Producers[]; Thread Consumers[]; int ProducerNumber; int ConsumerNumber; int producerPriority; int consumerPriority; int interval;

if (args.length < 5 ) { System.out.print("Usage: \n> "); System.out.print("<NumberProducers> <NumberConsumers> "); System.out.println("<ProducerPriority> <ConsumerPriority>"); System.out.println("<SleepInterval> "); return; }

data = new SharedData(); ProducerNumber=Integer.parseInt(args[0]); ConsumerNumber=Integer.parseInt(args[1]); producerPriority = Integer.parseInt(args[2]); consumerPriority = Integer.parseInt(args[3]); interval=Integer.parseInt(args[4])); Producers = new Thread[ProducerNumber]; Consumers = new Thread[ConsumerNumber];

for(int i=0;i<ProducerNumber;i++){ Producers[i]=new Thread (new Producer(data, i, interval)); Producers[i].setPriority(producerPriority); Producers[i].start(); }

Page 103: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-35

• • •••

Appendix A: Exercise SolutionsUnit 9 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

for(int i=0;i<ConsumerNumber;i++) { Consumers[i]=new Thread (new Consumer(data, i, interval)); Consumers[i].setPriority(consumerPriority); Consumers[i].start(); } }}

class Producer implements Runnable{ SharedData data; int interval; int identifier; public Producer(SharedData data, int id, int interval) { this.data=data; this.interval=interval; this.identifier=id; } public void run() { int i; for(i=0; ; i++) { data.put(i); System.out.println("Producer "+ identifier+ ": "+i); try { Thread.sleep((int) (Math.random()*interval)); } catch (InterruptedException e) { System.out.println("Producer error\n"); } } }}

public class Consumer implements Runnable{ SharedData data; int interval; int identifier; public Consumer(SharedData data, int id, int interval) { this.data=data; this.interval=interval; this.identifier=id; } public void run() { for(;;) { System.out.println(" Consumer " + identifier + ": "+data.get()); try {

Thread.sleep((int) (Math.random()*interval)); } catch (InterruptedException e) { System.out.println("Consumer error\n"); } }

Page 104: Ibm enterprise it and asset management 7.1 java for customization exercise

A-36 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 10 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

}}

public class SharedData { protected int Data; boolean data2Consume = false; public synchronized void put(int Data) { while (data2Consume) { try {

wait(); } catch (InterruptedException e) {} }

this.Data=Data; data2Consume = true; notifyAll(); } public synchronized int get() { int Data; while(!data2Consume) { try { wait(); } catch (InterruptedException e) {} }

Data = this.Data; data2Consume = false; notifyAll(); return Data; }}

Unit 10 Exercise Solutions

Exercise 1

package exercises.serial;

import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.io.Serializable;import java.util.ArrayList;

Page 105: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-37

• • •••

Appendix A: Exercise SolutionsUnit 10 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

public class SerialObject implements Serializable {

transient int transValue; int value; String stringValue; ArrayList<String> lst;

SerialObject() { transValue = 10; value = 20; stringValue = "Serialization Test"; lst = new ArrayList<String>(); }

public void populateList(File in) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(in)); String line = null;

while ((line=reader.readLine()) != null) { lst.add(line); }

reader.close(); System.out.println("Print populated list using foreach"); for (String s: lst) System.out.println(s); } public void printList() { System.out.println("Print list using foreach"); for (String s: lst) System.out.println(s); }}

Exercise 2

package exercises.serial;

import java.io.*;

public class SerializeDriver {

public static void main(String[] args) throws IOException, ClassNotFoundException { SerialObject so = new SerialObject(); String inFileName = "c:\\JavaIO.txt"; String serialFileName = "c:\\Serial.txt"; File in = new File(inFileName); File serialFile = new File(serialFileName); boolean exists = in.exists(); if (!exists) {

Page 106: Ibm enterprise it and asset management 7.1 java for customization exercise

A-38 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 10 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

System.out.println("File " + in.getName() + "does not exists"); return; }

so.populateList(in); System.out.println("so.transValue = " + so.transValue); // create a file stream for writing FileOutputStream fos = new FileOutputStream(serialFile); // create object to write to fos ObjectOutputStream oStream = new ObjectOutputStream(fos); // save so object oStream.writeObject(so); oStream.flush(); so.lst.add("Added a non-Serialized String"); so.printList(); System.out.println("That was the none -serialized list"); so.stringValue = "Nothing"; System.out.println(so.stringValue); // create a file stream for reading FileInputStream fis = new FileInputStream(serialFileName); // create object to read fis ObjectInputStream iStream = new ObjectInputStream(fis); // retrieve the object's serialized state so = (SerialObject)iStream.readObject(); System.out.println("After serialization"); System.out.println("so.transValue = " + so.transValue); System.out.println("so.value = " + so.value); System.out.println("so.StringValue = " + so.stringValue); so.printList(); } }

Exercise 3

package exercises.serial;

import java.io.*;

public class DeSerializeDriver {

public static void main(String[] args) throws IOException, ClassNotFoundException { SerialObject obj = new SerialObject(); String serialFileName = "c:\\Serial.txt"; File serialFile = new File(serialFileName); boolean exists = serialFile.exists(); if (!exists) {

Page 107: Ibm enterprise it and asset management 7.1 java for customization exercise

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization A-39

• • •••

Appendix A: Exercise SolutionsUnit 10 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

System.out.println("File " + serialFile.getName() + "does not exists"); return; } // so.lst.add("Added a non-Serialized String");// so.printList();// System.out.println("That was the non-serialized list"); // create a file stream for reading FileInputStream fis = new FileInputStream(serialFileName); // create object to read fis ObjectInputStream iStream = new ObjectInputStream(fis); // deserialize state into obj obj = (SerialObject)iStream.readObject(); System.out.println("After deserialization"); System.out.println("obj.transValue = " + obj.transValue); System.out.println("obj.value = " + obj.value); obj.printList(); } }

Exercise 4

Solution files were provided as part of the exercise.

Page 108: Ibm enterprise it and asset management 7.1 java for customization exercise

A-40 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Appendix A: Exercise SolutionsUnit 10 Exercise Solutions

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Page 109: Ibm enterprise it and asset management 7.1 java for customization exercise
Page 110: Ibm enterprise it and asset management 7.1 java for customization exercise

S150-3086-00

C T5

DFE

N

IBM

Printed in Ireland

®