452
IBM Enterprise IT and Asset Management 7.1: Java for Customization Student’s Training Guide S150-3087-00 May 2009

Ibm enterprise it and asset management 7.1 java for customization training

  • View
    538

  • Download
    0

Embed Size (px)

DESCRIPTION

java basic

Citation preview

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

IBM Enterprise IT and Asset Management 7.1: Java for CustomizationStudent’s Training GuideS150-3087-00

May 2009

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

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 training

• • • ••

I

Table of Contents

Preface Course Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .XAudience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .XIBM Tivoli Technical Education . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .XTivoli User Group Community . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .XCourse Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . XICourse Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . XITypographical Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . XIIIProduct Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . XIII

Product Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . XIII

Unit 1: Objects and Object-Oriented ProgrammingIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2Evolution to Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3Software Evolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4Modeling Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5Everything Is an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6Object Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7Similar Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8Keys to Object-Oriented Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9Characteristics of an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10Car Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11A Class Is the Blueprint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12Classes and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14The Car Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-15An Object’s Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-17Abstraction and Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-18Data Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19Inheritance and Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-20Subclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-21Object Interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-22Representing an Entity with Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-23Classes and Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-24Object Interaction and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-25Class Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-26Object-Oriented Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-27Encapsulation and Information Hiding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-28Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-29Class Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-30Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-31One Interface, Multiple Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-32Polymorphism and Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-33Shape Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-34Explaining Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-35Key Concepts and Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-36Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-37Review Answers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-38Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-39

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

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.

Unit 2: Programming with JavaIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2

Lesson 1: The Java Programming Language . . . . . . . . . . . . . . . . . . . . . . . . . .2-3The Java Platform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4Platform Independence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5Just-in-Time Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6Language Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7JDK, JRE, and JVM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8Java API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9Types of Java Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10

Lesson 2: Development Environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-11Using the Eclipse IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12Creating Projects, Classes, and Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13Running Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14Run Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16Debugging Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-18Setting Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19Debug Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20Student Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-21Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-22Review Answers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-24Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-25

Unit 3: Java Basics and OperatorsIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2

Lesson 1: Class Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-3File Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6Package Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7import Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8import Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-9Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-11

Lesson 2: Language Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-13Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-14Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-15Built-in Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-17Wrapper Classes for Primitives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-18Primitives and References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-19Common Wrapper Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-20Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-22Variables in Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-23Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-24Print Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-25Printing Newlines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-26

Lesson 3: Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-27Assignment with Combination Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-28Assignment Using the ++ and -- Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-29Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-30Relational Operator Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-31

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

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

• • •••

Table of Contents

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

Relational Operator Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-32Common Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-33Comparing Primitives and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-34Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-35Ternary ? Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-36Bitwise Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-37Bitwise Shift Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-38Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-39Student Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-40Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-41Review Answers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-42Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-43

Unit 4: Java Basics and Programming SyntaxIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2Variable Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3Variable Access Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4Method Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5Method Access Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6main() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7main() Method Signature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9Array Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10Allocating an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-11Arrays in Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-12Arrays Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-13Arrays of Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14Declare an Array of Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-15Different Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-16Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-17Variable Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-18Initial Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-19Casting Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-20Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-21if and if-else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-23if-else Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-24if-else if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-26switch Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-27break and continue Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-29break Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-30Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-31while Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-32for Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-33Comparing for and while Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-34do-while Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-36Infinite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-37foreach statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-38Scope of a Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-39Printing Program Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-40Add Program Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-41Conversions from String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-42Class Sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-43Student Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-44Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-45Review Answers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-46Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-47

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

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

Unit 5: Classes, Constructors, and StringsIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2

Lesson 1: Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-3Create Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4Classes and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5Using new . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-6Garbage Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7

Lesson 2: Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-8Default Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9Using the Keyword this . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10Using the super() Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11Constructors versus Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-12Order of Construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13Object Creation with Instance Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-14Static Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15Static Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-16Calling Static Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-17

Lesson 3: Java Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-18Java Documentation Navigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-19Documentation Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-20

Lesson 4: String Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-21Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-22String Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-23String Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-24More String Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-26Using String Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-27Conversion Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-28Comparison Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-29Searching Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-30Regular Expression Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-31Conversions from String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-32Conversions to String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-33Using the split() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-34ConvertTemperature Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-35ConvertTemperature Class Variation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-36The convert() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-37Student Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-38Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-39Review Answers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-40Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-41

Unit 6: Java Exceptions, I/O, and InheritanceIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2

Lesson 1: Access Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-3Access Control Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4Access Control Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5abstract, final, and static Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6Using the Keyword this . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7this Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8Passing Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-10Pass by Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-11

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

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

• • •••

Table of Contents

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

Passing Objects by Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-12Passing an Object Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-13A Copy of an Object Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-14Pass by Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-15Garbage Collection Revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-16Garbage Collection and Object References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-17Memory Leaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-18Overloading Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-20Guidelines for Overloading Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-21Overloading versus Overriding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-23

Lesson 2: Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-24Exception Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-25Exception Propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-26Methods and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-27Catching Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-28Rethrowing an Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-29To Catch or Throw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-31Java Exception Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-32User-Defined Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-33Catch Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-34try...finally Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-35finally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-36

Lesson 3: Java I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-37Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-38Key Classes in java.io Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-39Efficient I/O Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-40The PrintWriter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-41Using Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-42File I/O Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-44Changing File Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-45

Lesson 4: Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-46Principles of Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-47The Object Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-48The extends Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-49Constructor Execution Revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-50Constructor Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-51Constructors with and without Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-53Abstract Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-55Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-56Multiple Inheritance with Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-57Casting within the Class Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-59Casting Primitives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-60Automatic Class Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-61Automatic Interface Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-62Explicit Casts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-63Upcasting and Downcasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-65Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-66Dynamic Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-67Student Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-68Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-69Review Answers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-70Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-72

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

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

Unit 7: Design Patterns, Interfaces, and the Collections Framework

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2

Lesson 1: Design Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-3Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4Singleton Design Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6Using the Singleton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7Proxy Design Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-8Adapter Design Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9Immutable Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10Iterator Design Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-11Generic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12

Lesson 2: Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-13An Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-14Implementing an Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-15Abstract Classes versus Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-16Implementing Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-17Interfaces and Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-18Extending Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-19Extending Multiple Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-20Nested and Inner Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-22

Lesson 3: The Collections Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-23Java Collections Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-24Basic Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-25Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-26Linked List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-27Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-28Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-29Collection Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-30Interface Implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-31Navigating a Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-32Original Enumeration Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-33Student Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-34Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-35Review Answers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-36Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-37

Unit 8: Strings, Arrays, and Collection ClassesIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2

Lesson 1: StringBuffer and StringBuilder . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-3StringBuilder Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4StringBuilder Methods and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-6StringBuilder Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-8Immutable Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-9

Lesson 2: Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-11Using Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-12Length of an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-13foreach Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-14Array Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-15ArrayList Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-16

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

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

• • •••

Table of Contents

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

Lesson 3: Collections Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-17Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-18Collection Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-19Collections Classes and Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-20Map Classes and Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-21

Lesson 4: ArrayList<E> Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-22Choosing an ArrayList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-23ArrayList Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-24Searching, Adding, and Deleting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-25Looping over an ArrayList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-27Iterator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-29Iterator Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-30Iterator Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-31ListIterator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-32ListIterator Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-33Using an Iterator and Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-34LinkedList Class Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-35LinkedList Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-36Adding to a Linked List with fillList() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-38Iterating through a LinkedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-39Autoboxing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-40Student Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-41Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-42Review Answers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-44Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-45

Unit 9: ThreadsIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2

Lesson 1: Threading Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-3Multithreaded Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4Advantages and Disadvantages of Using Multiple Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-5The Life Cycle of a Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6Threads and the Operating System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7Preemptive Threading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-8Priorities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-9Thread States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-10Blocking and Yielding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-11Locks and Critical Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-12Deadlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-13Semaphore . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-14Starvation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-15

Lesson 2: Implementing Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-16The Thread Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-17The Runnable Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-18Starting a Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-19Thread Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-20Extending the Thread Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-21Running the Thread Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-22Implementing the Runnable Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-24Running the Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-25Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-26Synchronization Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-27The Producer-Consumer Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-29Synchronized Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-32

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

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

Using wait() and notify() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-33Student Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-35Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-36Review Answers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-38Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-39

Unit 10: Serialization and Remote Method InvocationIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2

Lesson 1: Serialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10-3Serialization of an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-4Why Use Serialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-5Static and Transient Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-6Making a Class Serializable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-7Implementing the Serializable Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-8Instance and Superclass State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-9equals() and hashCode() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-10Serialization Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-11writeObject() and readObject() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-12Serialization Implementation Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-13Serialization Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-14

Lesson 2: Remote Method Invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10-15Distributed Computing and RMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-16Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-17Client and Server Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-18RMI Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-19Proxy Stubs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-20Remote Reference and Transport Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-21Finding RMI Remote Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-22RMI System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-23HelloRemote Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-24Hello Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-25RMIServer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-26RMIClient Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-28Invoking Remote Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-30Student Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-31Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-32Review Answers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-34Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-35

Tivoli Professional Certification Special Offer for Having Taken This Course . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IReasons for Certification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IRole-based Certification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IWhen to Attempt a Certification Exam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IILocation and Cost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IISources of Additional Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . II

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

• • • ••

IX

Preface

© 2009 IBM Corporation

Student Guide

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

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

• • • ••

Preface

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

Course Description

The IBM Enterprise IT and Asset Management 7.1 Java for Customization course provides hands-on training to learn Java™ programming skills using the Eclipse Integrated Development Environment. This course includes Java and object-oriented fundamentals in addition to advanced features of the language. These topics are prerequisite knowledge for the IBM Enterprise IT and Asset Management 7.1 Customizing Business Objects course and the IBM Integration Framework 7.1 Customization course.

Audience

This course is designed for developers, implementers, and administrators who want to learn how to design, build, and debug Java applications. This course is also appropriate for those who want to learn the more advanced Java topics presented in this course before attending the IBM Enterprise IT and Asset Management 7.1 Customizing Business Objects course or the IBM Integration Framework 7.1 Customization course.

IBM Tivoli Technical Education

The latest information about IBM Tivoli education offerings can be found online at

http://www.ibm.com/software/tivoli/education/

If you have any questions about education offerings, send an e-mail to the appropriate alias for your region:

• Americas: [email protected]

• Asia Pacific: [email protected]

• EMEA: [email protected]

Tivoli User Group Community

You can get even more out of Tivoli software by joining and participating in one of the 91 independently run Tivoli User Groups around the world. Learn about online and in-person Tivoli User Group opportunities near you at www.tivoli-ug.org.

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

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

• • •••

Preface

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

Course Objectives

Course Outline

The following outline is a high-level description of the contents of this course. Each unit has an overview presentation, and most units have a series of student exercises designed to reinforce the concepts presented. The course contains the following units:

• Unit 1: Objects and Object-Oriented Programming

This course covers the basics of the Java programming language. It also includes classes and constructs specific to customizing integration framework and related business objects. It does not include any graphical user interface or applet programming.

• Unit 2: Programming with Java

This unit examines Java’s architecture and the basics of compiling and running programs using the Java platform. Java allows you to write a program once and run it on any platform.

IBM Software Group | Tivoli software

2

Course Objectives

Upon completion of this course, you will be able to:• Identify object-oriented concepts and their advantages

• Write code using Java classes, operations, and program control structures

• Use Java to design and code classes based on inheritance, composition, and polymorphism

• Write and troubleshoot programs using the Eclipse IDE

• Use different classes included in the Java API (I/O, Collection Framework, Strings, and so on)

• Write code that uses serialization, remote method invocation (RMI), and threads

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

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

• • • ••

Preface

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

• Unit 3: Java Basics and Operators

This unit covers basic Java programming constructs and concepts.

• Unit 4: Java Basics and Programming Syntax

This unit covers the basics of the Java programming language and syntax.

• Unit 5: Classes, Constructors, and Strings

This unit examines the difference between classes and objects, and how objects are constructed. The String class and its methods are introduced.

• Unit 6: Java Exceptions, I/O, and Inheritance

This unit covers access control for data and methods in more detail, in addition to implementing inheritance and polymorphism with abstract classes and interfaces. You will also implement Java exception handing and Java I/O basics.

• Unit 7: Design Patterns, Interfaces, and the Collections Framework

This unit covers design patterns, interfaces, and the Java Collections Framework.

• Unit 8: Strings, Arrays, and Collection Classes

This unit examines some of the Java Collection classes introduced in Unit 7 in more detail.

• Unit 9: Threads

This unit focuses on extending the Thread class to create multiple threads, and implementing the Runnable interface.

• Unit 10: Serialization and Remote Method Invocation

This unit covers object serialization and Remote Method Invocation. Using serialization, you can save and reconstruct an object’s state. This process is used when implementing Remote Method Invocation.

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

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

• • •••

Preface

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

Typographical Conventions

In this course, the following typographical conventions are used.

Product Information

Product Documentation

In some cases IBM Tivoli product documentation is available in the classroom or on the Instructor Resources CD. For access to documentation outside the classroom environment, visit the IBM Web site.

Convention Usage

BoldCommands, keywords, file names, authorization roles, URLs, or other information that you must use literally appear in bold.

ItalicsVariables and values that you must provide appear in italics. Words and phrases that are emphasized also appear in italics.

Bold Italics New terms appear in bold italics when they are defined in the text.

MonospaceCode examples, output, and system messages appear in a monospace font.

>In this manual, the arrow character is used as a path arrow. The arrow indicates the path to the named window.

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

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

• • • ••

Preface

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

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

• • • ••

1-1

Unit 1: Objects and Object-Oriented Programming

© 2009 IBM Corporation

Unit 1: Objects and Object-oriented Programming

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Introduction

This course covers the basics of the Java programming language. It also includes classes and constructs specific to customizing integration framework and related business objects. It does not include any graphical user interface or applet programming.

Objectives

IBM Software Group | Tivoli software

2

Objectives

Upon completion of this unit, you will be able to:Describe the following basic concepts of object-oriented programming:– Abstraction– Encapsulation– Inheritance– Polymorphism

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Evolution to Objects

Large-scale software programs today are highly complex. Over time, the increasing complexity of these systems gradually led to the need for a powerful, effective software solution. That solution was object-oriented programming.

Complex systems, whether large businesses, public organizations, a cell phone, or a hospital, can be modeled as objects.

IBM Software Group | Tivoli software

3

Evolution to Objects

• Today’s business solutions are complex

• Objects can reflect the components of a complex solution

• Objects are used to model systems and their components

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Software Evolution

Software evolution defines the process by which programs change and adapt. Programming paradigms have undergone major shifts in the past 50 years to handle the complexity of software development.

Modular programming allowed programs to branch to another part of the program.

Structured programming used a top-down design model and the overall program structure maps to separate subsections. A function or set of similar functions were coded in separate modules or submodules.

Later, stored procedures, a subroutine available to applications accessing a relational database system, provided additional functionality.

In the mid-1980s, object-oriented programming became the industry standard using classes written in C++. Ten years later, the Java programming language was introduced. Its ability to be written once and run on multiple platforms has made Java the current programming language of choice.

The older languages did not enforce any property or method boundaries, which often resulted in unwanted side effects. Variables were changed or affected in unexpected ways, and the code was difficult to understand and maintain.

IBM Software Group | Tivoli software

4

Software Evolution

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Modeling Objects

Complex systems exist everywhere. They can be independent or they can interact with defined dependencies. Objects represent these systems.

An object can be used to model anything, such as a car engine, the human body, or a large-scale organization.

IBM Software Group | Tivoli software

5

Modeling Objects

• Objects are everywhere

• Objects can be independent

• Objects can interact

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Everything Is an Object

Anything can be modeled as an object. For example, a car engine with multiple interacting parts can be represented as an object that contains a collection of interacting objects.

A cell (of the organic variety) also can be represented as an object. It has unique characteristics and can interact with other cells, because complex organisms are multicellular, with cooperative organ systems that perform complex activities.

A collection of objects is itself an object. A list is an object, and every object contained in the list is also an object.

IBM Software Group | Tivoli software

6

Everything Is an Object

• Anything can be modeled as an object

• A collection of objects is itself an objectCar engine

Hospital

Home theater system

• The contents of a collection are objectsCar engine contains an ignition, starter, and battery object

Hospital contains doctor, patient, lab test, and test request objects

Home theater system contains a DVD, speaker, and screen object

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Object Hierarchy

Consider that a human body consists of many structures, including muscle, blood, and nerve. Each of these structures is further composed of a collection of cells, and inside each cell is yet another level of complexity. The parts form a hierarchy, and each level of this hierarchy embodies its own complexity. This arrangement can be represented as a hierarchy of objects.

A hospital could contain a laboratory, and the laboratory could be separated into a blood laboratory, an X-ray laboratory, a pathology laboratory, and an ultrasound laboratory.

Object hierarchies model the specialization of objects.

IBM Software Group | Tivoli software

7

Object Hierarchy

• Represents specialization of a more basic object

• Parent, base class, or superclass

• Child, subclasses, orderived classes

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Similar Objects

Objects might have a common interface but a dissimilar function.

For example, a saw and a table knife can both cut, and they both have a blade and handle, but their purpose is functionally different.

With object-oriented programming, you can use this commonality between otherwise unrelated objects and treat them identically.

IBM Software Group | Tivoli software

8

Similar Objects

• Common interface

• Functionally similar but different purpose

• Both objects have a blade and can cut

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Keys to Object-Oriented Technology

The objects themselves are the building blocks that provide the advantages of object-oriented programming. The power of Java lies in its use of object hierarchies and establishment of well-defined interaction between the objects.

IBM Software Group | Tivoli software

9

Keys to Object-Oriented Technology

• Objects

• Interaction between objects

• Hierarchy of objects

• Object composition

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Characteristics of an Object

An object models anything that is a part of an entity, or the entity itself.

Objects are described by their behavior and state. An object has methods, and its methods reflect behavior. An object also contains variables, and its variables reflect its state.

Most objects are dependent. They typically are part of another object, or they collaborate with other objects.

IBM Software Group | Tivoli software

10

Characteristics of an Object

• Any object can be anything that models a thing: a truck, a car, or a bank statement

• An object has two aspects: state and behavior

• An object’s methods reflect an object’s behavior

• An object’s variables reflect an object’s state

• Most objects act as part of a system: a sound system, a human body, or an engine

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Car Object

An car object might contain an engine and a chassis, travel at a particular speed in a certain direction, and contain a specific amount of fuel. These characteristics represent the car’s properties. They are called data members, attributes, fields, variables, or state.

The behavior of the car might include starting, stopping, and turning. Behaviors are called functions, methods, or member functions. These actions represent the car object’s functionality.

IBM Software Group | Tivoli software

11

Car Object

• An object has attributesAttributes, data members, fields, properties, data

• An object has functionalityFunctions, methods, behaviors, member functions

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

A Class Is the Blueprint

A class serves as a template or blueprint for an object. There might be tens of thousands of cars that were created to match a design blueprint and are exactly the same. A single car is an instance of the class of objects known as car. A class is the blueprint (or template) from which individual objects are created.

The following Car class is a possible implementation of a car:

class Car {

String color;String engineType;int numberDoors = 4;

void start() {...}

void stop() {...}

void turn() {}

}

IBM Software Group | Tivoli software

12

A Class Is the Blueprint

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

The variables represent the object’s state, and the methods (functions) allow the object to interact with other objects.

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Classes and Objects

A class is a description of the objects that it represents. A class is used to instantiate (create an instance of) an object. A class is the blueprint or template of an object; it is not the actual object itself.

An object is an instantiation of a class. It models something in the real world. An object has data (states) and methods (behaviors) as defined for the class of objects to which it belongs.

A class defines a new data type. A char, boolean, int, String, or Array is a data type. The class Car creates another data type that can be used in the system.

IBM Software Group | Tivoli software

13

Classes and Objects

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

The Car Class

The Car class includes (or encapsulates) attributes and methods that all instances of a Car object will have. The class is made up of the properties and behavior that a Car object represents.

The following example creates an instance of a Car object:

class Car {private int aProperty;private int anotherProperty;

public void aMethod() {}

public void anotherMethod() {}

}

public class MainApplication {public static void main(String[] arg) {

Car carA = new Car();Car carB = new Car();

}

IBM Software Group | Tivoli software

14

The Car Class

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

An object has the properties and behaviors defined in a class. After you write the class definition, you create one or more objects of that class using the new keyword.

To create a new object, type the word new followed by the name of the class, followed by parentheses. You can also specify arguments in the parentheses when creating new objects. When a new object is created, memory is allocated to hold the class variable plus additional memory required by all objects.

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

An Object’s Interface

An object’s interface is how it represents itself to other objects.

Note: Do not confuse this term with the concept of interfaces, which will be covered in Unit 7.

The methods and instance variables refer to functions and data that are stored in each object. All variables and methods can be referenced using dot notation. To reference an instance variable, type the object name, a dot, and then the variable name.

IBM Software Group | Tivoli software

15

An Object’s Interface

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Abstraction and Encapsulation

There are always clear boundaries between the outside and the inside of a specific level of abstraction. For example, the parts of a muscle work together to provide the functionality of the muscle as a whole. However, they have little or no direct interaction with the elementary parts of blood. There is a distinct separation among the parts at different levels of abstraction.

Abstraction and encapsulation are different but closely related object-oriented concepts.

• Abstraction denotes an entity that is represented with a specific level of detail, and unnecessary details are ignored.

• Encapsulation is the technique by which an object’s internal information and functionality is hidden, and what is visible is intended to be visible. You can get information from an object without all of its data being directly accessible.

IBM Software Group | Tivoli software

16

Abstraction and Encapsulation

• Encapsulation and information hiding

• Data encapsulation versus data abstraction

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Data Abstraction

All parts at the same level of abstraction interact in well-defined ways. For example, at a high level of abstraction in a living body, muscle is controlled by the nervous system. At lower levels of abstraction, muscle interacts with blood, which transports nutrients to the muscles. The muscles in turn use the nutrients provided by the blood to produce energy and respond to nerve stimuli.

In a similar manner, a car engine contains parts that interact in a well-defined way. An ignition switch responds to the turn of a key. Battery voltage creates a magnet effect inside the solenoid. When this connection is completed, current flows to start the engine.

Every object in these processes haves characteristics and well-defined functionality. The highest level of abstraction is the engine itself. The next level could be a few components. The lowest level could be millions of objects representing aluminium atoms.

IBM Software Group | Tivoli software

17

Data Abstraction

• Data abstraction versus levels of abstraction

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Inheritance and Composition

Good object-oriented design includes establishing relationships between classes. Classes are usually related through inheritance or composition.

A car is composed of many objects. It has an engine object, a chassis object, and so on. The human body is also composed of many objects. The relationship is one of composition and is characterized by a has-a relationship.

A Prius™ is a type of car. The relationship is one of inheritance and is characterized as an is-a type, which can be modeled with a hierarchical diagram.

Inheritance is a way of reusing behavior and data. Similar classes of objects can be organized into categories to form class hierarchies. The subclasses can use the behavior of higher classes (superclasses) in the hierarchy.

IBM Software Group | Tivoli software

18

Inheritance and Composition

• Inheritance is an is-a relationship between objects

• Composition is a has-a relationship between objects

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Subclasses

Classes can be derived from other classes. The derived class is called a subclass (or child class). The class from which it is derived is called the superclass (or parent class).

A subclass inherits properties and behavior from all of its parent classes. The term superclass refers to the direct parent, and all of the parent classes, of a class.

Use the extends clause in your class declaration to create a subclass of another class. As a subclass, your class inherits member variables and methods from its superclass in addition to adding its own. The subclass can use the inherited items from the superclass as is, or the subclass can hide variables or override methods inherited from its superclass.

In Java, all classes are derived from some root class. The topmost class from which all classes are derived is the Object class, which is defined in java.lang.

As the root of the class hierarchy, all objects inherit directly or indirectly from the Object class.

IBM Software Group | Tivoli software

19

Subclasses

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Object Interaction

Typically, individual objects are each responsible for a small part in a single larger process. There might be centralized objects that directly coordinate the activities of lower-level objects. Some objects might act as independent agents, each of which might show highly complex behavior and might contribute to many higher-level functions. High-level functionality is realized through the mutual cooperation of meaningful collections of objects.

A business can be a complex system: Multinational corporations contain companies, which are made up of divisions, which contain branches, and so on. The relationships among the various parts of a large organization are like those found among the cells in a living system. The processes of employee interaction and the sharing of common facilities to accomplish their tasks are defined and enforced with restrictive boundaries and business rules.

IBM Software Group | Tivoli software

20

Object Interaction

• Object design is about behavior

• Object design emphasizes the interplay between objects

• Objects have responsibilities

• Objects act independently and cooperatively

• Object relationships and interaction determine design

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Representing an Entity with Objects

Drawing an analogy between objects and a car engine or human cells can help you better understand this concept. A car engine encapsulates its complexity under the vehicle hood. The human cell encapsulates its internal complexity behind a cell membrane. The car engine components communicate through electrical messages or signal to each other. Cells communicate by sending chemical signals, each uniquely coded to elicit a particular response from a cell when it penetrates the cell’s membrane.

Similar to the car engine or cell membrane, an object’s interface hides the object’s internal complexity from the outside world. Communication with the object is achieved by sending preestablished messages through the interface.

IBM Software Group | Tivoli software

21

Representing an Entity with Objects

• Object complexity should be abstracted from user

• Complexity is encapsulated within the object itself

• Object’s interface should hide its internal complexity

• Object components communicate by sending messages and requests to each other

• Communication is established through the object interface

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Classes and Interfaces

A class definition is a template from which objects can be created. A class definition includes the variables (state information) and the capabilities (behaviors or methods) for instances of that class. The class definition defines how an object (instance) of that class behaves, but the class definition is not an object.

An interface is similar to a class but it has no instances. Interfaces are used to facilitate the sharing of behavior among similar, more specialized classes. They are also used for sharing behavior between objects that do not have a class relationship.

IBM Software Group | Tivoli software

22

Classes and Interfaces

• A class definition is a template

• The class definition is not an object

• An interface is similar to a class:Cannot be instantiated

Models similarities between otherwise unrelated objects

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Object Interaction and Methods

Methods are how objects communicate. An object makes a request from another object by sending a message in the form of a method call.

There are two types of methods: instance and static.

• Instance methods are associated with an instance of an object. These methods use the instance variables of the object.

From outside the defining class, an instance method is called by using an object name as a prefix, such as:

object1.setText("Hello");

• Static methods are associated with the class itself. They do not use instance variables of any object of the class they are defined in.

A static method is called by using a class name as a prefix, such as:

Math.min(i,j);

IBM Software Group | Tivoli software

23

Object Interaction and Methods

There are two types of methods: instance and static.• Instance methods are associated with an instance of the object:

object1.setText("Hello");

• Static methods are associated with the class itself:Math.min(i,j);

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Class Example

Classes are composed of a name, attributes, and methods. The slide illustrates an example of a class.

IBM Software Group | Tivoli software

24

Class Example

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Object-Oriented Concepts

All object-oriented programming languages provide mechanisms that help you implement the object-oriented paradigm. These mechanisms are encapsulation, inheritance, and polymorphism.

• Encapsulation is the means to get information from an object without its data being directly accessible.

• Inheritance is a way of reusing behavior and data within a class. Similar classes of objects can be organized into categories to form class hierarchies. The subclasses can use the behavior of higher classes (superclasses) in the hierarchy.

• With the polymorphism feature, one interface can be used for a general set of actions. The specific action is determined by the exact context of the situation.

IBM Software Group | Tivoli software

25

Object-oriented Concepts

Fundamental mechanisms provided by object-oriented languages:

Encapsulation

Inheritance

Polymorphism

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Encapsulation and Information Hiding

The basis of encapsulation is the class. A class defines the data and behavior to be shared by a set of objects. Each object of a class contains the structure and behavior defined by that class. A class is a logical construct. An object has physical reality.

When you create a class, you specify the methods and data that constitute that class. The data defined by the class is referred to as member variables or instance variables. The operations on that data are referred to as methods. The methods define how the member variables can be used.

The purpose of a class is to encapsulate complexity. There are mechanisms for hiding the complexity of the implementation inside the class. Each method or variable in a class can be marked public or private. The public interface of a class represents everything that other objects can access. The private methods and private data can only be accessed by methods of the class itself. Code that does not belong to the class cannot access a private method or variable.

The private data members of a class can only be accessed by other parts of your program through the public methods of the class. You can prevent undesirable actions by designing the public interface to limit exposure to a class.

IBM Software Group | Tivoli software

26

Encapsulation and Information Hiding

• Basis of encapsulation is the class

• Methods define how the variables are used by other objects

• The class encapsulates complexity of the implementation

• The methods provide the class interface and ensure that unwanted actions do not occur

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Inheritance

Inheritance is the process by which one object acquires the properties of another object. This important process supports the concept of hierarchical classification. As mentioned earlier, many relationship are made manageable by hierarchical (that is, top-down) classifications.

Dog is part of the classification Mammal, which is under the larger classification Animal. Without the use of hierarchies, each object would have to define all of its characteristics explicitly. However, by using inheritance, an object must only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. Thus, the inheritance mechanism makes it possible for one object to be a specific instance of a more general case.

IBM Software Group | Tivoli software

27

Inheritance

• Inheritance is a way for objects to define relationships with each other

• Objects inherit characteristics from a parent object

• Parent object must be able to pass its state and methods to its children

• Parent and child objects must have characteristics in common

• Child objects (subclasses) are more specialized versions of the parent object (superclass)

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Class Hierarchy

Most people naturally view the world as made up of objects that are related to each other in a hierarchical way, such as animals, mammals, and cows. To describe animals in an abstract way, you would say that they have some attributes, such as size, intelligence, and type of skeletal system. Animals also have certain behavioral aspects; they eat, breathe, and sleep. This description of attributes and behavior is the class definition for animals.

To describe a more specific class of animals, such as mammals, you would use more specific attributes, such as type of teeth, and mammary glands. This category is known as a subclass of animals, where animals are referred to as mammals’ superclass.

Because mammals are simply more precisely specified animals, they inherit all of the attributes from animals. A deeply inherited subclass inherits all of the attributes from each of its ancestors in the class hierarchy.

IBM Software Group | Tivoli software

28

Class Hierarchy

• Real-world objects can form natural hierarchies

• A base class (superclass) can be described in an abstract way

• A more specialized class can be described in a more concrete way

• The specialized class inherits everything from the more general classes in the hierarchy

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Polymorphism

With the polymorphism (meaning many forms) feature, one interface can be used for a general class of actions. The specific action is determined by the exact nature of the situation.

Polymorphism is one of the fundamental principles of object-oriented programming. You must understand inheritance before learning about polymorphism.

IBM Software Group | Tivoli software

29

Polymorphism

• Means many forms

• One interface can be used to specify a general action

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

One Interface, Multiple Methods

More generally, the concept of polymorphism is often expressed by the phrase “one interface, multiple methods.” This phrase means that you can design a generic interface to a group of related activities. Being able to use the same interface to specify a general class of action helps reduce complexity.

It is the compiler’s job to select the specific action (that is, method) as it applies to each situation. You, the programmer, do not have to make this selection manually. You must only remember and use the general interface.

IBM Software Group | Tivoli software

30

One Interface, Multiple Methods

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Polymorphism and Inheritance

To review, inheritance allows a class to be defined as a specialization of another class. The more specialized class is a subclass or a child class of the more general class. The class from which the child class is derived is also called the parent class.

Inheritance means that the subclass inherits the properties and methods of the parent class.

When working with class hierarchies, you do not have to treat an object as the specific type that it is. Instead, you can treat it as its base type. Using this capability, you can write code that does not depend on specific types, which is the mechanism that allows polymorphism to work.

IBM Software Group | Tivoli software

31

Polymorphism and Inheritance

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Shape Example

Suppose you have a program that requires three types of shapes: one shape for circles, one for triangles, and one for squares. The algorithm that implements each shape is the same, even though the data being stored differs. In a non–object-oriented language, you would have to create three different sets of shape routines, with each set using different names. However, because of polymorphism, in Java you can specify a general set of shape routines that all share the same names.

In this hierarchy, Circle, Triangle, and Square are specialized forms of Shape. They also share some basic behavior. If Shape has a method called draw(), then Circle, Triangle, and Square inherit this method. The inherited draw() method can be overridden in the child class. This method overriding illustrates the potential of polymorphism.

IBM Software Group | Tivoli software

32

Shape Example

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Explaining Polymorphism

Because Circle, Triangle, and Square are derived from Shape, they are themselves Shapes. Therefore you can write the following code, which is called upcasting:

Shape shape = new Circle();Shape shape = new Triangle();Shape shape = new Square();

You can store a Rectangle object in a Shape object reference because a Rectangle is also a Shape. The reverse is not true: a Shape is not always a Rectangle.

You might have a Shape object reference containing an object that is a subclass of Shape, but you might not know whether the object is a circle, triangle, or line. However, when you call the draw() method of Shape, the correct subclass implementation will be called. For example, if the object is a Circle, the draw() method in the Circle class is invoked. If it is a Square object, then the draw() method in the Square class is called.

IBM Software Group | Tivoli software

33

Explaining Polymorphism

Shape shape = new Circle();

Shape shape = new Triangle();

Shape shape = new Line();

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Key Concepts and Elements

Key concepts of object-oriented programming are abstraction, encapsulation, inheritance, and polymorphism. With the Java programming language, you can use these object-oriented constructs.

Key elements of object-oriented programming are the objects themselves, the interaction between the objects in the form of messages, and the object hierarchy. Through the object hierarchy, the potential for inheritance and polymorphism can be realized.

IBM Software Group | Tivoli software

34

Key Concepts and Elements

• Key concepts:AbstractionEncapsulationInheritancePolymorphism

• Key elements: ObjectsInteraction between the objectsObject hierarchy

• The object hierarchy provides the potential for inheritance and polymorphism

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Review Questions

1. What is an object?

2. What is inheritance?

3. What is polymorphism?

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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

Review Answers

1. What is an object?

An object is an instance of a class.

2. What is inheritance?

Inheritance is the mechanism that allows a class to inherit the properties and behavior of another class.

3. What is polymorphism?

Polymorphism is the ability to assign different behaviors depending on different context.

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

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

• • •••

Unit 1: Objects and Object-Oriented Programming

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

Summary

IBM Software Group | Tivoli software

35

Summary

You should now be able to:Describe the following basic concepts of object-oriented programming:– Abstraction– Encapsulation– Inheritance– Polymorphism

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

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

• • • ••

Unit 1: Objects and Object-Oriented Programming

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 training

• • • ••

2-1

Unit 2: Programming with Java

© 2009 IBM Corporation

Unit 2: Programming with Java

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

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

• • • ••

Unit 2: Programming with Java

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

Introduction

This unit examines Java’s architecture and the basics of compiling and running programs using the Java platform. With Java, you can write a program once and run it on any platform.

Objectives

IBM Software Group | Tivoli software

2

Objectives

Upon completion of this unit, you will be able to:Describe how the Java architecture works to provide platform independence using:– The Java programming language– The .class file– API libraries– Java Virtual Machine (JVM) and the just-in-time (JIT) compilerDescribe how the Java platform is comprised of the JVM and API libraries Describe how the Java platform forms a compile and runtime environment

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

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

• • •••

Unit 2: Programming with JavaThe Java Programming Language

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

Lesson 1: The Java Programming Language

The Java programming language is object-oriented and platform-neutral. It supports multithreading, serialization, reflection, and many design patterns with its extensive and robust application programming interface (API).

The language is completely object-oriented. Code must be within a class definition, and that includes main().

The language is robust and secure. Exception handling is built into the language and all data types must be explicitly declared. There are no pointers to memory and programs run inside their own virtual machine. The Java Virtual Machine (JVM™) handles memory management with automatic garbage collection. Linking of data and methods is done at run time using dynamic binding, so new classes can be loaded during program execution.

The language was designed with multithreading and networking in mind. Many classes are included in the API libraries to develop multithreaded applications and Internet communication programming.

IBM Software Group | Tivoli software

3

The Java Programming Language

• Object oriented

• Platform independent

• Compiled and interpreted

• Robust and secure

• Automatic garbage collection

• Dynamic

• Multithreaded

• Networking

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

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

• • • ••

Unit 2: Programming with JavaThe Java Programming Language

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

The Java Platform

Java code is compiled into bytecode that is then interpreted by a JVM. These two steps provide extensive code checking and improved security. The compiled code can be run on any machine for which a virtual machine has been written.

Although the write-once-run-anywhere claim has not been achieved completely, Java comes closer to this platform independence ideal than any other language. Some adjustments are usually required for different platforms.

When a Java application is running, it calls methods from the API libraries, which provide access to system resources such as networking and I/O. The JVM and the API libraries form a compile-and-execution environment that is known as the Java platform.

IBM Software Group | Tivoli software

4

The Java Platform

• Write a program and save it in a file with a .javaextension

• Code is compiled into bytecode and a .class file is generated

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

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

• • •••

Unit 2: Programming with JavaThe Java Programming Language

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

Platform Independence

Java achieves platform independence by compiling the source code (someFile.java) into an intermediate representation. This method is unlike the typical compilation of machine-dependent opcode (operation code), which is laid out in the specific instruction set for the hardware platform. This intermediate representation is called bytecode and it is designed to run in architecture provided by the Java Virtual Machine. The JVM loads class files and executes the bytecode.

IBM Software Group | Tivoli software

5

Platform Independence

• Source code is compiled into bytecode

• The .class files that contain the bytecode are loaded into the JVM

• The JVM executes the bytecode

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

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

• • • ••

Unit 2: Programming with JavaThe Java Programming Language

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

Just-in-Time Compiler

Just-in-time compilation is used to improve runtime performance. The just-in-time (JIT) Java compiler is part of the JVM. It converts bytecode at run time into native machine code for a particular system.

The JIT compiler compiles bytecode as it executes. Just-in-time refers to the fact that the JIT compiler only compiles code that is ready (just in time) to be executed. Runtime performance is improved because only code that is executed is compiled.

The JIT compiler maintains a table called the V-table that contains the addresses of the class methods in the bytecode. The V-table contains both a table with the addresses of the bytecode and another table of the native code from the bytecode.The first time that a method executes, it is converted to the native code by the JIT compiler. The address of the native code for that particular method is then stored. For subsequent calls to that method, the native code is called directly and execution speed is improved.

IBM Software Group | Tivoli software

6

Just-in-Time Compiler

• Used to improve runtime performance

• Part of the JVM

• Converts bytecode to native machine code

• V-table contains addresses of class methods

• Contains addresses of bytecode and native code

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

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

• • •••

Unit 2: Programming with JavaThe Java Programming Language

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

Language Features

The rapid adoption of Java owes a great deal to its syntax, which is like that of C++. Unlike C++, the Java language does not allow pointers, operator overloading, multiple inheritance, or explicit memory management.

The Java environment includes hundreds of classes and methods in its standard library. There are classes for language features such as strings, threads, arrays, exception handling, date and time functions, container classes, input and output classes, and networking classes.

Java was designed with security in mind. There is bytecode verification on untrusted code and there is no access to the file system. The SecurityManager class controls security restrictions and you can attach a digital signature to the code.

Java has a lower potential for programming errors than some other languages, such as C++. Strings are immutable. The Java compiler checks whether all local variables have been initialized before they are read.

IBM Software Group | Tivoli software

7

Language Features

• Everything is an object

• Automatic memory management

• Troublesome features eliminated:No header files or preprocessor

No pointers

No operator overloading

No multiple inheritance

• Supports networking

• Secure

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

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

• • • ••

Unit 2: Programming with JavaThe Java Programming Language

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

JDK, JRE, and JVM

The Java Developer Kit (JDK™) contains the tools necessary to develop Java programs. These tools include the Java compiler (javac.exe) and the application launcher (java.exe). The JDK also contains the Java Runtime Environment ™ (JRE™) to run the programs.

• javac.exe converts Java programs to bytecode.

• java.exe opens a JRE, loads the class, and begins execution with the main() method.

The Java Runtime Environment contains the Java virtual machine (JVM), class libraries, and supporting files to run the program. The JVM runs the program and uses the class libraries and files that the JRE provides.

The JVM interprets the compiler-generated bytecode into machine code that is compatible with the machine’s underlying operating system and hardware architecture. The JVM implementations might differ on speed and performance. Features that are not in the Java specification can be implemented differently. For example, garbage collection is JVM dependent.

IBM Software Group | Tivoli software

8

JDK, JRE, and JVM

• JDK– Java Developer Kit– Contains tools to develop programs and JRE to run them

• JRE– Java Runtime Environment– Contains the JVM, class libraries, and supporting files

• JVM– Java Virtual Machine– Interprets byte code into machine code for the underlying operating

system

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

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

• • •••

Unit 2: Programming with JavaThe Java Programming Language

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

Java API

The Java programming language application programming interfaces (APIs) are contained in the JDK and JRE. There are three editions:

• Java ME (Micro edition)

• Java SE (Standard edition)

• Java EE (Enterprise edition)

IBM Software Group | Tivoli software

9

Java API

• Java ME: Micro edition

• Java SE: Standard edition

• Java EE: Enterprise edition

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

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

• • • ••

Unit 2: Programming with JavaThe Java Programming Language

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

Types of Java Programs

You can build many types of programs in Java. For example:

• Applications are programs with a main() that run independently. Applications can have either a command-line interface (CLI) or a graphical user interface (GUI).

• Applets are programs that run in Web pages.

• Servlets are programs that run on a Web server.

• JavaBeans™ are components that adhere to a specification and can be used by other programs.

IBM Software Group | Tivoli software

10

Types of Java Programs

• Applications

• Applets

• Servlets

• JavaBeans

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

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

• • •••

Unit 2: Programming with JavaDevelopment Environments

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

Lesson 2: Development Environments

An integrated development environment (IDE) simplifies the task of creating Java code. A Java editor is another option. Either option offers more than opening a text editor, typing your code, compiling the .java file with javac.exe, and running the class file with java.exe.

Editors are simple to use. A Java editor will highlight Java syntax, indent, track braces and parentheses, and compile within the editor. The IDEs are more complex. They will write code and are tightly integrated to a compiler or application server. They also can include graphical development tools for debugging, compile and runtime options, and refactoring.

Eclipse is the most popular Java IDE. It is a free and open-source IDE that is available for download from www.eclipse.org.

IBM Software Group | Tivoli software

11

Integrated Development Environments (IDEs)

• IBM Rational® Application Developer

• EclipseOperates under an open source paradigm

Download IDE at www.eclipse.orgMore information available at www.eclipse.org

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

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

• • • ••

Unit 2: Programming with JavaDevelopment Environments

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

Using the Eclipse IDE

The Eclipse Integrated Development Environment is a development environment that can be further customized with plug-ins. Plug-ins are created to do specific tasks that a development group might need to create a software product.

You can download Eclipse at www.eclipse.org. After you download Eclipse, extract the zipped file into whatever directory you want. To run Eclipse after extracting the files, launch the eclipse.exe executable file in the top-level Eclipse directory.

Eclipse stores all its files in a directory called a workspace. When you run Eclipse for the first time, you will be prompted for a workspace location. Your project files are saved in this directory.

The Eclipse interface contains editors and views. Different editors can be opened depending on the file type selected. You can specify which editor or application is opened when a file is selected by clicking Window > Preferences > General > Editors > File Associations. A view represents a single task in the Eclipse environment. Any number of views can be open at one time. To open a view, click Window > Show View> Other to select from a complete list of views.

In Eclipse, the graphical user interface layout can be changed to one of many options by selecting Window > Open Perspective. A perspective provides a set of functionality that is specific to a task. For example, the Java perspective is associated with creating a Java application.

IBM Software Group | Tivoli software

12

Using the Eclipse IDE

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

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

• • •••

Unit 2: Programming with JavaDevelopment Environments

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

Creating Projects, Classes, and Interfaces

Use the context menus, the main menu, or icons to create new projects, class files, and interfaces.

To remove a class file from a project, right-click the file in the Package Explorer and select Delete.

Note: Removing a Java file from a project will delete the Java file from disk. Deleting a project is safer.

You can import both Java files and jar (Java ARchive) files. Select your project, right-click, and select Import. Whether you are importing a file system or a compressed file, a directory structure is displayed. You can select the folders or individual files you want to import.

Other options include exporting files and creating a jar file.

IBM Software Group | Tivoli software

13

Creating Projects, Classes, and Interfaces

Use either context menus or main menu to create and manage projects, classes, and interfaces

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

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

• • • ••

Unit 2: Programming with JavaDevelopment Environments

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

Running Programs

There are several ways to run a program. If the program has never been run before, you must create a run configuration.

IBM Software Group | Tivoli software

14

Running Programs

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

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

• • •••

Unit 2: Programming with JavaDevelopment Environments

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

Run Configurations

If there are any command-line arguments, enter them in the arguments text box on the Arguments tab. You can add jar files to the classpath on the Classpath tab. Click Run to run the program.

If a run configuration already exists, you can select the configuration by clicking the arrow on the toolbar icon. Clicking the green button will run the last configuration that was launched.

IBM Software Group | Tivoli software

15

Run Configurations

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

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

• • • ••

Unit 2: Programming with JavaDevelopment Environments

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

Debugging

Two tabs in the upper right corner of the IDE facilitate switching between the Java and Debug perspectives.

IBM Software Group | Tivoli software

16

Debugging

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

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

• • •••

Unit 2: Programming with JavaDevelopment Environments

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

Debugging Programs

This slide shows the Debug perspective. The top left window displays all running applications and the call stack. On the top right are the program variables, breakpoints, and expressions.

IBM Software Group | Tivoli software

17

Debugging Programs

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

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

• • • ••

Unit 2: Programming with JavaDevelopment Environments

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

Breakpoints

A breakpoint is a debugging mechanism that indicates a point in the program where you want the program to stop.

IBM Software Group | Tivoli software

18

Breakpoints

• Used to pause program execution at a specified point

• Right-click side panel and select Toggle Breakpoint

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

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

• • •••

Unit 2: Programming with JavaDevelopment Environments

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

Setting Breakpoints

To set a breakpoint, go to the line of code on which you want to set it. Right-click the blue bar where the line is and select Toggle Breakpoint.

IBM Software Group | Tivoli software

19

Setting Breakpoints

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

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

• • • ••

Unit 2: Programming with JavaDevelopment Environments

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

Debug Options

In this slide, the program has stopped executing. In the upper left window is the main program and what it has called. In the top right window are the local variables, breakpoints, and expressions. The line with the breakpoint is green, and is the next line of code that will be executed.

There are several debugging options:

• Step into: With this option you will go to the next line of the code; if it is a function call it will go into that function.

• Step over: To keep stepping without going into a function, use step over to execute the line and move on without entering the function.

• Step return: Assume that you used step into to get into a function call and you want to return from the function. Use the step called return. This step will finish executing that function and place you on the next executable line after the function.

• Resume: Click the Resume icon in the top left window if you are done stepping through the code and want to finish the program.

• Terminate: To quit debugging, or if the program hangs, click the red Terminate icon located to the right of the Resume button in the top left window.

IBM Software Group | Tivoli software

20

Debug Options

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

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

• • •••

Unit 2: Programming with JavaDevelopment Environments

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

Student Exercise

Open your Student Exercises book and perform the exercises for this unit.

IBM Software Group | Tivoli software

21

Student Exercise

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

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

• • • ••

Unit 2: Programming with JavaDevelopment Environments

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

Review Questions

1. What is the difference between the JDK and the JRE?

2. What is the difference between the JRE and a JVM?

3. At what Web site can you find downloads and tutorials for the Eclipse IDE?

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

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

• • •••

Unit 2: Programming with JavaDevelopment Environments

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

Review answers appear on next page.

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

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

• • • ••

Unit 2: Programming with JavaDevelopment Environments

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

Review Answers

1. What is the difference between the JDK and the JRE?

The JDK is the Java Development Kit, which you can use to develop Java-based software. The JRE is the Java Runtime Environment. The JRE is an implementation of the Java virtual machine, which executes Java programs.

2. What is the difference between the JRE and a JVM?

The JVM (Java virtual machine) is the definition of the abstract, computational engine that executes Java bytecode. The JRE (Java Runtime Environment) is a specific implementation of the JVM.

JVM is an abstract definition and the JRE is a specific implementation.

3. At what Web site can you find downloads and tutorials for the Eclipse IDE?

www.eclipse.org

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

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

• • •••

Unit 2: Programming with JavaDevelopment Environments

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

Summary

IBM Software Group | Tivoli software

22

Summary

You should now be able to:Describe how the Java architecture works to provide platform independence using:– The Java programming language– The .class file– API libraries– Java Virtual Machine (JVM) and the just-in-time (JIT) compilerDescribe how the Java platform is comprised of the JVM and API libraries Describe how the Java platform forms a compile and runtime environment

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

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

• • • ••

Unit 2: Programming with JavaDevelopment Environments

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

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

• • • ••

3-1

Unit 3: Java Basics and Operators

© 2009 IBM Corporation

Unit 3: Java Basics and Operators

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

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

• • • ••

Unit 3: Java Basics and Operators

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

Introduction

This unit covers basic Java programming constructs and concepts.

Objectives

IBM Software Group | Tivoli software

2

Objectives

Upon completion of this unit, you will be able to:

Describe the Java language basics

– Variable types– Data types– Object referencesOperators– Mathematical operators– Logical operators– Relational operators

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

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

• • •••

Unit 3: Java Basics and OperatorsClass Structure

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

Lesson 1: Class Structure

The first line starts with the reserved word public. This word indicates that other objects can use instances of this class. The reserved word class indicates that you are writing a new class.

In this case, MyClass is the class name and it is case-sensitive. It is a Java convention to capitalize the first letter of a class name. The next line is an opening brace ({) that marks the start of the class definition.

The next two lines are a declaration of two instance variables (or fields). Fields and methods can be declared private, protected, public, or package. If no access level is specified, the default access level is package. Neither of these two fields has an access level specified, so the default is in effect.

The next line is a constructor. The constructor looks similar to a function, but its name matches the class name and it does not have a return type. The constructor returns an instance of the class type.

The code for this class contains a no-argument constructor. It is not the default constructor. A default constructor is automatically generated for you by the Java compiler if your class does not include a constructor.

IBM Software Group | Tivoli software

3

Class Structure

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

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

• • • ••

Unit 3: Java Basics and OperatorsClass Structure

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

The next line is the specification of a method called method1. It returns a result of type int. An access level of public has been specified, so any other class can invoke this method. The second method is called method2. The reserved word void indicates that no result is returned.

Each Java statement ends with a semicolon (;).

A closing brace completes the object definition.

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

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

• • •••

Unit 3: Java Basics and OperatorsClass Structure

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

File Structure

Java source files must have the extension .java. This requirement is enforced by the Java tools.

Declare classes in individual files, with the file name matching the class name. Make sure that the capitalization of the file name and the class definition name inside the file match exactly.

Compiling the Java file will create a .class file with the bytecode for each class in the file. With the exception of small utility classes and inner classes, each class definition should be put into its own file.

IBM Software Group | Tivoli software

4

File Structure

• Files must have a .javaextension

• The file name should match the name of the class

• Usually one class definition per file

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

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

• • • ••

Unit 3: Java Basics and OperatorsClass Structure

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

Packages

A package is a collection of related classes and interfaces stored in a single directory that is named after the package. . Each file within that directory contains a package directive at the top of the file. A Java directive (unlike a Java statement) occurs outside the class definition.

A package can contain subpackages. For example, a package exercises can contain a subpackage called exer1. A class file within the subpackage exer1 would have the following directive at the top of the class file:

package exercises.exer1;

By convention, package names start with a lowercase letter.

IBM Software Group | Tivoli software

5

Packages

• Collection of related classes

• Files contain a package directive at the top

• A package can contain sub-packages

• Package names start with a lowercase letter

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

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

• • •••

Unit 3: Java Basics and OperatorsClass Structure

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

Package Example

The syntax for a package statement is:

package Package_Name;

A file can belong to a maximum of one package.

Packages are imported (accessed) by using dot notation.

IBM Software Group | Tivoli software

6

Package Example

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

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

• • • ••

Unit 3: Java Basics and OperatorsClass Structure

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

import Statement

The following statement will import the contents of the SayHello class located in the examples/hello directory:

import examples.hello.SayHello;

The SayHello class is contained in the SayHello.class file in the examples/hello directory. The SayHello.java file must be in a file that begins with:

package examples.hello;

IBM Software Group | Tivoli software

7

import Statement

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

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

• • •••

Unit 3: Java Basics and OperatorsClass Structure

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

import Options

All classes in the java.lang package are visible without an import.

The LinkedList class is in the util package, which is located in the java package. The wildcard character (*) can be used to specify that all classes within that package are available to your program, even if only one is used.

import java.util.*; // Make all classes visible

Classes can be specified explicitly upon import instead of using the wildcard character.

import java.util.LinkedList; // Make a single class visible

Alternatively, you can use the fully qualified class name without an import.

public java.util.LinkedList<XRayTest> listIn;

IBM Software Group | Tivoli software

8

import Options

• All classes in the java.lang package are visible without an import

• A wildcard option is available

import java.util.*;

import java.util.LinkedList;

public java.util.LinkedList<XRayTest> listIn;

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

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

• • • ••

Unit 3: Java Basics and OperatorsClass Structure

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

There are more than 150 packages and over 3000 classes and interfaces in Java 5. Some common (non-GUI) packages are described in the following table.

Package Name Description

import java.util.*; Collections, data structures, time classes, and so on

import java.io.*; I/O classes

import java.text.*; Some text formatting classes

import java.util.regex.*; Regular expression classes

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

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

• • •••

Unit 3: Java Basics and OperatorsClass Structure

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

Comments

Comments should always be included in a Java program. They can provide a useful overview of the programming logic. They can also serve to segment a program, identify key ideas, and provide other useful information.

A few well-placed comments can be useful to others trying to read and understand your code, especially complicated code. A declaration is a good place to write comments describing the variable and how it is used.

There are three types of comments used in Java:

• All characters from // to the end of the line are ignored.

// text

• All characters from /* to */ are ignored.

/* text */

• Comments for automatic documentation are usually called doc comments. They start with the three characters /** and continue until the next */.

/** text */

Each doc comment describes the element of the identifier that immediately follows it, and should not be used anywhere else in the code. Doc comments

IBM Software Group | Tivoli software

9

Comments

• Line comments// everything to the end of the line is a commenttotal = 0; // initialize total to 0

• Block comments/* Compiler ignores everything between the /* and *//* This is a multiple-line comment

This is the second line,

and this is another line

*/

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

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

• • • ••

Unit 3: Java Basics and OperatorsClass Structure

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

indicate that the enclosed text is a description of the declared item and should be included in automatically generated documentation.

Page 95: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsLanguage Basics

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

Lesson 2: Language Basics

A program is composed of:

• Variables

• Assignment statements

• Mathematical operators

• Automatic increment and decrement operators

• Relational operators

• Logical operators

• Execution control

Java statements must end with a semicolon.

IBM Software Group | Tivoli software

10

Language Basics

Page 96: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsLanguage Basics

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

Variables

Variables are used to hold program data. Data type determines the values that a variable can contain and the operations that can be performed on the variable.

Variable names are letters or digits from one to several characters long. The underscore is also used as part of a variable name for clarity. Java is case-sensitive, so testVariable and TestVariable are considered two different variables. By convention, variable names start with a lowercase character.

All variables must be declared before their use. The syntax for a variable declaration is:

possible_modifiers data_type variable_name;

The following statements declare x to be an integer and y to be the data type Boolean:

int x;Boolean y;

IBM Software Group | Tivoli software

11

Variables

• Data is stored in variables

• Variables can be custom, user-defined data types

• A class is a user-defined data type

• Variable names can be composed of alphanumeric and some special characters

• Variable name must not be a reserved word

• Variable declaration: possible_modifiers data_type variable_name;

Page 97: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsLanguage Basics

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

Variable Types

There are four variable types:

• Instance

• Class (or static)

• Local

• Parameter

An instance variable is unique to each instance of a class, as opposed to a class variable.

A class variable is a variable that has been declared with the static modifier. The static reserved word is used for a variable that has only one of the specified variables in existence, no matter how many instances of the classes have been created. Non-static fields are instance variables because there is one for each instance of the class.

Adding the keyword static in front of a variable declaration will create a static variable. The following example would create a static variable:

static int numberDoors = 4;

Adding the modifier final indicates that the variable will not be modified. The final variable can be given an initial value that will not change.

IBM Software Group | Tivoli software

12

Variable Types

• Instance variables

• Class variables

• Local variables

• Parameters

Page 98: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsLanguage Basics

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

Local variables are known and used only by the method in which they are declared. They cannot be used by other methods in the class. There is no special keyword to denote that a variable is a local variable. Local variables are declared in the same way as instance variables. Declaring the variable within a method makes it a local variable and determines its scope.

Local variables are not assigned a default value and must be initialized before they are used. Accessing an uninitialized local variable produces a compilation error.

A parameter list is a comma-separated list of variables passed to a method.

Page 99: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsLanguage Basics

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

Built-in Data Types

Java has an assortment of primitive data types. A primitive type is built into the language and named with a reserved keyword.

Java supports eight primitive data types:

• byte: An 8-bit signed two’s complement integer. The default value is 0.

• short: A 16-bit signed two’s complement integer. The default value is 0.

• int: A 32-bit signed two’s complement integer. This data type is the default choice for numeric data unless a larger range of values is neeeded. The default value is 0.

• long: A 64-bit signed two’s complement integer. The default value is 0L.

• float: A single-precision 32-bit IEEE floating point. Do not use this data type for currency or accounting functions requiring precision. The default value is 0.0f.

• double: A single-precision 64-bit IEEE floating point. The default value is 0.0d.

• boolean: A flag for true/false conditions. The default value is false.

• char: A single 16-bit Unicode character. The default value is \u0000.

Local variables are not assigned a default value by the compiler. You must initialize a local variable before it is used.

IBM Software Group | Tivoli software

13

Built-in Data Types

• byte

• short

• int

• long

• float

• double

• boolean

• char

Page 100: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsLanguage Basics

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

Wrapper Classes for Primitives

Each primitive data type has a wrapper class associated with it. The wrapper class wraps the primitive data type into an object of that class. For example, an Integer wrapper class holds an int variable, a Float wrapper class holds a float variable, and so on. The wrapper classes are part of the java.lang package. This package is imported by default.

Use the primitive types when there is no need for objects, because the primitive types might be faster than the corresponding wrapper types. They are never slower. Another reason to use the primitive type is the immutability of the wrapper types, which might make them difficult to use.

IBM Software Group | Tivoli software

14

Wrapper Classes for Primitives

Page 101: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsLanguage Basics

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

Primitives and References

The following statements illustrate the difference between a primitive data type and an object of a wrapper class:

int i = 5;Integer I = new Integer(12);

The first statement declares an int variable named i and initializes it to 5. The new operator is not necessary when declaring a variable of primitive type. The next statement instantiates an Integer object and the new operator is necessary. The object is initialized with the value 12. A reference to the object is assigned to the variable I.

The following example illustrates the difference between declaring and initializing a variable, and the instantiation of an object. The variable i holds a value of 5. The object variable I holds a reference to an object. Prior to Java 5, the data in the object is accessible only by using the access method of the Integer class.

int x = i; // variable x is assigned the value 5int x = I; // invalid statement (prior to Java 5)int x = I.intValue(); // returns int value of the object

IBM Software Group | Tivoli software

15

Primitives and References

• Primitives are not objects

• Primitives contain values

• Two variables and two different locations in memory– int x = 5;– int y = x;

• References point to memory locations

• Two references to the same memory location, but only one String object

– String s = “Hello”;– String t = s;

Page 102: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsLanguage Basics

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

Common Wrapper Methods

The following tables illustrate some common wrapper methods.

Constructor Description

Integer(i) Constructs an Integer object equivalent to the integer i

Integer(s) Constructs an Integer object equivalent to the String s

Static Method Return Value

parseInt(s) A signed decimal integer value equivalent to String s

toString(i) A new String object representing the integer i

Instance Method Return Value

byteValue() The value of this Integer object as a byte

doubleValue() The value of this Integer object as a double

floatValue() The value of this Integer object as a float

intValue() The value of this Integer object as an int

IBM Software Group | Tivoli software

16

Common Wrapper Methods

• Constructors

• Static (or class) methods – Act upon the class itself– The dot is preceded by the name of the class

• Instance methods – Acts upon an instance variable– The dot is preceded by the name of the instance variable

• Methods for wrapper classes can be found in Java API documentation

Page 103: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsLanguage Basics

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

Some Java classes include only instance methods or only static methods, and some include both. The Integer class includes both instance and static methods.

The following statement illustrates the usage of a static method:

int i = Integer.parseInt(someString);

The method parseInt() is a static method. It is not called through an instance of the class. The term Integer identifies the class that defines the method parseInt(). This is one of the differences between an instance method and a static method. In the case of an instance method, the dot is preceded by the name of an object variable. For a static method, the dot is preceded by the name of a class.

longValue() The value of this Integer object as a long

shortValue() The value of this Integer object as a short

toString() A String object representing the value of this Integer object

Instance Method Return Value

Page 104: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsLanguage Basics

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

Assignment Statements

Use the assignment operator (=) to assign the value of an expression to a variable.

You can also use the assignment operator to assign the value of an expression to a variable as it is being declared, which is called variable initialization. This variation of the assignment operator can be used to assign a value to a final (constant) variable.

Use the assignment operator to assign a value to the variable on the left of the assignment operator that is the same type as the right-hand expression. Otherwise, there will be an implicit conversion of the right type to the left type (such as float to int).

IBM Software Group | Tivoli software

17

Assignment Statements

• Assignments are made with the = symbol

• Variable can be assigned the value of a variable or expression

• Variable declaration:String s;int i;

• Assignment: s = “This is a string”;i = 5;

Page 105: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsLanguage Basics

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

Variables in Memory

The following statements illustrate the difference between a primitive data type and an object:

int i = 5;String s1 = “one”;

The first statement declares an int variable named i and initializes it to 5. An integer requires 4 bytes of memory and, in this example, is stored at memory location 1000.

The next statement instantiates a String object. The object is initialized with the value one. A reference to the object is assigned to the variable s1.

This example illustrates the difference between variables in memory. The variable i holds a value of 5 at the memory address for i. The object variable s1 holds a reference to an object. Object reference variables store links to data in memory, so address 700 holds a reference to the contents of s1. In this example, the address 700 contains a reference to the address 900. Address 900 contains the value one.

IBM Software Group | Tivoli software

18

Variables in Memory

Page 106: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsLanguage Basics

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

Concatenation

In Java, strings are a separate object type named String. Joining two strings to make a third string is called concatenation. The + symbol is the operator that is used for concatenation, although all other operations on strings are done with methods in the String class.

The + symbol is the same operator that is used for adding numbers. If either operand is a String, Java will convert the other operand or operands to String, if possible, and concatenate them.

Operands Result

2 + 4 6

“2” + 4 “24”

2 + “4” “24”

“2” + 4 + 6 “246”

2 + 4 + “6” “246”

2 + 4 + 6 12

IBM Software Group | Tivoli software

19

Concatenation

• The + symbol is the concatenation operator that has been overloaded to handle concatenation of String objects

• + is the same operator used for adding numbers

Page 107: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsLanguage Basics

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

Print Statements

There are three predefined I/O streams that use the console. These are equivalent to UNIX® standard input, error, and output streams. In practice, console input is rarely used. Java was primarily designed for graphical user interfaces, file I/O, and Internet I/O, but programmers will often use System.out.println() during the development and debugging phase.

Different major systems (UNIX, Microsoft® Windows®, and so on) indicate the end of a line (newline) differently. In UNIX, the \n character (sometimes called linefeed) represents the Unicode character 10 ('\u000A') and is used to separate lines.

Windows programs might process a \n separated text file correctly, but others expect a pair of characters (\r\n). You can obtain the system independent value for your Java program from the system properties.

String newline = System.getProperty("line.separator");

It is not necessary to determine the system independent newline characters when using console output. System.out.println() will work, even on Windows systems.

IBM Software Group | Tivoli software

20

Print Statements

• Java uses the System.out attribute for console output

• Print methods have the option of putting a newline at the end of the print stream

• A newline (backslash n) can be inserted to force a newline anywhere within a string of characters

Page 108: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsLanguage Basics

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

Printing Newlines

out is a static member of the System class. This member is of type java.io.PrintStream. The PrintStream class contains a method called println(), which is invoked with a call to System.out.println().

The output methods in the PrintStream class include these methods for printing the standard data types:

public void print(String s) public void print(char c) public void print(int i) public void print(long l) public void print(float f) public void print(double d) public void print(boolean b)

The following methods are identical to the previous ones except that they also print a newline:

public void println() public void println(String s) public void println(char c) public void println(int i) public void println(long l) public void println(float f) public void println(double d) public void println(boolean b)

IBM Software Group | Tivoli software

21

Printing Newlines

Page 109: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsOperators

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

Lesson 3: Operators

Java contains a binary operator for addition, subtraction, multiplication, division, and modulus arithmetic. You can also combine an arithmetic operator and an assignment operator by using the arithmetic and assignment combination operators. The combination operators are equivalent to applying the arithmetic operation on the right-hand side of the expression with the left-hand variable, and assigning the result to the variable.

For example, the following operations are equivalent:

y += 5;

y = y + 5;

IBM Software Group | Tivoli software

22

Operators

• Standard math operators:

– Addition– Subtraction – Multiplication – Division – Modulus

• Shortcut combination operators

Page 110: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsOperators

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

Assignment with Combination Operators

Mathematical operators are not the only operations that can use a combination of an assignment and operation operator.

Use the shift and assignment combination operators to perform bitwise shifts on integers. There are three variants:

• <<= (shift left assignment)

• >>= (shift right assignment)

• >>>= (shift right without sign extension assignment)

The bitwise and assignment combination operators perform a bitwise operation before assignment. There are three variants:

• &= (AND assignment)

• |= (OR assignment)

• ^= (XOR assignment)

IBM Software Group | Tivoli software

23

Assignment with Combination Operators

• Combines an arithmetic operator and an assignment operator– addition (+=) – subtraction (-=) – multiplication (*=) – division (/=)– modulus (%=)

• Combines a shift operator and assignment operator<<=, >>=, and >>>=

• Combines a bitwise and assignment operator&=, |=, and ^=

Page 111: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsOperators

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

Assignment Using the ++ and -- Operators

Java includes operators that act upon a single operand to produce a new value. Those operators are called unary operators.

Two commonly used unary operators are the increment operator (++) and the decrement operator (--). The increment operator increases its operand by 1. The decrement operator decreases its operand by 1. The operand used with these two operators must be a single variable.

The increment and decrement operators can be placed before or after the single operand, but the two options use the operator functionality in two different ways. If the operator precedes the operand (for example, ++i;), the value of the operand will be incremented before it is used within the same statement in the program. If the operator follows the operand (for example, i++;), the operand’s value will be incremented after it is used within the same statement.

IBM Software Group | Tivoli software

24

Assignment Using the ++ and -- Operators

• Unary increment operator is ++• Unary decrement operator is --• Used for adding or subtracting 1 from a variable

• Prefix: Value of operand is changed before useint j = 3;System.out.println(“The value of i is “ + (++j) );

• Postfix: Value of operand is changed after useint j = 3;System.out.println(“The value of i is “ + (j++) );

Page 112: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsOperators

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

Relational Operators

Java has a set of binary relational operators that return either true or false as a boolean type.

Operator Description

> True if left operand is greater than right operand

>= True if left operand is greater than or equal to right operand

< True if left operand is less than right operand

<= True if left operand is less than or equal to right operand

== True if left operand is equal to right operand

!= True if left operand is not equal to right operand

IBM Software Group | Tivoli software

25

Relational Operators

• Comparison operators work for primitive values

• The == and != operators can be used to compare object references

• Comparing object references does not necessarily compare object values

• The result of every comparison is boolean

< less than

<= less than or equal to

== equal to

>= greater than or equal to

> greater than

!= not equal

Page 113: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsOperators

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

Relational Operator Usage

The relational operators are used to compare two or more numeric expressions. The result of the expression is a boolean value.

Relational operators are most often used in conditional control statements.

if(leftOperand <= rightOperand) then ...

IBM Software Group | Tivoli software

26

Relational Operator Usage

• Used to compare two or more numeric expressions

• Evaluation results in a boolean value

• Example:int i = 5;int j = 5;(i == j) evaluates to true

String s1 = “one”;String s2 = “one”;(s1 == s2) is false

• Use s1.equals(s2)

Page 114: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsOperators

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

Relational Operator Example

public class BooleanExample { public static void main(String[] args) { int v1 = 3; int v2 = 5; int v3 = 7; boolean boo = (v1 > v2); System.out.println("Is v1 greater than v2? Answer: " + boo); boo = (v3 > v2); System.out.println("Is v3 greater than v2? Answer: " + boo); }}

Application Output:

Is v1 greater than v2? Answer: false

Is v3 greater than v2? Answer: true

IBM Software Group | Tivoli software

27

Relational Operator Examplepublic class BooleanExample {

public static void main(String[] args) {int v1 = 3;int v2 = 5;int v3 = 7;boolean boo = (v1 > v2);System.out.println("Is v1 greater than v2? Answer: " +

boo);boo = (v3 > v2);System.out.println("Is v3 greater than v2? Answer: " +

boo);}

}

Page 115: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsOperators

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

Common Errors

The following list describes some common programming errors:

• 0 < x < 20 is legal in mathematics but illegal in Java. Comparison operators can be used with two numbers, but this must be written as the and of two comparisons:

0<x && x<100

• Using the assignment operator (=) instead of equality (==) will produce a compiler error.

• Floating-point numbers are not exact, so use >= or <= instead of ==.

• To compare objects, you want to know whether to use == to see if they are the same object, or equals() to see if they might be a different object but have the same value.

IBM Software Group | Tivoli software

28

Common Errors

• In Java, 0 < x < 20 is illegal

• = instead of == will generate a compile error

• Floating-point numbers are not exact, so do not use ==

• The == and != operators can be used to compare object references, but use equals() for object values

Page 116: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsOperators

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

Comparing Primitives and Objects

The only one way to compare primitives is with the == or != operators. The respective values of two compatible data types are compared.

There are multiple ways to compare objects:

• The == or != operators compare references, not values. Use this only if you wasnt to see if a reference is null or if two references are to the same object.

• The equals() method compares values using an == test, which compares the references. This method belongs to the Object class, so it is automatically defined for every class. It has been defined to perform a useful comparison for many Java classes. Unless you want it to behave likes == for your user-defined classes, it should be overridden.

• The compareTo() method compares values and returns an int that indicates if the values compare less than, equal, or greater than. This method is appropriate for Java classes that have a natural ordering, such as String, Double, and so on.

• The compare() method is implemented as part of the Comparator<T> interface.

IBM Software Group | Tivoli software

29

Comparing Primitives and Objects

• x == y and x != y

• x.equals(y)

• x.compareTo(y)

• compare(x,y)

Page 117: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsOperators

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

Logical Operators

The relational operators are often combined with logical operators to construct more complex expressions. Java supports the following three logical operators.

The && and || operators are evaluated from left to right. The evaluation of the expression is terminated as soon as the result of the expression is determined.

Example:

(i < 10) && (j > 5) || (--k != 0)

In this expression, if the variable i is greater than 10, there is no need to evaluate the left operand of the || to determine the value of the entire expression. The evaluation always stops when the answer is determined. For this reason, placing unary operators to increment or decrement a variable within a conditional expression might have unexpected (and unwanted) results.

Operator Usage Evaluates to true if

&& A && B Both A and B are true

|| A || B Either A or B is true

! ! A A is false

IBM Software Group | Tivoli software

30

Logical Operators

• AND (&&)

• OR (||)

• NOT (!)

• Logical operators (also called conditional operators) produce a true or false boolean value

• Expression evaluation is left to right(I < 10) && (j > 5) || (k != 0)

• Parentheses can be used to group conditions(I < 10) && ((j > 5) || (k != 0))

Page 118: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsOperators

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

Ternary ? Operator

The if-else ternary operator is an expression that returns a value based on the conditional expression it evaluates. It is an alternative to the if-then-else syntax that you will see in Unit 4.

A common use of the ternary operator is to assign the value of one of two variables to a third variable based on a condition.

The ternary code that assigns the maximum of two variables, a and b, to a third variable named maximum is:

maximum = a > b? a : b;

In this code, if the variable a is more than b, maximum is assigned the value of a; otherwise, it is assigned the value of b.

IBM Software Group | Tivoli software

31

Ternary ? Operator

• Boolean expression ? if true : if false;

• If i is less than 3, then the return value is j*10, else the return value is 0

return (i<3) ? j*10 : 0;

• Assign the maximum of two variables to a thirdmaximum = (a > b ? a : b);

• Parentheses are not required

Page 119: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsOperators

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

Bitwise Operators

Java’s bitwise operators operate on individual bits of integer type values. If a short is used, it is first promoted to an int data type.

The following example illustrates the use of the bitwise operators. Some preliminary background might be helpful: the decimal number 3 is represented as 11 in binary, and the decimal number 6 is represented as 110 in binary. Negative integers are store in two’s complement form. For example, -4 is 1111 1111 1111 1111 1111 1111 1111 1100.

On a historical note, sometimes XOR is used to flip between 1 and 0:

x = x ^ 1; // which is the same as x ^= 1;

3 & 6 Result is 2 0011 & 0110 equates to 0010

3 | 6 Result is 7 0011 | 0110 equates to 0111

3 ^ 6 Result is 5 0011 ^ 0110 equates to 0101

~3 Result is -4 ~0011 equates to...1111 1111 1111 1100

IBM Software Group | Tivoli software

32

Bitwise Operators

Page 120: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsOperators

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

Bitwise Shift Operators

n << p shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.

n >> p shifts the bits of n right p positions. If n is a two’s complement signed number, the sign bit is shifted into the high-order positions.

n >>> p shifts the bits of n right p positions. Zeros are shifted into the high-order positions.

Historically, it was faster to use shift instead of multiply or divide.

y = x << 3; // Multiplies x times 8 and assigns it to y

A common use of the bitwise operators is to work with multiple values that have been encoded in one integer to pack and unpack the individual values.

IBM Software Group | Tivoli software

33

Bitwise Shift Operators

Page 121: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsOperators

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

Operator Precedence

Well-defined rules specify the order in which an expression with multiple operators is evaluated. For example, multiplication and division have higher precedence than addition and subtraction.

If two operators share an operand, the operation with higher precedence is evaluated first. For example, because multiplication has a higher precedence than addition, 5 + 10 * 15 is treated as 5 + (10 * 15).

When two operators have the same precedence, the expression is evaluated according to its associativity. For example, x = y = z = 10 is treated as x = (y = (z = 10)). All three variables are assigned the value 20, because the = operator has right-to-left associativity (and an assignment statement evaluates to the value on the right-hand side). Because the / operator has left-to-right associativity, 72 / 2 / 3 is treated as (72 / 2) / 3.

Precedence can be overridden by explicit parentheses, and parentheses should be used for clarity.

IBM Software Group | Tivoli software

34

Operator Precedence

•Well-defined rules regarding precedence when an expression contains multiple operators

•Operation with higher precedence is evaluated first

•If operators have the same precedence, the expression is evaluated according to associativity

•Explicit parentheses override precedence

•Use parentheses for clarity

Page 122: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsOperators

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

Student Exercise

Open your Student Exercises book and perform the exercises for this unit.

IBM Software Group | Tivoli software

35

Student Exercise

Page 123: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsOperators

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

Review Questions

1. What is the file extension for Java source?

2. What is the file extension for a compiled Java class file?

3. What is the difference between an int and an Integer?

4. What is the difference between a reference and a primitive stored in memory?

Page 124: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsOperators

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

Review Answers

1. What is the file extension for Java source?

.java

2. What is the file extension for a compiled Java class file?

.class

3. What is the difference between an int and an Integer?

An int is a primitive data type. An Integer is a class that wraps an integer into an object.

4. What is the difference between a reference and a primitive stored in memory?

Memory allocated to a reference points to an object; memory allocated to a primitive data type points to data.

Page 125: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 3: Java Basics and OperatorsOperators

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

Summary

IBM Software Group | Tivoli software

36

Summary

You should now be able to:

Describe the Java language basics

– Variable types– Data types– Object referencesOperators– Mathematical operators– Logical operators– Relational operators

Page 126: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 3: Java Basics and OperatorsOperators

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

Page 127: Ibm enterprise it and asset management 7.1 java for customization training

• • • ••

4-1

Unit 4: Java Basics and Programming Syntax

© 2009 IBM Corporation

Unit 4: Java Basics and Programming Syntax

Page 128: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Introduction

This unit covers the basics of the Java programming language and syntax.

Objectives

IBM Software Group | Tivoli software

2

Objectives

Upon completion of this unit, you will be able to:Use Java syntax basics

Use Java conditional control constructs

Use Java iteration constructs

Use arrays

Page 129: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Variable Declaration

A variable declaration can be made in different ways. The following syntax example declares a variable, its data type, and the optional access modifier:

[accessControl] dataType variableName;

This statement reserves memory for the variable. It indicates nothing regarding what value is put in memory. However, if the data type is a primitive and it is not a local variable, the variable is automatically initialized with a default value.

The next example declares a variable, declares its data type, reserves memory for it, and puts a value into that memory. That value must be of the correct data type.

[accessControl] dataType variableName = initialValue;

The third syntax example declares two variables, both of the same data type. It reserves memory for each, but puts nothing in either variable.

[accessControl] dataType variableNameOne, variableNameTwo;

You can do this with multiple variables, and you can put initial values into each variable if you want.

IBM Software Group | Tivoli software

3

Variable Declaration

• Optional access control modifier

• Variable data type

• Variable name

Page 130: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Variable Access Control

Access control modifiers are used at the class, variable, and method levels. The access level determines whether other classes can use a particular class or variable, or call a particular method.

At the variable level, the access modifiers are public, private, protected, or no explicit modifier, which is known as package.

The public modifier specifies that the variable can be accessed by any class or method. The private modifier specifies that the variable can only be accessed within its own class. The protected modifier specifies that the variable can only be accessed within its own package, and any subclass, even if the subclass is in another package. The default access is package and the variable is visible only within its own package.

Deciding when to make a variable private, protected, or public depends on whether an external object must have access to the data in the variable. If you want other objects to access internal data, you must decide if the access will be direct or if you want to control it. Make the variable public to allow direct access. To hide the data from direct manipulation, make it either private or protected, and provide methods to retrieve or manipulate the data in a controlled manner.

IBM Software Group | Tivoli software

4

Variable Access Control

• public

• private

• protected

• package

Page 131: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Method Definitions

The general form of a method definition is:

accessControl returnType methodName(parameter list){ declarations and statements (return statement)}

The return type is the data type of the result returned by the method to the calling method. If no value is returned, the return value is void.

The parameter list is a comma-separated list containing the parameters for the method. It is provided whenever the method is called. A type must be declared for each parameter in the list. The parentheses are required, whether or not the parameter list is empty.

Local variables that are declared and used within a method are not accessible outside of the method.

Java programs communicate with their methods using pass-by-value. The method works with a copy of the original argument, not the argument itself. Therefore, the method cannot modify the original argument even if it modifies the parameter.

IBM Software Group | Tivoli software

5

Method Definitions

The general form of a method definition contains:An access control keyword

A return type

A method name

A parameter list

Page 132: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Method Access Control

Access control for methods and constructors is similar to access control for classes and data members. A method that is public within a public class is accessible to any class in the Java program, whether or not the classes are in the same package.

Private methods or constructors are strictly controlled; they cannot be accessed outside the class that defines them. A common strategy is to make all fields private and provide public getter and setter methods for them.

Variables, methods, and constructors declared protected in a superclass can be accessed only by:

• Subclasses (in the same or other packages)

• Classes in the same package, whether or not they are a subclass of the protected member’s class

When no access modifier specified, the method is accessible only by classes in the same package.

IBM Software Group | Tivoli software

6

Method Access Control

• public

• private

• protected

• package

Page 133: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

main() Method

The controlling class of a Java application contains the main() method.

The main() method in Java is similar to main() in other languages that use it as the starting point of a program.

When you execute a Java application with the Java interpreter, the runtime system starts by calling the controlling class’s main() method. The main() method in turn creates objects and calls the methods required to run your application.

IBM Software Group | Tivoli software

7

main() Method

• main() is in the controlling class of a Java application

• main() is the starting point of a program

Page 134: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

main() Method Signature

The main() method has the following signature:

public static void main(String[] args)

The reserved word public is a modifier that specifies the visibility of the method to other classes. Most Java methods are public, meaning that they are accessible and visible to other methods, including methods in other classes.

The reserved word static is also a modifier, and it identifies the method as a class (or static) method. A static method is not called through an instance of a class; instead, it is called through the class itself.

The reserved word void identifies the return type of the method. The main() method does not return a value, so the return value is void. All Java methods must include a return type in their signature, even if the method has nothing to return. If there is nothing to return, the method is defined to return a void.

Next is the name of the method. Like any other method, the main() method conforms to the Java naming conventions. The name of the method is followed by a set of parentheses containing the arguments passed to the method. In the case of main(), it receives an array of String references as an argument.

Immediately following the method signature is the definition of the method within a set of braces.

IBM Software Group | Tivoli software

8

main() Method Signature

• The main() method has the reserved words public, static, and void

• The main() method receives an array of String references as a parameter

Page 135: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Arrays

An array in Java is the same as an array in most programming languages. It is similar to a matrix in math and, like a mathematical matrix, an array can be one or more dimensions.

An array can store a large number of values that are the same data type in memory. Each value is accessed with an integer index in brackets ([]) following the array name.

In Java, you must both declare an array and allocate a fixed amount of memory to hold its contents.

Arrays are best for working with a fixed number of elements. Other data types are a better choice for working with a variable number of elements. Those data types will be covered later.

IBM Software Group | Tivoli software

9

Arrays

• Similar to a mathematical matrix

• Can be one or more dimensions

• Store data of the same data type

• Each array element is accessed using an integer index

• Work best for a fixed number of elements

Page 136: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Array Declaration

An array must be declared like any other variable. When you declare an array, you must declare the type of elements that are in the array. All of the array elements must be the same data type.

To declare an array, type the element type name, type brackets ([]), and then type the name of the array variable. The name of an array variable usually denotes a list or collection of items, so it should be meaningful to someone reading your code.

The declaration allocates only enough space for a reference to an array. It does not create the actual array object.

String[] args; // args is an array of Stringsint[] grades; // grades is an array of integersItem[] itemList; // itemList is an array of Item objects

An array declaration specifies only the element type and the variable name. The size of the array will be specified when you allocate memory for the array.

IBM Software Group | Tivoli software

10

Array Declaration

• Declare an array like any other variable

• Include the data type that is in the array

• Syntax is the type of data contained in the array, followed by brackets, and then the array variable name

String[ ] stringList;

int[ ] numberList;

Page 137: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Allocating an Array

When an array is declared, it creates a reference to the array. An array object is then allocated with new.

Using new, the following statements illustrate creating an array of 100 String elements, from stringList[0] to stringList[99].

String[] stringList; // Declare an array of StringsstringList = new String[100]; // Allocate an array of 100 // references to String

The array declaration and allocation are often combined in one line. The following statement creates an array of 20 integers:

int[] numberList = new int[20];

Each array has an instance variable that has the number of elements in the array. That value is final (constant). To determine how many elements an array can hold, write the array name followed by .length. In the previous example, the value of numberList.length would be 20.

IBM Software Group | Tivoli software

11

Allocating an Array

• Declare an array:String[ ] stringList;

• Allocate memory for array:stringList = new String[100];

• Declare and allocate for an array:int[ ] numberList = new int[20];

• Use .length to return the number of array elements

Page 138: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Arrays in Memory

When you declare an array, you can allocate a preinitialized array in the same statement. Java counts the number of values to determine the size.

The code declares and initializes an array of three array objects with this statement:

int[] tasks = {10, 20, 30};

The slide illustrates an array variable named tasks to represent the memory allocated for an array.

The contents of tasks is a memory address. The address is the location of a block of memory that was allocated to hold the array elements.

Another way to think of the contents of tasks is as a reference to a block of memory. References can be represented by an arrow pointing to the data to which they refer. Each box represents the memory needed for one array element.

When you declare an array variable, Java reserves only enough memory for a reference to an array object. When an array object is created with new, a reference is returned; that reference can then be assigned to a variable. When you assign one array variable to another, only the reference is copied.

IBM Software Group | Tivoli software

12

Arrays in Memory

int[] tasks = {10,20,30};

int[] tasks;

tasks = new int[3];

tasks[0] = 10;

tasks[1] = 20;

tasks[2] = 30;

Page 139: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Arrays Class

The java.util.Arrays class is a utility class to manipulate arrays. It contains the following static methods:

void fill(array, value);boolean equals(array1, array2);void sort(array);int binarySearch(array, val);

The following statements fill each element in the aInt array with the integer 5:

int[] aInt = new int[10];Arrays.fill(aInt, 5);

The following statement sorts the arr array in ascending order:

Arrays.sort(arr);

The following statement searches the arr array of ints for the number 7 using the binary search algorithm:

int foundAtIndex = Arrays.binarySearch(arr,7);

IBM Software Group | Tivoli software

13

Arrays Class

• void fill(array, value);int[ ] aInt = new int[10];Arrays.fill(aInt, 5);

• void equals(array1, array2);

• void sort(array);Arrays.sort(arr);

• int binarySearch(array, val);// Searches a sorted array for the number 7Arrays.binarySearch(arr,7);

Page 140: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Arrays of Arrays

Java does not support multidimensional arrays, but it does support arrays of arrays.

In Java, a two-dimensional array is really an array of one-dimensional arrays. It is implemented by creating a one-dimensional array whose elements are also an array.

IBM Software Group | Tivoli software

14

Arrays of Arrays

• Java supports an array of arrays

• Not a two-dimensional array whereby the dimensions are fixed

• The arrays can be of different sizes

Page 141: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Declare an Array of Arrays

First declare a reference to an array of arrays. Then create the individual arrays associated with each element. For example:

int y[][]; // create reference to an array of arraysy = new int[3][4]; // create array objects

The declaration and allocation of the arrays can be made with one statement:

int[][] y = new int[3][4];

The expression y[i] selects the i-th one-dimensional array. The expression y[i][j] selects the j-th element from the y array.

IBM Software Group | Tivoli software

15

Declare an Array of Arraysint matrix[][] = new int [3][3];

orint[][] matrix;matrix = new int [3][3];

Page 142: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Different Dimensions

Rows can be different sizes, and each row is an array object that can be used independently.

The following example allocates an array of 10 rows and then allocates each part of the two-dimensional array individually:

String[][] skills = new Strings[10][];

skills[0] = new String[4]; // Allocate rowsskills[1] = new String[2];skills[2] = new String[3];...

// Print the skills array for (int i=0; i<skills.length; i++) { for (int j=0; j < skills[i].length; j++) { System.out.print(" " + skills[i][j]); } System.out.println("");}

IBM Software Group | Tivoli software

16

Different Dimensions

String[][] skills = new Strings[10][];

skills[0] = new String[4];

skills[1] = new String[2];

skills[2] = new String[3];

Page 143: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Constants

Java does not have a constant type, but you can achieve a constant in effect by declaring and initializing variables that are static, public, and final. After final variables have been initialized, their value is constant and unchangeable. Because they are static, they are only created once for the class or interface in which they are defined.

By convention, a constant is uppercase and words are separated by an underscore.

If constants are integer variables, they can be enumerated and used as an index in a loop or switch statement.

An enum type is a type whose fields consist of a fixed set of constants.

Example:

public static final int EAST = 0;public static final int WEST = 1;public static final int NORTH = 2;public static final int SOUTH = 3;

These constants can be represented with a one-line definition:

public enum numbers { EAST, WEST, NORTH, SOUTH };

IBM Software Group | Tivoli software

17

Constants

• Variables declared with the final modifier cannot be changed after initialization

• Constants are declared with the static and final keywords:– public static final int MAX_CAPACITY = 33;– public static final String STOCK_TYPE = " IBM";

• Uppercase, by convention

Page 144: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Variable Initialization

Variable declarations are required. The indicate the data type so that the compiler can provide the correct amount of memory to store values. The compiler can also use them to determine where variables are being misused. A variable’s data type specifies the kind of data a variable stores and how much memory is required to store that particular data type.

You have seen that Java has two general kinds of data types: primitive and object.

There are eight primitive types (byte, short, int, long, float, double, char, boolean) and an unlimited number of object types (String, Array, and so on). Object variables contain a reference that refers (points) to the object.

IBM Software Group | Tivoli software

18

Variable Initialization

• Declaration, allocation, and initializationint j = 5;double d = 33.44;String s = " This is it"; int[] tasks = { 10, 20,30 };String[] cases = {" A", " B", " C"};

• Allocates an array and sets valuesString[] cases = new String[3]; //allocates arraycase[0] = " A"; // Assigns values to array elementscase[1] = " B"; case[2] = " C";

Page 145: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Initial Values

The possible values that a variable can have when it is created are as follows:

• No initial value. Java local variables have no initial value, so you must ensure that every local variable is assigned a value before it is used.

• User-defined initial value. A initial value can be assigned in the declaration of a variable.

• Instance and static variables are assigned default initial values:

– 0 for numbers

– null for objects

– false for booleans

IBM Software Group | Tivoli software

19

Initial Values

• Local variables have no initial value

• Ensure that every local variable is assigned a value

• User-defined initial value can be assigned in the declaration of a variable

• Instance and static variables are assigned default initial values:

– 0 for numbers– null for objects

– false for booleans

Page 146: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Casting Operator

Implicit conversions can occur during an assignment. For example, an integer can be converted to a floating-point value if appropriate. You can use an object of one class wherever a reference to one of its superclasses is required. In other words, you can reference up the class hierarchy, but not down.

Explicit conversion occurs when one type cannot be assigned to another type through implicit conversion. That situation requires the cast operator. The syntax is simply (type).

To summarize:

• Widening conversions do not require casting, and they preserve the exact original value of the number.

byte > short > int > long > float > doublechar > int > long > float > double

• Referencing up the class hierarchy to a superclass does not require casting.

• Narrowing conversions require explicit casting with the cast operator, and might lose information and precision.

double > float > long > int > char > short > byte

• Any type can be converted to String with the toString() method.

IBM Software Group | Tivoli software

20

Casting Operator

• Syntax is simply (type)

• Implicit conversions:

byte > short > int > long > float > double

char > int > long > float > double

• Explicit conversions:

double > float > long > int > char > short > byte

• toString()

Page 147: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Literals

A literal is any number, character, boolean, or string that represents a value in a program. Literals, in addition to variables, are used in Java statements. In the following statement, the literal is the integer value 6:

int width = 6;

The default data type of an integer literal is int. An integer literal can be specified as long by appending the suffix L or l to the integer value.

The default data type of a floating-point literal is double. You can explicitly specify double by appending the D or d suffix. Append F or f to designate that the data type is a floating-point literal.

A string literal is enclosed in double quotation marks (") and is of type String (for example, “a” and “Hello World”).

Boolean literals are the primitive data type boolean, and true and false are reserved boolean literals.

Character literals are the primitive data type character. A character literal is enclosed in single quotation marks (').

IBM Software Group | Tivoli software

21

Literals

• Integer literals: 24 0 -3• Floating-point literals: .3 0.111 3.14f• Double literals: 9.0 9. 9D• Character literals: '(‘ 'B' '=‘• Boolean literals: true false• String literals: " Java is a language" "5.0" "real" ""• Three reserved, predefined literals:

– true– false– null

Page 148: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Three reserved words are predefined literals:

• true

• false

• null

True and false are the boolean values. Null is the null reference.

Page 149: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

if and if-else Statement

The if statement is used to make decisions and execute different parts of your program depending on a boolean value.

The form of the if statement is:

if (boolean expression) {block of statements

}

The form of the if-else statement is:

if (boolean expression) {block of statements1

}else {

block of statements2}

The else is optional. The condition can be an expression that evaluates to a boolean value. If the expression evaluates to true, then the first block of statements is executed. Otherwise, if it exists, the second block of statements is executed.

IBM Software Group | Tivoli software

22

if and if-else Statement

• Used to control program flow depending on a condition

• Condition is evaluated with a boolean expression

• The else is optional

Page 150: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

if-else Example

This example assigns a number to the variable discount, depending on the condition.

There are other ways to write the if statement. One option is to reverse the condition. Put the normal case first, or the one that makes the condition easiest to read.

double discount; if (value <= 5) { discount = .10; } else { discount = .20;}

Another option is to initialize the variable to a default value and change it if necessary. Use this option when the condition is rarely true.

double discount = .10; if (value > 5) discount = .20;

IBM Software Group | Tivoli software

23

if-else Example

• Assignment depends upon the condition (value > 5)

• Many ways to express the if-else statement using variations of the condition

• Do not use multiple ifstatements in place of an if-else statement

Page 151: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Do not use two if statements. Doing so is confusing and inefficient because both conditions must be evaluated.

double discount;// Confusing and inefficient codeif (value <= 5) { discount = .10;}if (value > 5) { discount = .20;}

Page 152: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

if-else if Statement

To make a series of tests on a value, the else part of the statement contains another if statement.

if (boolean expression1) { statement block1;} else if (boolean expression2) { statement block2;} else if (boolean expression3) { statement block3;} else if (boolean expression4) { statement block4;} else { statement block5;}

This example is an exception to common indention rules, but this format results in more readable code.

IBM Software Group | Tivoli software

24

if-else if Statement

Page 153: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

switch Statement

Most conditions are tested with the if statement. However, there is also a switch statement that is used to test multiple conditions based on an integer (including char) or enum value. It is used to direct execution in one of several different ways.

The switch statement syntax is:

switch (expr) { case c1: statements // do if expr == c1 break; case c2: statements // do if expr == c2 break; case c2: case c3: case c4: // Cases can fall thru to the next case statements break; . . . default: statements }

The switch reserved word is followed by an integer expression in parentheses. It is followed by all the cases enclosed in braces. The case corresponding to the value of the

IBM Software Group | Tivoli software

25

switch Statement

Page 154: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

switch expression is executed. The code for each case clause usually ends with a break statement to exit the switch statement. The break statement causes execution to go to the statement after the end of the switch. If there is no break, execution continues into the next case. This situation is usually an error.

If no case matches, the default clause is executed, if there is one.

The case reserved word is followed by an integer constant and a colon.

Page 155: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

break and continue Statements

The break and continue statements direct the flow of compound statements. The break and continue statements refer to the closest enclosing for, while, do, or switch statement.

A continue statement immediately goes to the next iteration of the appropriate loop. A continue statement does not apply to a switch statement.

IBM Software Group | Tivoli software

26

break and continue Statements

• The break and continue statements direct the flow of the closest appropriate block of statements

• A continue statement immediately goes to the next iteration of the enclosing loop

Page 156: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

break Statement

A break statement immediately goes to the end (and out) of the appropriate statement or block of statements.

IBM Software Group | Tivoli software

27

break Statement

Page 157: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Loops

Loop statements are used to repeat Java statements many times. There are different types of loop statements in Java:

• The while statement

• The for statement

• The do-while statement

• The foreach statement

IBM Software Group | Tivoli software

28

Loops

Page 158: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

while Statement

The while statement is used to repeat a block of statements while some condition is true. The condition must become false somewhere in the loop; otherwise it will iterate indefinitely, which is known as an infinite loop.

The while statement is used to test a condition at the beginning of the loop. If the condition is false at the beginning, the statement or statements inside the loop are never executed.

The form of the while statement is:

while (boolean expression) { statement block}

The syntax is like an if statement, except that it uses the while keyword. The value of condition must be a boolean value, and it is often a comparison.

IBM Software Group | Tivoli software

29

while Statement

• Used to repeat a block of statements while a condition is true

• Tests the condition at the beginning of the loop

Page 159: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

for Statement

An alternative to the while loop is the for loop. The for loop combines the following three parts into one statement:

• Initializing a variable

• Testing a boolean expression

• Updating a value before the next iteration

The for loop is typically used for repeating code a known number of times. The form of the for statement is:

for (initialization; boolean expression; increment) ( statement block;}

Semicolons are used to separate the fields inside the parentheses.

• The first field initializes a variable. The variable can also be declared here.

• The second field determines whether the loop will execute.

• The third field executes at the end of each pass through the loop.

IBM Software Group | Tivoli software

30

for Statement

• Alternative to whileloop

• Used to repeat code a known number of times

• Initialization, testing of condition, and updates before next iteration are accomplished in one statement rather than three

Page 160: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Comparing for and while Statements

The for statement is similar to the while statement. The for statement is often easier to read when counting or using indexes because it combines three loop elements in one statement:

• Initialization

• Testing

• Incrementing

The following table illustrates equivalent for and while statements.

for Loop while Loop

for (initialization; boolean expression; any statement) {......processing statements}

initialization statement;while (boolean expression) {.... any statement;processing statements}

IBM Software Group | Tivoli software

31

Comparing for and while Statements

for (initialize stmt; condition; next stmt) {body

}

initialize stmt;

while (condition) {bodynext stmt;

}

Page 161: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

There are three clauses in the loops statement. The following statements apply to both the for and while loops:

• The initialization statement is done before the loop is started, usually to initialize an iteration variable.

• The boolean expression is tested before each time the loop is executed. The loop is not executed if the boolean expression is false.

• The any statement is executed after the body of the loop has executed. It usually increments an iteration variable so that the boolean expression will evaluate to false and the loop can terminate.

Page 162: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

do-while Statement

The do-while loop is the only loop that will always have at least one pass through the block of statements, because the boolean expression is tested at the end of the loop. Therefore, if you want to test at the end to see whether something should be repeated, the do-while statement is the best choice.

The syntax of this statement is:

do {statement block} while (boolean expression)

IBM Software Group | Tivoli software

32

do-while Statement

• Always one pass through the block of statements

• Used to test whether something should be repeated

Page 163: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Infinite Loops

An infinite loop is often due to a programming error. However, sometimes you might want a program to iterate forever, or until an error condition is recognized.

An infinite loop can be created with any of the loop options:

// infinite for loopfor (;;) {}

// infinite while loopwhile (true) {}

// infinite do-while loopdo {} while (true);

IBM Software Group | Tivoli software

33

Infinite Loops• Sometimes you might want a program to iterate forever

• An infinite loop can be created with any of these loop options:

for (;;) {

}

while (true) {

}

do {

} while (true);

Page 164: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

foreach statement

The foreach is an enhanced for loop to use specifically with arrays and collection classes. It accesses each successive element of various data structures, and you do not have to keep track of iterators or indexes.

You will see this loop again in Unit 8, which covers collection class types. But the following example illustrates the syntax without the complexity of a generic collection:

String[] nameList = { "a", "b", "c" };for (String name: nameList) System.out.println(name.charAt(0));

The for loop will iterate for each String object name in nameList. It will execute the println() method until all of the items in nameList are retrieved. After all of the items have been retrieved, it will exit the loop.

IBM Software Group | Tivoli software

34

foreach Statement

• An enhanced for loop to use specifically with arrays and collection classes

• Accesses each element of various data structures in sequence

• No need to keep track of iterators or indexesString[ ] nameList = { "a", "b", "c" };for (String name: nameList)

System.out.println(name.charAt(0));

Page 165: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Scope of a Variable

The scope of a variable determines who can see it. All constants and variables have scope. They are accessible in some parts of the program, and they do not appear to exist in other parts. The scope of a variable is related to program structure. There are different types of scope, such as block, method, class, or package.

Variables and objects that are declared within a block of code are only visible within that block of code.

Local variables and parameters are created when a method is entered. They are destroyed when the method returns. Instance variables are created by new and they are destroyed when there are no longer any references to them. Class (static) variables are created when the class is loaded, and destroyed when the program terminates.

IBM Software Group | Tivoli software

35

Scope of a Variable

Page 166: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Printing Program Arguments

The slide illustrates a class named PrintArgs within the package examples.str. An enhanced for loop (Java 5) is used to loop through the arguments and print them out, one by one.

Next, the traditional for loop is used to perform the same task. The int variable i is declared only for use by the traditional for loop, so its scope is restricted to use only within that for loop.

IBM Software Group | Tivoli software

36

Printing Program Arguments

• Add text

Page 167: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Add Program Arguments

Use the Arguments tab in the Run Configurations window to include program arguments.

IBM Software Group | Tivoli software

37

Add Program Arguments

• Add text

Page 168: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Conversions from String

Program arguments are of type String. Those arguments are converted to an appropriate data type with the parseInt() (or parseDouble(), parseFloat(), and so on) method when necessary.

IBM Software Group | Tivoli software

38

Conversions from String

• Add text

Page 169: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Class Sum

The slide illustrates a class named Sum. The arguments are of type String and are converted to an appropriate data type with the parseInt() method.

Both for loops are used to loop through the program arguments.

IBM Software Group | Tivoli software

39

Class Sum

• Add text

Page 170: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Student Exercise

Open your Student Exercises book and perform the exercises for this unit.

IBM Software Group | Tivoli software

40

Student Exercise

Page 171: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Review Questions

1. When do you use a continue statement?

2. When do you use a break statement?

3. What is the difference between while and do-while loops?

4. What loop is the best choice for a known number of iterations?

Page 172: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Review Answers

1. When do you use a continue statement?

Use the continue statement to prematurely complete an iteration of a loop.

2. When do you use a break statement?

Use the break statement to exit a loop or switch statement.

3. What is the difference between while and do-while loops?

The test is performed at the end of the body in the do-while loop, this loop always executes the body of the loop at least once. The body of the while loop is executed only after the test is performed.

4. What loop is the best choice for a known number of iterations?

The for loop

Page 173: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 4: Java Basics and Programming Syntax

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

Summary

IBM Software Group | Tivoli software

41

Summary

You should now be able to:Use Java syntax basics

Use Java conditional control constructs

Use Java iteration constructs

Use arrays

Page 174: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 4: Java Basics and Programming Syntax

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

Page 175: Ibm enterprise it and asset management 7.1 java for customization training

• • • ••

5-1

Unit 5: Classes, Constructors, and Strings

© 2009 IBM Corporation

Unit 5: Classes, Constructors, and Strings

Page 176: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and Strings

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

Introduction

This unit examines the difference between classes and objects, and how objects are constructed. The String class and its methods are introduced.

Objectives

IBM Software Group | Tivoli software

2

Objectives

Upon completion of this unit, you will be able to:Use classes

Use constructors

Use the String class

Page 177: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsClasses

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

Lesson 1: Classes

A typical class has the following elements:

• A package statement

• Import statements

• A class declaration

• Instance variable declarations

• Constructor declaration

• Method declarations

Class names begin with uppercase letters by convention. The method names begin with lowercase letters.

IBM Software Group | Tivoli software

3

Classes

Page 178: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsClasses

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

Create Objects

An object is an instance of a class. The new keyword is used to allocate memory for an object. The operator new takes an operand, which is the constructor.

A constructor is a specialized method that constructs an object.

IBM Software Group | Tivoli software

4

Create Objects

• An object is an instance of a class

• new allocates memory for an object

• Operator new requires a constructor operand

• Constructors build and initialize objects

Page 179: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsClasses

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

Classes and Objects

After new allocates memory, it calls the constructor to initialize the object. After the constructor has built the object, new returns the address of that object.

The example illustrated in the slide is the creation of three objects using the default constructor, which does not take any arguments. Each instance of these objects has its own x and y variables.

IBM Software Group | Tivoli software

5

Classes and Objects

Use operator new to create instances of MyClass and assign them to variables a, b, and c

Page 180: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsClasses

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

Using new

To create an instance of an object, use the new keyword.

public class TestingMyClass {public static void main(String[] args) {

TestClass mc = new TestClass();TestClass mc2 = new TestClass("Start");

}}

On the left side of the equal sign is the object declaration. To create a TestClass object called mc, create a new instance of a TestClass object and assign it to that variable. The two statements illustrated in the preceding code use two different constructors. The TestClass objects are assigned new TestClass instances.

After an instance of an object is assigned to a variable, class methods can be called using dot notation. From outside of the defining class, an instance method is called by using an object name as a prefix, followed by a dot (.). The object is passed as an implicit parameter to the instance method.

IBM Software Group | Tivoli software

6

Using new

• Use the new keyword to create an instance of an object:public class TestingMyClass {public static void main(String[] args) {

TestClass mc = new TestClass();TestClass mc2 = new TestClass("Start");}

}

• Instance methods and data are accessible after instance of object has been assigned to variable

Page 181: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsClasses

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

Garbage Collection

Java automates the error-prone process of manually deallocating memory for objects that are no longer being used. The process is called garbage collection.

Garbage collection automatically finds blocks of memory that are no longer being used (and are therefore considered garbage) and makes that memory available.

The memory that is dynamically allocated is called the heap. Java manages the allocation of memory with new and deallocation is performed automatically with garbage collection.

IBM Software Group | Tivoli software

7

Garbage Collection

• Memory must be allocated on the heap for objects

• Memory is deallocated when objects are no longer in use

• Java automates deallocation of memory

• Finds unused blocks of memory and recycles them

Page 182: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsConstructors

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

Lesson 2: Constructors

When you create a new instance of a class using the new keyword, a constructor for that class is called.

Constructors are similar to methods, but their purpose is to create an instance of their class.

A constructor must have the same name as the class it is in, and does not have a return type. There is no need for a return type because the return value is an instance of the object itself.

public class Rectangle { int x; int y;

public Rectangle(int a, int b) { x=a; y=b; }......}

IBM Software Group | Tivoli software

8

Constructors• Classes contain constructors• Purpose is to construct an object of the class• Must have the same name as the class

public class Rectangle {int x;int y;

public Rectangle (int a, int b) {x=a;y=b;

}......}

Page 183: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsConstructors

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

Default Constructor

If you do not define a constructor for a class, the compiler automatically creates a default constructor that takes no parameters.

The default constructor calls the default constructors of any superclasses and initializes instance variables to their default value. Default values are 0 for numeric data types, a reference to null for objects, and false for a boolean data type.

If you define any constructor for your class, a default constructor will not be automatically created for you.

public class Rectangle { int x; int y;

public Rectangle() { x=0; y=0; }

public Rectangle(int a, int b) { x=a; y=b; }......}

IBM Software Group | Tivoli software

9

Default Constructor

• Default constructor does not take any parameters• Automatically created by compiler if a constructor is not

defined

Page 184: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsConstructors

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

Using the Keyword this

Use the keyword this to call another constructor in the same class. A constructor with fewer parameters will often call a constructor with more parameters and use default values for the missing parameters.

public class Rectangle { int x; int y;

public Rectangle() { this(0,0); // Calls another constructor } public Rectangle(int x, int y) { this.x = x; // notice another use of the keyword this this.y = y; }......}

IBM Software Group | Tivoli software

10

Using the Keyword thispublic class Rectangle {int x;int y;

public Rectangle() {this(0,0); // Calls another constructor

}public Rectangle(int x, int y) {this. x = x; // notice another use of the keyword thisthis.y = y;

}......}

Page 185: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsConstructors

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

Using the super() Keyword

Use super() to call a constructor in a superclass.

If you have to call the superclass constructor, it must be the first statement in the body of a constructor. Otherwise, the default constructor in the superclass will be called automatically as part of the object construction.

Typically, you do not need to call the superclass constructor because it is automatically generated. However, calling it is necessary in the following two cases:

• You want to call a superclass constructor that has parameters.

• There is no parameterless superclass constructor.

public class Rectangle { int x; int y;

public Rectangle() { this(0,0); // Calls another constructor } public Rectangle(int x, int y) { super(); // Or automatically placed by compiler this.x = x; this.y = y; }......}

IBM Software Group | Tivoli software

11

Using the super() Keyword

public class Rectangle {int x;int y;

public Rectangle() {this(0,0); // Calls another constructor

}public Rectangle(int x, int y) {super(); // If you do not call, automatically placed by compiler this. x = x; this.y = y;

}......}

Page 186: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsConstructors

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

Constructors versus Methods

There are some significant differences between methods and constructors:

• There is no return type in a constructor signature.

• There is no return statement within the body of a constructor.

• The first line of a constructor can be either of the following calls:

– A call to another constructor in the same class using the keyword this

– A call to the superclass constructor using the keyword super()

If the first line is neither, the compiler automatically inserts a call to the default, parameterless superclass constructor.

IBM Software Group | Tivoli software

12

Constructors versus Methods

• No return type in signature

• No return statement in the constructor body

• First line can be a call to another constructor using keyword this

• First line can be a call to superclass constructor using super()

• If neither this nor super() is used in first line, parameterless superclass constructor is called

• Must explicitly call superclass constructor if a default superclass constructor does not exist

Page 187: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsConstructors

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

Order of Construction

Every object contains the instance variables of its class. Every object also contains all the instance variables of all of its superclasses (the parent class, the grandparent class, and so on).

These superclass constructors are called, and the variables are initialized, before the class itself is constructed and its instances variables are initialized.

IBM Software Group | Tivoli software

13

Order of Construction

Page 188: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsConstructors

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

Object Creation with Instance Variables

When many objects are created from the same class, each instance has its own variables, unless the variable has been declared with the keyword static.

IBM Software Group | Tivoli software

14

Object Creation with Instance Variables

Page 189: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsConstructors

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

Static Variables

To repeat, when many objects are created from the same class, each instance has its own variables, unless the variable has been declared with the keyword static.

A static variable (or a static method) is not attached to a specific instance, but rather it is associated with the class as a whole. Static variables are allocated when the class is loaded.

IBM Software Group | Tivoli software

15

Static Variables

Page 190: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsConstructors

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

Static Methods

Instance methods are the default. They are associated with an object instance and use its instance variables. In contrast, static methods use no instance variables of any object of the class they are defined in.

Although a static method cannot access instance variables, it can access static variables. A common use of static variables is to define them as constants.

Two examples from the Java library are Color.BLUE and Math.PI. They are qualified with the class name, so you know they are static. Any method can access static variables, but instance variables can be accessed only by instance methods.

If you define a method to be static, the compiler will return an error if you try to access any instance variables. Use only static variables and other static methods.

class StatUtils { . . . public static double mean(int[] a) { int sum = 0; for (int i=0; i<a.length; i++) { sum += a[i]; } return ((double)sum) / a.length; } . . .}

IBM Software Group | Tivoli software

16

Static Methods

• Instance methods are default

• Static methods do not need an instance of the object

• Static methods cannot use instance variables

• Use instance method by using an instance name as prefix

• Use static method by using a class name as prefix

class StatUtils {. . . public static double mean(int[] a) {int sum = 0; . . .

Page 191: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsConstructors

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

Calling Static Methods

Remember that an instance method is called by using an object as a prefix. A static method is called by using a class name as a prefix.

From within the same class, write the static method name:

double avgAmount = mean(Amounts);

If a method (whether static or instance) is called from another class, something must be specified before the method name to identify the class where the method is defined. For instance methods, it is the object. For static methods, it is the class name.

double avgAmount = StatUtils.mean(Amounts);

IBM Software Group | Tivoli software

17

Calling Static Methods

• From within the class:double avgAmount = mean(Amounts);

• From outside of the class:double avgAmount = StatUtils.mean(Amounts);

Page 192: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsJava Documentation

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

Lesson 3: Java Documentation

The Java documentation includes what you need to use the classes in the API. It contains a list of all the Java packages, classes, and interfaces. Also included are all of their constructors, methods, fields, and the information on how to use them.

Each version of Java has its own API documentation.

You can download the API or access it online.

IBM Software Group | Tivoli software

18

Java Documentation

• Javadocs

• What you need to know to use the classes in the API

• Contains Java packages, classes, and interfaces

• Contains constructors, methods, fields, and how to use them

• Each version has its own API

• Download or access online

Page 193: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsJava Documentation

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

Java Documentation Navigation

The documentation is organized in three windows. The two windows on the left contain the packages. Each package is a link to its classes, interfaces, exceptions, and so on. The larger window on the right can show lists of packages and also link to details for methods, constructors, and variables.

The documentation provides links to navigate packages and classes. If you select a package from the upper left window, the lower left frame displays all the classes, exceptions, and related information in that package. Detailed information is displayed in the larger window on the right.

IBM Software Group | Tivoli software

19

Java Documentation Navigation

Page 194: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsJava Documentation

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

Documentation Details

The Java class and interface hierarchy can be listed in the left window and the details examined in the right window. The fields, constructors, and methods are listed alphabetically and are linked to detailed corresponding explanations.

IBM Software Group | Tivoli software

20

Documentation Details

Page 195: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsString Class

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

Lesson 4: String Class

Strings are a sequence of characters. Many programming languages use arrays to store characters. In Java, strings are a separate class called String.

The + operator is used for concatenation, but all other operations on String objects are performed using methods in the String class.

Objects of type String cannot be changed; they are immutable.

The following table describes some related classes.

Class Name Description

Character Used to work with characters. Wrapper class for char primitive.

StringBuffer Used to build or change strings.

StringBuilder Similar to StringBuffer but unsynchronized. Added in Java 5.

StringTokenizer Used to break a string into words (tokens).

IBM Software Group | Tivoli software

21

String Class

Page 196: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsString Class

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

Strings

To create a constant string, type the string characters between double quotation marks (for example, "xyz").

Some characters cannot be written directly in a string, such as a double quotation mark. Use the backslash (\) character to precede these special characters. If a string contains double quotation marks, type a backslash before each internal double quotation mark. The compiler replaces the backslash and character with only the character (in this case, a double quotation mark).

The String equivalent of 0 is an empty string, a string with no characters: “”.

IBM Software Group | Tivoli software

22

Strings

• To create a string, enclose the characters in double quotation marks (" ")

• Escape special characters with a backslash(\)

Page 197: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsString Class

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

String Constructors

Multiple constructors are defined for the String class:

String s1 = new String();String sr2 = new String("Another String");char charArray[] = {'A', ' ', 'S', 't', 'r','i', 'n', 'g' };String s3 = new String(charArray);String s4 = new String(charArray, 2, 3);StringBuffer sBuf = new StringBuffer("A String Buffer");String s5 = new String(sBuf);

In the first example, s1 is created as an empty string. String s2 is assigned the text Another String. Strings s3 and s4 are constructed from a character array. For s4, three characters starting in array position 2 are copied into the string. Java arrays are zero-based, so the result is that s4 contains Str. The string s5 is constructed from a StringBuffer.

The following output reflects the contents of the five constructed strings:

s1 is s2 is Another Strings3 is A Strings4 is Strs5 is A String Buffer

IBM Software Group | Tivoli software

23

String Constructors

String s1 = new String();

String sr2 = new String("Another String");

char charArray[] = {'A', ' ', 'S', 't', 'r','i', 'n', 'g' };

String s3 = new String(charArray);

String s4 = new String(charArray, 2, 3);

StringBuffer sBuf = new StringBuffer("A String Buffer");

String s5 = new String(sBuf);

Page 198: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsString Class

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

String Methods

The String class has several methods. For example, the following method assigns the length of the string s to i:

i = s.length();

Java also has methods to change to lowercase (or uppercase), depending on whether you have a single character or a String.

The following method converts a string to lowercase:

s = s.toLowerCase();

The following method converts a character to lowercase:

c = Character.toLowerCase(c);

You can assign these values back to themselves, or use the values where you want.

IBM Software Group | Tivoli software

24

String Methods

• i = s.length();

• s = s.toLowerCase();• s1 = s.toUpperCase();• s1 = s.trim();• s1 = s.replace(c1, c2);• s1 = s.replace(cs2, cs3);

Page 199: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsString Class

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

The methods described in the following table can be used to create a new string from the original.

Method Usage Description

s1 = s.toLowerCase(); New String with all chars lowercase

s1 = s.toUpperCase(); New String with all chars uppercase

s1 = s.trim(); New String with whitespace deleted from front and back

s1 = s.replace(c1, c2); New String with all c1 characters replaced by character c2

s1 = s.replace(cs2, cs3); New String with all cs2 substrings replaced by cs3

Page 200: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsString Class

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

More String Methods

Some String methods return a part of the string.

The most efficient way to build strings from parts is to use StringBuffer or the essentially identical StringBuilder (Java 5). Their many append() methods perform default conversions from numbers to String before appending them to their current value.

StringBuilder sb = new StringBuilder();int i = 42;sb.append("Answer = ");sb.append(i); // Converts i to string and appends to endsb.append(", ");sb.append(1.0/3.0);String s = sb.toString(); // s is "Answer = 42, 0.3333333333333333"

Method Usage Description

c = s.charAt(i); char at position i in s

s1 = s.substring(i); substring from index i to the end of s

s1 = s.substring(i, j); substring from index i to BEFORE index j of s

IBM Software Group | Tivoli software

25

More String Methods

• s.charAt(2) returns character at the specified index

• s.substring(5,8) returns new String that is a substring

• indexOf(" I") returns index of first occurrence of character 'I'

• length() returns length of String object

Page 201: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsString Class

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

Using String Methods

The following snippet of code illustrates the usage of the startWith() and endsWith() methods. Notice the use of the escape character in the print statements.

package examples.str;

public class StartEnd {

public static void main(String[] args) { String str = "GOOD MORNING";

if (str.startsWith("GO")) System.out.println("startsWith(\"GO\") is true");

if (str.endsWith("ING")) System.out.println("endsWith(\"ING\") is true"); }

}

The program output is:

startsWith("GO") is trueendsWith("ING") is true

IBM Software Group | Tivoli software

26

Using String Methods

• startsWith(String prefix) tests whether the String begins with the specified prefix

• endsWith(String suffix) tests whether the String ends with the specified suffix

Page 202: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsString Class

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

Conversion Methods

The Object class contains a toString() method that every object inherits, but it might not produce the results you want. Override this method to produce the proper results.

Concatenating anything to a string automatically converts it to a string before the concatenation takes place. This common Java idiom performs a string conversion:

int i = 6;Date d = new Date();System.out.println("int i = " + i);System.out.println("Date = " + d);

The output from the two print statements is:

int i = 6Date = Sat Apr 25 15:08:07 CDT 2009

Convert a variable to String, where the variable is any type value (primitive or object) with the valueOf() method:

s = String.valueOf(i); // where i is an ints = String.valueOf(d); // where d is a Date

IBM Software Group | Tivoli software

27

Conversion Methods

• Every object inherits the toString() method from the Object root class

• Override the toString() method

• Concatenation automatically converts the values to a String

• The valueOf() method converts any type to a StringSystem.out.println(String.valueOf(i));

System.out.println(String.valueOf(d));

Page 203: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsString Class

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

Comparison Methods

Do not use the == or != logical operators to make String comparisons. Instead, use the methods described in the following table.

Method Usage Description

i = s.compareTo(t); Compares t to s, returns <0 if s<t, 0 if ==, >0 if s>t

i = s.compareToIgnoreCase(t); Same as previous, ignoring case

b = s.equals(t); True if the two strings s and t have equal values

b = s.equalsIgnoreCase(t); Same as previous, ignoring case

b = s.startsWith(t); True if s starts with t

b = s.startsWith(t, i); True if t occurs starting at index i

b = s.endsWith(t); True if s ends with t

IBM Software Group | Tivoli software

28

Comparison Methods

• i = s.compareTo(t);

• i = s.compareToIgnoreCase(t);

• b = s.equals(t);

• b = s.equalsIgnoreCase(t);

• b = s.startsWith(t);

• b = s.startsWith(t, i) ;

• b = s.endsWith(t);

Page 204: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsString Class

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

Searching Methods

The following methods return -1 if the String or char is not found.

Method Usage Description

i = s.contains(cs); True if cs can be found in s

i = s.indexOf(t); Index of the first occurrence of String t in s

i = s.indexOf(t, i); Index of String t at or after position i in s

i = s.indexOf(c); Index of the first occurrence of char c in s

i = s.indexOf(c, i); Index of char c at or after position i in s

i = s.lastIndexOf(c); Index of last occurrence of c in s

i = s.lastIndexOf(c, i); Index of last occurrence of c on or before i in s

i = s.lastIndexOf(t); Index of last occurrence of t in s

i = s.lastIndexOf(t, i); Index of last occurrence of t on or before i in s

IBM Software Group | Tivoli software

29

Searching Methods

• i = s.contains(cs);

• i = s.indexOf(t);

• i = s.indexOf(t, i);

• i = s.indexOf(c);

• i = s.indexOf(c, i);

• i = s.lastIndexOf(c);

• i = s.lastIndexOf(c, i);

• i = s.lastIndexOf(t);

• i = s.lastIndexOf(t, i);

Page 205: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsString Class

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

Regular Expression Methods

Regular expressions (as of Java 1.4) regexStr parameters are Strings.

Method Usage Description

b = s.matches(regexStr) True if regexStr matches the entire string in s. Same as Pattern.matches(regexStr, s)

s1 = s.replaceAll(regexStr, t) s1 = s.replaceAll(regexStr, t) replaces each substring that matches regexStr with String t

s1 = s.replaceFirst(regexStr, t) Replaces first substring that matches regexStr with String t

sa = s.split(regexStr) Array of all substrings terminated by regexStr

sa = s.split(regexStr, c) Limited to applying regexStr only c times

IBM Software Group | Tivoli software

30

Regular Expression Methods

• b = s.matches(regexStr)

• s1 = s.replaceAll(regexStr, t)

• s1 = s.replaceFirst(regexStr, t)

• sa = s.split(regexStr)

• sa = s.split(regexStr, c)

Page 206: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsString Class

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

Conversions from String

The toString() method is already defined. When Java converts an object to a String, it calls the object’s toString() method. Every class inherits from the Object class and its toString() method is defined, so this method is automatically defined for every class. This method generates a string from an object, but it will not always be useful.

If the subclass does not override toString(), the default probably will not print anything useful. Just as many of the Java library classes override toString() to produce something more useful, you should also override toString() in your classes.

Use the parseInt() method of the Integer wrapper class or the valueOf() and intValue() methods together as follows for integer conversion from a string:

str = "200"; int i = Integer.valueOf(str).intValue(); int j = Integer.parseInt(str);

The same conversion methods are available for the other data types, such as:

double d = Double.parseDouble(str);float f = Float.parseFloat(str);

IBM Software Group | Tivoli software

31

Conversions from String

str = "200";

int i = Integer.valueOf(str).intValue();

int j = Integer.parseInt(str);

double d = Double.parseDouble(str);

float f = Float.parseFloat(str);

Page 207: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsString Class

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

Conversions to String

Call String’s valueOf() to convert a primitive type to a string.

String s = String.valueOf('t'); // ts = String.valueOf(123); // 123s = String.valueOf(1.23f); // 1.23

You can implicitly convert to a string with the concatenation operator +.

s = "" + 't'; // ts = "" + 123; // 123s = "" + 1.23f; // 1.23

IBM Software Group | Tivoli software

32

Conversions to String

String s = String.valueOf('t'); // ts = String.valueOf(123); // 123s = String.valueOf(1.23f); // 1.23

Convert to a string with the concatenation operator +: s = "" + 't'; // ts = "" + 123; // 123s = "" + 1.23f; // 1.23

Page 208: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsString Class

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

Using the split() Method

The split() method breaks a string into substrings. The method uses the concept of a regular expression to specify the delimiters.

The split() method returns a tokenized String array.

IBM Software Group | Tivoli software

33

Using the split() MethodString str = "I am a string. Split me.";String[] words = str.split (" ");for (int i=0; i < words.length; i++)

System.out.println (words[i]);

words = str.split ("\\. ");for (int i=0; i < words.length; i++)

System.out.println (words[i]);

Iamastring.Splitme.

I am a stringSplit me.

Page 209: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsString Class

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

ConvertTemperature Class

The following code converts a temperature to Celsius or Fahrenheit. In this case, the convert method() is defined as a static method and used in a static manner within main().

package examples.str;

public class ConvertTemperature {

private static final String CELSIUS2FAHRENHEIT = "C"; private static final String FAHRENHEIT2CELSIUS = "F"; public static void main(String[] args) { String tempType = args[0]; double temperature = Double.parseDouble(args[1]); ConvertTemperature.convert(tempType,temperature); } public static void convert(String type, double temp) { ....... }

}

IBM Software Group | Tivoli software

34

ConvertTemperature Classpublic class ConvertTemperature {

private static final String CELSIUS2FAHRENHEIT = "C";private static final String FAHRENHEIT2CELSIUS = "F";

public static void main(String[] args) {String tempType = args[0];double temperature = Double.parseDouble(args[1]);

ConvertTemperature.convert(tempType,temperature); }

public static void convert(String type, double temp) { } }

Page 210: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsString Class

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

ConvertTemperature Class Variation

The following code duplicates ConvertTemperature, but the convert() method is not defined as a static method. Now an instance of a ConvertTemperature object must be created to use the convert() method.

package examples.str;

public class ConvertTemperature {

private static final String CELSIUS2FAHRENHEIT = "C"; private static final String FAHRENHEIT2CELSIUS = "F"; public static void main(String[] args) { String tempType = args[0]; double temperature = Double.parseDouble(args[1]); ConvertTemperature ct = new ConvertTemperature(); ct.convert(tempType,temperature); } public void convert(String type, double temp) {

......}}

IBM Software Group | Tivoli software

35

ConvertTemperature Class Variationpublic class ConvertTemperature {

private static final String CELSIUS2FAHRENHEIT = "C";private static final String FAHRENHEIT2CELSIUS = "F";

public static void main(String[] args) {String tempType = args[0];double temperature = Double.parseDouble(args[1]);

ConvertTemperature ct = new ConvertTemperature();ct.convert(tempType,temperature);

}

public void convert(String type, double temp) { }}

Page 211: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsString Class

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

The convert() Method

The following code is the convert() method from the ConvertTemperature class. The following example is the non-static version:

public void convert(String type, double temp) { double result = 0;

if (type.equalsIgnoreCase(CELSIUS2FAHRENHEIT)) { result = temp * (9/5) + 32; System.out.println(temp +

" Celsius = " + result + " Fahrenheit");}

else if (type.equalsIgnoreCase(FAHRENHEIT2CELSIUS)) { result = (temp-32) * (9/5); System.out.println(temp +

" Fahrenheit = " + result + " Celsius"); } else System.out.println("Temperature code must be C or F"); }

Just add the keyword static to the method’s signature to change it to a static method.

IBM Software Group | Tivoli software

36

The convert() Method

public void convert(String type, double temp) {double result = 0;

if (type.equalsIgnoreCase(CELSIUS2FAHRENHEIT)) {result = temp * (9/5) + 32;System.out.println(temp + " Celsius = " + result + " Fahrenheit");

}else if (type.equalsIgnoreCase(FAHRENHEIT2CELSIUS)) {

result = (temp-32) * (9/5);System.out.println(temp + " Fahrenheit = " + result + " Celsius");

}else

System.out.println("Temperature code must be C or F"); }

Page 212: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsString Class

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

Student Exercise

Open your Student Exercises book and perform the exercises for this unit.

IBM Software Group | Tivoli software

37

Student Exercise

Page 213: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsString Class

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

Review Questions

1. In Java, what does static modifier mean?

2. What is the difference between a constructor and a method of a class?

3. What is the purpose of garbage collection in Java?

Page 214: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsString Class

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

Review Answers

1. In Java, what does static modifier mean?

Static means one per class, not one for each object, no matter how many instances of a class exist.

2. What is the difference between a constructor and a method of a class?

A constructor is used to create objects of that class. It has the same name as the class, has no return type, and is invoked using the new operator. A method has its own name and a return type (which can be void), and is invoked using the dot operator whether or not the method is static.

3. What is the purpose of garbage collection in Java?

In Java, garbage collection is used to identify and deallocate objects that are no longer needed by a program so that their resources can be reused.

Page 215: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 5: Classes, Constructors, and StringsString Class

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

Summary

IBM Software Group | Tivoli software

38

Summary

You should now be able to:Use classes

Use constructors

Use the String class

Page 216: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 5: Classes, Constructors, and StringsString Class

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

Page 217: Ibm enterprise it and asset management 7.1 java for customization training

• • • ••

6-1

Unit 6: Java Exceptions, I/O, and Inheritance

© 2009 IBM Corporation

Unit 6: Java Exceptions, I/O, and Inheritance

Page 218: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and Inheritance

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

Introduction

This unit covers access control for data and methods in more detail, in addition to implementing inheritance and polymorphism with abstract classes and interfaces. You will also implement Java exception handing and Java I/O basics.

Objectives

IBM Software Group | Tivoli software

2

Objectives

Upon completion of this unit, you will be able to:

Describe how Java handles access control for data and methods

Overload and override Java methods

Describe the basics of Java I/O classes

Implement exception handling

Page 219: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Lesson 1: Access Control

Access to a class and its constructors, methods, and variables is controlled using access modifiers. In this way, a class can control what information can be accessed by other classes. Encapsulation is achieved by minimizing access whenever possible.

A member has package (default) accessibility when no modifier is specified.

IBM Software Group | Tivoli software

3

Access Control

• Access modifiers control access to classes and their contents

• A class controls what information can be accessed by other classes

• Encapsulation is achieved with access modifiers

Page 220: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Access Control Modifiers

The access modifiers are public, private, protected, and default.

1. public: Variables, methods, and constructors declared public within a public class are visible to any class in the Java program, whether or not they are in the same package.

2. private: Variables, methods, and constructors declared private cannot be accessed outside of the enclosing class. A best practice strategy is to make all fields private and provide public getter and setter methods.

3. protected: Variables, methods, and constructors declared protected can be accessed by subclasses in other packages. They also can be accessed by classes in the same package, even if they are not a subclass of the protected class.

4. default: Variables, methods, and constructors have package accessibility when no modifier is specified.

IBM Software Group | Tivoli software

4

Access Control Modifiers

• Public: Accessible by all

• Private: Cannot be accessed outside class

• Protected: Accessed by subclasses and classes within same package whether subclass or not

• Default: Package access when nothing is specified

Page 221: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Access Control Example

The example on this slide is a definition of the Account class. The class contains a private variable named totalAmount, which is only accessible within the class itself. Other classes that need access to this variable use the public getter and setter methods that are defined within the class.

IBM Software Group | Tivoli software

5

Access Control Example

public class Account {

private double totalAmount = 0;

public void setTotalAmount(double value) {

totalAmount = val;

}

public double getTotalAmount() {

return totalAmount; }

}

Page 222: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

abstract, final, and static Modifiers

There are other modifiers in addition to public, private, and protected, and certain combinations of modifying keywords are allowed.

Classes can be further modified with the keywords abstract or final. An abstract class cannot be instantiated, and it can contain abstract methods. A final class cannot be subclassed.

Variables and methods can be modified to be static or final. Final variables and methods cannot be changed. Variables are constants and their methods cannot be overridden. A static method or variable belongs to the class, rather than any particular instance of the class. There is one copy of a static variable for all instances of the class. If one instance changes the static value, the other instances see the updated value. For methods, this means that the method can be called without having to create an instance.

An abstract method is a method that is not implemented. The method must be implemented in a subclass if that subclass is to be a concrete class, meaning that it can be instantiated.

IBM Software Group | Tivoli software

6

abstract, final, and static Modifiers

• abstract For methods: Must be defined in concrete class

For classes: Cannot be instantiated and can contain abstract methods

• finalFor methods and variable: Cannot be modified

• staticFor methods and variable: Associated with class rather than instance

Page 223: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Using the Keyword this

The keyword this is used to refer to the current class instance. Use it to refer to variables or methods of the current class and resolve any ambiguity between instance variables and parameters.

You can also use it to pass the current object as a parameter to another method.

In the code illustrated on the slide, this is used for the current instance. Because this is an instance of a class, it cannot be used inside a static method.

IBM Software Group | Tivoli software

7

Using the Keyword this

• Refers to current class instance

• Is used to refer to variables or methods

• Resolves ambiguitypublic class Account {private double total = 0;

public void setTotal(double total) {this.total = total;

}public double getTotal() {return total;

} }

Page 224: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

this Usage

public final class Account {

private double total = 0; private double creditLine = 0;

public Account() { this(0,0); }

public Account(double total) { this.total = total; creditLine = 0; }

public Account (double total, double creditLine) { this.total = total; this.creditLine = creditLine; }

public void setTotal(double total) { this.total = total; }

IBM Software Group | Tivoli software

8

this Usagepublic final class Account {

private double total = 0;private double creditLine = 0;

public Account() {this(0,0);

}

public Account(double total) {this.total = total;creditLine = 0;

} …….

Page 225: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

public double getTotal() { return total; }

public Account getAccount() { return this; }}

Page 226: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Passing Arguments

Java passes all arguments by value. Java manipulates objects by reference, and all object variables are references, but Java does not pass method arguments by reference.

public class Banking { static Account a = new Account(); ...... public static void main(String[] args) { a.setTotal(2500); a.noChangeToTotal(a.total); a.changeToTotal(a); ........

public final class Account {

public double total = 0; .... ........ public double noChangeToTotal(double total) { total = total + 1000; return total; } public double changeToTotal(Account obj) { obj.total = obj.total + 1000; System.out.println("Testing total = " + obj.total); return obj.total; } }

IBM Software Group | Tivoli software

9

Passing Arguments

public final class Account {public double total = 0; ............public double noChangeToTotal(double total) {return total = total + 1000; }

public class Banking {static Account a = new Account();......public static void main(String[] args) {a.setTotal(2500);a.noChangeToTotal(a.total);.......

• Arguments are passed by value

• A copy of the argument is sent to the method

Page 227: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Pass by Value

Pass by value is an important principle in Java. If a variable is passed, the method receives a copy of the variable’s value. The value of the original variable cannot be changed within the method. The reason is that the method does not have access to the original variable, only to a copy of the value.

IBM Software Group | Tivoli software

10

Pass by Value

Page 228: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Passing Objects by Value

If the variable passed is an object, then a reference to an object is passed to the method as an argument. Objects are not passed to or returned by methods. Rather, a reference to an object is passed or returned.

IBM Software Group | Tivoli software

11

Passing Objects by Value

public final class Account {public double total = 0; ............public double noChangeToTotal(double total) {return total = total + 1000; }

public double changeToTotal(Account obj) {return obj.total = obj.total + 1000;} }

public class Banking {static Account a = new Account();......public static void main(String[] args) {a.setTotal(2500);a.noChangeToTotal(a.total);a.changeToTotal(a);.......

•A copy of the object reference is sent to the method

•The reference will not change but the object does

Page 229: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Passing an Object Reference

In general, pass by reference means passing a copy of the object’s address rather than passing a copy of the object itself. Pass by value means passing a copy of the value as an argument.

IBM Software Group | Tivoli software

12

Passing an Object Reference

Page 230: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

A Copy of an Object Reference

In Java, pass by value refers to passing a constant or a variable that contains a primitive data type. Pass by reference refers to passing an object variable (a reference to the object) to a method. In both cases a copy of the variable is passed to the method. A copy of the value is passed for a primitive data type variable and is a copy of the reference for an object variable.

IBM Software Group | Tivoli software

13

A Copy of an Object Reference

• Pass by value refers to primitive data type variables

• Pass by reference refers to passing the reference of an object variable

• A copy is passed in either case:– A copy of the primitive data type variable’s value

– A copy of the reference that points to an object variable

• The object can be changed unless it has been defined as immutable

Page 231: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Pass by Reference

A method receiving an object variable as an argument receives a copy of the reference to the original object. Thus it is possible to change the original object, because the copy of the reference refers to the same original object. One exception is a String object, which is immutable in Java.

IBM Software Group | Tivoli software

14

Pass by Reference

Page 232: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Garbage Collection Revisited

When there are no more references to a memory block that represents a Java object, the memory can be recycled. Automatic garbage collection determines when an object is no longer referenced and makes that memory available for future objects.

Garbage collection ideally solves the problems common to allocating and deallocating memory on the heap. However, although the main cause of memory leaks is addressed, Java programs might still contain possible memory leaks. The following code sample contains a block of memory that was originally allocated to the object variables a and b, and is no longer referenced by any object.

public class Banking {

static Account a = new Account(); static Account b = a; static Account c = new Account ();

public static void main(String[] args) { a = c; b = a; }

IBM Software Group | Tivoli software

15

Garbage Collection Revisited

• Automatic garbage collection determines if a block of memory is no longer referenced

• Garbage collection makes that memory available for future use

• You can improve the performance of garbage collection

Page 233: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Garbage Collection and Object References

Although the deallocation of memory is handled automatically by garbage collection, there are two common causes of memory problems:

• Memory leaks: When an allocated memory block was never deallocated and is no longer reachable, this memory will remain allocated. If the block of code that is creating this problem occurs many times, the program might run out of memory and crash.

• Dangling references: This problem occurs when memory is deallocated, but there are still references that point to this memory. The memory is no longer valid and will be reallocated when there is a new request for memory. However, the dangling references will be used, and they still point to the original memory.

IBM Software Group | Tivoli software

16

Garbage Collection and Object References

• Memory leaks: Memory is unreachable but remains allocated

• Dangling references: Memory is deallocated but there are still references that point to this memory

Page 234: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Memory Leaks

There are some techniques you can use to improve the performance of garbage collection. One technique is to assign null to variables that you are no longer using.

Local variables are deallocated automatically when a method returns, but static variables are allocated for the lifetime of a program. You can assign a null to any static variable, especially static variables that reference large data structures that are no longer used.

Sometimes a Java program will create an object in a loop. For example:

for (int i = 0; i < 5000000; ++i){ MyClass obj = new MyClass(i); // do some additional processing with obj}

This code creates 5,000,000 instances of MyClass and the program can potentially run out of memory.

Keep garbage to a minimum and reuse your objects whenever possible. Every time an instance of an object is created, potential garbage is created. The following code negates the potential of running out of memory by creating only one object instance.

IBM Software Group | Tivoli software

17

Memory Leaks

• Possible to improve the performance of garbage collection

• The following code has the potential to crash the system: for (int i = 0; i < 5000000; ++i){

MyClass obj = new MyClass(i);

// do some additional processing with obj}

Page 235: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

MyClass obj = new SomeClass ();for (int i = 0; i < 5000000; ++i){ obj.setInt (i); // do additional processing with obj}

By rewriting the code to use a single object instance, the amount of garbage produced has been significantly reduced.

Page 236: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Overloading Methods

It is often useful or necessary to perform the same action, but with different parameters. Overloading a method refers to creating multiple methods with the same name.

The compiler can only distinguish methods with the same name if their function signatures are different. To accomplish this, use a different number of parameters or different types of parameters.

The following examples show overloaded constructors:

public Account() { …… }

public Account(double total) { ….. }

public Account (double total, double creditLine) {……..}

public Account(double total, String name) { ….. }

public Account (double total, Date date) {……..}

IBM Software Group | Tivoli software

18

Overloading Methods

• Overloading methods have the same name, different signatures

• Different parameters

public Account() {…… }

public Account(double total) {….. }

public Account (double total, double creditLine) {……..}

Page 237: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Guidelines for Overloading Methods

To avoid confusion, make sure that all the methods with the same name do the same thing. All methods sharing the same name should return the same value and all should be either static or instance methods. The language does not enforce this condition, but it is a good practice to follow.

Because overloaded methods should be doing the same thing, it is common for one to call another while supplying default values for the extra parameters when needed.

public final class Account {

prvate double total = 0; private double creditLine = 0;

......

public init() { init(0,0); }

public init() (double total) { init(total, 0); }

public init() (double total, double creditLine) { this.total = total;

IBM Software Group | Tivoli software

19

Guidelines for Overloading Methodspublic final class Account {

prvate double total = 0;private double creditLine = 0;

public init() {init(0,0);

}public init() (double total) {

init(total, 0);}public init() (double total, double creditLine) {

this.total = total;this.creditLine = creditLine;

}

Page 238: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

this.creditLine = creditLine; }

.......

Page 239: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceAccess Control

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

Overloading versus Overriding

Although these terms are both related to multiple definitions of methods, overloading and overriding do not have the same meaning.

Overloading is creating multiple method definitions that differ in their signature. The number or types of parameters differ, but the return type does not.

Overriding is redefining a method that exists in a superclass. You must use exactly the same number and types of parameters.

IBM Software Group | Tivoli software

20

Overloading versus Overriding

• Do not confuse overloading a method with overriding a method

• Overloading creates multiple method definitions with different signatures

• Overriding is redefining a method in a superclass

• Overriding a method requires the function signature to be the same

Page 240: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceExceptions

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

Lesson 2: Exceptions

When a program generates an error, Java throws an exception.

When an exception is thrown, execution of that statement stops and Java searches for a part of the program to catch the exception. Java then throws this exception to that part of the program. It is not necessary to catch most exceptions. However, try to catch all exceptions caused by things over which you have no control, such as exceptions due to invalid user input or I/O problems.

IBM Software Group | Tivoli software

21

Exceptions

• Java throws an exception when a program generates an error

• Execution stops

• If there is a part in the program that can catch and handle the exception, then the exception is thrown to that part of the program

• Attempt to catch exceptions caused by things over which you have no control

Page 241: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceExceptions

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

Exception Syntax

Create a try...catch block around any section of code that might cause a user-generated exception. The following example shows the syntax:

try { // Statements that might cause a problem

} catch (exceptionName parameterName) {

// Statements to execute if exception is thrown.

}

IBM Software Group | Tivoli software

22

Exception Syntax

try {

// Statements that might cause a problem

} catch (exceptionName parameterName) {

// Statements to execute if exception is thrown.

}

Page 242: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceExceptions

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

Exception Propagation

1. When an exception is thrown, Java checks whether the code that caused the exception is inside a try block that can handle the exception. If the try statement has a catch clause that can handle this type of exception, then it goes to that code. After the catch clause is executed, execution resumes after the end of the entire try statement. It is not possible to return to the point at which the exception was thrown.

2. If the exception is not inside a try block, Java goes up the call stack and looks at the statement that called this method. Java then checks for a try block surrounding that call. If it finds an enclosing try block that has a catch clause for this kind of exception, the catch clause is executed. Execution then continues after that try statement. Java continues moving up the call stack until it finds an enclosing try block.

3. If Java does not find an enclosing try block and catch clause, the exception is caught by the Java system method that called main() initially. An error message is issued and the program terminates.

IBM Software Group | Tivoli software

23

Exception Propagation

• When an exception is thrown, Java looks to see if thecode is inside a try block that can handle the exception

• If it is not, Java moves up the call stack to find a tryblock that has a catch clause for the exception

• If it does not, the exception is caught by the system that called main() and the program terminates

Page 243: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceExceptions

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

Methods and Exceptions

A method must either catch exceptions or specify the exceptions that it can throw.

The following example demonstrates the syntax used to add the throw clause to the method’s signature:

public String someMethod(String s) throws IOException {....}

IBM Software Group | Tivoli software

24

Methods and Exceptions

• A method must either catch the exception or specify the exceptions it can throw

• The throw clause can be added to a method signaturepublic String readFile(String fName) throws IOException

Page 244: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceExceptions

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

Catching Exceptions

try block

• Must be accompanied by at least one catch block or a finally block

• The code could throw the Exception or call a method that can throw the Exception

• Can be any number of lines of code

catch block

• Handles the exception

• Code is executed if, and only if, exception is thrown

• Can be more than one catch block associated with one try block to catch different kinds of exceptions

• After being caught, there is no further processing of other catch blocks

finally block

• Is entered regardless of what occurs

• finally block code performs cleanup, closes files, and so on

IBM Software Group | Tivoli software

25

Catching Exceptions

public String readFile (String fName) {

try {

}

catch(SomeException e) {

}

catch(SomeOtherException e) {

}

finally {

}

}

Page 245: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceExceptions

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

Rethrowing an Exception

You can either rethrow the exception in the catch block or rethrow another exception.

The following code rethrows the exception:

catch (IOException){ e.GetMessage(); e.printStackTrace(); throw e; // rethrow the exception}

The following code rethrows another exception:

catch (IOException){ e.GetMessage(); e.printStackTrace(); throw new ApplicationException(“Cannot process error”);}

If your code must do some cleanup (such as close files), it can catch exceptions, do the cleanup, and then rethrow the exception.

IBM Software Group | Tivoli software

26

Rethrowing an Exception

catch (IOException e){

e.GetMessage();e.printStackTrace();throw e;

}

{ e.GetMessage();e.printStackTrace();throw new ApplicationException(" Cannot process

error"); }

Page 246: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceExceptions

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

For debugging purposes you can print a trace of the current call stack with the following statement:

e.printStackTrace();

Page 247: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceExceptions

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

To Catch or Throw

It is a programming decision whether to catch or to throw an exception. Catching is most suitable when it is appropriate and realistic to deal with the exception situation then and there. Throwing is more appropriate if the exception is the caller’s responsibility.

You can declare a method as throwing any number of exception types.

public String someMethod(String s) throws IOException, NumberFormatException {....}

IBM Software Group | Tivoli software

27

To Catch or Throw

• Programming decision to catch or throwDecide whether suitable to deal with exception then and there

Decide whether it is a caller’s responsibility

A method can be declared to throw any number of exceptions

public String someMethod(String s) throws IOException, NumberFormatException {

....}

Page 248: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceExceptions

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

Java Exception Hierarchy

Error subclasses represent very serious errors from which a program usually does not expect to catch and recover. These errors include such problems as a missing class file or running out of memory.

Exception subclasses represent errors from which a program can usually recover. Except for RuntimeException and its subclasses, they usually represent errors that a program expects to occur in the normal course of program execution.

RuntimeException and its subclasses represent exceptions that a program does not expect to occur. They represent what are most likely programming errors, rather than errors caused by invalid user input or the runtime environment.

IBM Software Group | Tivoli software

28

Java Exception Hierarchy

Page 249: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceExceptions

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

User-Defined Exceptions

You can also create your own exceptions.

User-defined exceptions are the separate Exception classes defined by the user for specific purposes. A user-defined exception can be created simply by extending the Exception class. In this way, custom exceptions are generated (using throw) and caught in the same way as other exceptions.

class myCustomException extends Exception {// Put anything inside the class definition}

The class must only exist to be an exception.

IBM Software Group | Tivoli software

29

User-Defined Exceptions

• A user-defined exception is created by extending an Exception class

• Applications can create a hierarchy of customized exceptions to handle specific error conditions

• MXException hierarchy exists, in addition to standard Java exceptions, RMI exceptions, and so on

Page 250: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceExceptions

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

Catch Blocks

1. The method calc() is called from within the recordTrans() method.

2. The method calc() calls the checkTotal() method.

3. The checkTotal() method throws a new exception.

4. The new exception is caught by the calc() method and rethrown to the recordTrans() method.

IBM Software Group | Tivoli software

30

Catch Blocks

Page 251: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceExceptions

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

try...finally Block

Exceptions provide a good mechanism for error processing. But the simplicity of throwing an exception at a deep level and catching it at a much higher level might create problems at the skipped levels.

Any of these methods could have left data or a resource in an inconsistent state. Any critical code where this might be possible should include cleanup code in a try...finally block.

Java enables you to define a finally block that will execute, regardless of any exceptions that might have occurred. The sequence in which the finally block is executed is:

• After the try block, if finally is after a try block without a matching catch block

• After the try block, if placed after the catch block and there is no exception thrown and caught

• After the catch block, if there is an exception and it is handled by the catch block

IBM Software Group | Tivoli software

31

try….finally Block

• A finally block will execute, regardless of any exceptions that might have occurred

• The finally block executes: After the try block, if finally is after a try block without a matching catch block

After the try block, if placed after the catch block and there is no exception thrown and caught

After the catch block, if there is an exception and it is handled by the catch block

Page 252: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceExceptions

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

finally

A few unusual situations would prevent all of the code in the finally block from executing:

• Use of system.exit()

• Loss of power

• Death of the thread that is running the code

• An exception thrown in the finally block

IBM Software Group | Tivoli software

32

finally

Page 253: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceJava I/O

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

Lesson 3: Java I/O

Integrated into most computer programming is the concept of reading, writing, and transferring data between sources. Basic input and output is necessary; for example:

• Reading data from or writing data to a buffer within the same method

• Exchanging data between processes that are running on systems located in different countries

IBM Software Group | Tivoli software

33

Java I/O• Most programs require the ability to read, write, and transfer data

between sources

• It could be between objects, such as reading data from or writing data to a buffer within the same method

• It could be exchanging data between processes that are running on systems located in different countries

• Java provides stream-based I/O classes

Page 254: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceJava I/O

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

Streams

Java stream classes provide a flexible and powerful framework for transferring data between objects.

Streams abstract the concept of exchanging information between various I/O devices (such as a file, console, keyboard, mouse, NIC, or disk drive). Streams provide an interface for programmers to interact with different sources of I/O.

A side effect of stream processing is blocking. With blocking, a program encounters a situation where it has to wait for a device (such as a disk drive or network connection) to process a request. The stream classes and methods were created with blocking in mind. The effects are minimized so that blocking does not affect the rest of the program.

IBM Software Group | Tivoli software

34

Streams

• The stream classes provide a flexible and powerful framework for transferring data between objects

• Streams abstract the concept of exchanging information between various I/O devices

• Streams provide an interface for programmers to interact with different sources of I/O

• The concept of a stream is that data enters one end of a data channel and exits the other end in the same sequence

Page 255: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceJava I/O

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

Key Classes in java.io Package

The Java implementation of streams starts with InputStream and OutputStream. These are two abstract classes, and more specialized streams for input and output operations are derived from these two classes.

The abstract InputStream class includes methods that provide the fundamental methods for all of the input stream classes. The abstract class OutputStream provides the basic output functionality used by all its derived output stream classes.

File is a class within the java.io package, but it is not part of the stream classes. The File class is used to represent a file in terms of the host file system. It provides basic file and directory functions such as making directories, enumerating files in a directory, deleting files, and renaming files. The FileDescriptor class (also not part of the stream classes) is used to represent a handle to an open file.

FileInputStream and FileOutputStream provide basic stream capabilities for dealing with files. Be aware that the FileOutputStream starts writing at the beginning of a file and any data in the file before it is opened will be lost. You can use the RandomAccessFile class in conjunction with FileOutputStream to append data to a file or write to a specific location.

Stream readers and writers are designed to read and write byte streams as character streams. Reader and Writer are the abstract base classes for working with character streams.

IBM Software Group | Tivoli software

35

Key Classes in java.io Package

• InputStream and OutputStream

• File

• FileDescriptor

• FileInputStream and FileOutputStream

• RandomAccessFile

• Reader and Writer

Page 256: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceJava I/O

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

Efficient I/O Classes

A buffer stream uses a storage place where data can be kept. When it is needed by a program, the buffer stream reads data from or writes data to the buffer. By using a buffer, you can transfer data without always going back to its original source. The BufferedInputStream class adds a buffer, or cache, to the stream to improve the performance of some input streams. You can specify the size of the buffer used by BufferedInputStream class when it is created, or accept the default of 2048 bytes.

The BufferedOutputStream class provides the same performance gains as the BufferedInputStream class, but its buffer is used for an output stream. Requests to write to an output stream are cached in an internal buffer. When it reaches capacity, the internal buffer is flushed to the output stream. The size of the internal buffer defaults to 512 bytes, but you can change the size by using the appropriate constructor and specifying the size you want.

BufferedReader and BufferedWriter are subclasses of Reader and Writer. They are the concrete (non-abstract) classes for working with character streams.

IBM Software Group | Tivoli software

36

Efficient I/O Classes

• BufferedInputStream

• BufferedOutputStream

• BufferedReader extends the Reader class

• BufferedWriter extends the Writer class

Page 257: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceJava I/O

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

The PrintWriter Class

The PrintWriter class defines the overloaded print() and println() methods for all of the primitive data types plus Object. A PrintWriter object can be created from a stream or from another Writer object.

Unlike the other stream objects, the PrintWriter object methods do not throw I/O exceptions. Instead, the programmer must call the checkError() method for the object itself. The return value is true if an error occurred; otherwise it is false.

IBM Software Group | Tivoli software

37

The PrintWriter Class

• The PrintWriter class contains methods for formatting binary data and writing that data to a stream

• It defines overloaded print() and println()

• Unlike the other stream objects, the PrintWriter object methods do not throw I/O exceptions

Page 258: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceJava I/O

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

Using Text Files

It is often possible to use abstract base classes rather than specific concrete classes. It is usually best to use buffering classes when reading and writing text files.

FileInputStream fis=new FileInputStream("test.txt"); BufferedReader bin=new BufferedReader(fis);

FileOutputStream fos=new FileOutputStream("test.txt"); BufferedWriter bout=new BufferedWriter(fos);

The BufferedReader class contain the useful readLine() method that returns a String. The BufferedWriter class contains the write() and newLine() methods.

The FileReader and FileWriter classes use the system’s default character encoding. However, if the default is not appropriate (such as when reading an XML file, which specifies its own encoding), alternatives are as follows:

FileInputStream fis=new FileInputStream("test.txt"); InputStreamReader in=new InputStreamReader(fis, "UTF-8");

FileOutputStream fos=new FileOutputStream("test.txt"); OutputStreamWriter out=new OutputStreamWriter(fos, "UTF-8");

Be aware of IOException and FileNotFoundException exceptions and code accordingly.

IBM Software Group | Tivoli software

38

Using Text Files

FileInputStream fis=new FileInputStream("test.txt"); BufferedReader bin=new BufferedReader(fis);

FileOutputStream fos=new FileOutputStream("test.txt"); BufferedWriter bout=new BufferedWriter(fos);

FileInputStream fis=new FileInputStream("test.txt"); InputStreamReader in=new InputStreamReader(fis, "UTF-8");

FileOutputStream fos=new FileOutputStream("test.txt"); OutputStreamWriter out=new OutputStreamWriter(fos, "UTF-8");

• Streams are resources that must be managed

• The close() method must be called

Page 259: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceJava I/O

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

Streams are resources that must be managed. The close method must always be called, or you will have a resource leak. Closing the file will automatically flush the stream and close any underlying stream.

Page 260: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceJava I/O

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

File I/O Example

The following example reads the contents of a text file and writes the contents to a second file in uppercase:

public class File2UpperCase {

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

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

boolean exists = inFile.exists(); if (!exists) { System.out.println(inFile.getName() + "does not exist");

return; } try { upperCaseCopy(inFile, outFile); } catch (IOException e) { System.out.println(e); System.exit(1); } }}

IBM Software Group | Tivoli software

39

File I/O Examplepublic class File2UpperCase {

public static void main(String[] args) throws IOException {// check for correct number of arguments

File inFile = new File(args[0]); // create input File objectFile outFile = new File(args[1]); //create output File object

try {upperCaseCopy(inFile, outFile);

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

}}

Page 261: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceJava I/O

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

Changing File Contents

The code is implemented to use buffering and to use readLine() to read one line at a time. The readLine() method returns:

• The content of a line minus the newline

• Null for the end of the stream

• An empty String if two newlines are in sequence

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

String line = null; while ((line=reader.readLine()) != null) { writer.write(line.toUpperCase()); writer.newLine(); }

reader.close(); writer.close(); }

IBM Software Group | Tivoli software

40

Changing File Contentspublic static void upperCase(File in, File out) throws IOException {

BufferedReader reader = new BufferedReader(new FileReader(in));BufferedWriter writer = new BufferedWriter(new FileWriter(out));

String line = null;while ((line=reader.readLine()) != null) {

writer.write(line.toUpperCase());writer.newLine();

}

reader.close(); writer.close();

}

Page 262: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Lesson 4: Inheritance

Inheritance is a powerful feature of object-oriented programming. It not only supports code reuse, but it is also necessary to implement polymorphism.

IBM Software Group | Tivoli software

41

Inheritance

• Inheritance allows code reuse

• Inheritance lays the foundation for polymorphism

Page 263: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Principles of Object-Oriented Programming

Encapsulation is the first of three fundamental principles in object-oriented programming. Inheritance is the second principle.

Encapsulation is an object’s ability to contain (or encapsulate) its data and methods. Data hiding is the ability of an object to control access to its data. Data hiding is also a consequence of the encapsulation principle. Encapsulation is supported by declaring contents of a class as public, protected, or private.

Inheritance is the ability to reuse the properties and methods of another class while adding more functionality. An example of this is a driver’s license. You could create a generic license class that is common to all states in the United States. More specific classes could be defined for more specific states. The generic license class is known as the parent (or superclass or base class) and the specific classes are known as children (or subclasses or derived classes). The concept of inheritance enhances the ability to reuse code.

IBM Software Group | Tivoli software

42

Principles of Object-Oriented Programming

• Encapsulation, inheritance, and polymorphism

• Encapsulation is an object’s ability to contain (or encapsulate) its data and methods

Encapsulation is supported by declaring contents of a class as public, protected, or private

• Inheritance is the ability to reuse the properties and methods of another class while adding more functionality

An example is a driver’s license

Page 264: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

The Object Class

The Object class is the highest superclass of Java. It is called the root class. Every other class is a subclass (child, descendant, or derived class) of the Object class.

The Object class includes the following methods:

• clone()

• copy(Object src)

• equals()

• finalize()

• getClass()

• hashCode()

• notify()

• notifyAll()

• toString()

• wait()

In Java, every class contains these methods because they are inherited from the root class Object.

IBM Software Group | Tivoli software

43

The Object Class

• The Object class is the root class

• Every class is a subclass of the Object class

• The Object class includes the following methods:clone() hashCode() copy(Object src) notify() equals() notifyAll() finalize() toString() getClass() wait()

Page 265: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

The extends Keyword

Java uses the extends keyword to establish the relationship between a superclass (base, parent) and a subclass (derived, child).

public class SubClass extends SuperClass {}

The subclass assumes (inherits) all the properties of the superclass and can add its own properties and methods. It can also override existing methods inherited from the superclass.

Overridden methods change the inherited implementation but retain the same method signature (method name, number of parameters and parameter types).

IBM Software Group | Tivoli software

44

The extends Keyword

• extends establishes the relationship between a superclassand a subclass

public class SubClass extends SuperClass {}

• The subclass inherits all the properties of the superclass

• The subclass can add its own properties and methods

• The subclass can override existing methods inherited from the superclass

• Overridden methods change the inherited implementation

• Overridden methods retain the method signature

Page 266: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Constructor Execution Revisited

When extending a class constructor, you can reuse the superclass constructor and overridden superclass methods by using the reserved word super. A super() call to a superclass constructor must come first in the subclass constructor. The reserved word this is used to call another constructor in the same class.

If the first line of a constructor is not a constructor call using the reserved words super or this, the compiler inserts a call to the default superclass constructor automatically.

IBM Software Group | Tivoli software

45

Constructor Execution Revisited

• A super() call to a superclass constructor must come first in the subclass constructor

• The reserved word this is used to call another constructor in the same class

• If the first line of a constructor is not a constructor call using the reserved words super or this, the compiler automatically inserts a call to the default superclassconstructor

Page 267: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Constructor Example

Every object contains the instance variables of its class and all the instance variables of every superclass (the parent class, the parent’s parent class, and so on). The variables of the superclass must be initialized before the instance variables of the class.

When you create an object, you must call the constructors of all superclasses to initialize their fields. Java does this automatically at the beginning if you do not do it.

Constructors are executed from the superclass to the subclass.

class ConstructorExecution { public static void main(String[] args) { C c = new C(); }}

class C extends B { C() { System.out.println("C() constructor"); }}

class B extends A { B() {

IBM Software Group | Tivoli software

46

Constructor Exampleclass ConstructorExecution {

public static void main(String[] args) {C c = new C();

}}

class C extends B {……}

class B extends A {…… }

class A {……… }

Page 268: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

this(10); System.out.println("B() constructor"); }

B(int i) { }}

class A { A() { System.out.println("A() constructor"); }

Page 269: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Constructors with and without Parameters

In two cases you must explicitly write the constructor for your parent class:

1. If there is no parameterless parent constructor. Sometimes it does not make sense to create an object without supplying parameters.

2. If you want to call a parent constructor that has parameters (instead of the default constructor, which has no parameters).

For example, if you are defining a subclass of class A, you might use the following code:

class B extends A { // constructor public B(String title) { super(title);

In this example you want to make use of the A constructor that takes a title as a parameter. You could also let the default constructor be called and follow it with a call to a setter method.

class B extends A { //constructor public B(String title) { // Default superclass constructor automatically

IBM Software Group | Tivoli software

47

Constructors with and without Parameters

• Sometimes you must include a constructor call with parameters to the parent

class B extends A {public B(String title) {super(title);

}

class B extends A {public B(String title) {// Default superclass constructor automatically inserted by compiler// Call setter method in superclasssetTitle(title);

}

Page 270: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

// inserted by compiler

// Call setter method in superclass setTitle(title);

Page 271: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Abstract Class

The superclass is more general than its subclass or subclasses. Often, the superclass will be set up as an abstract class that does not allow objects of its type to be created. To do this the reserved word abstract is included in the class definition. In this case, only objects of the subclass can be instantiated.

Abstract methods are methods without an implementation. Subclasses must provide the method implementation for their particular functionality. If the method was specified by the superclass, it should usually be overridden in each subclass.

public abstract class A { private String name;

public A(String nm) // constructor method { name=nm; }

public String getName() // non-abstract method { return (name); }

public abstract void speak(); // note absence of {}}

IBM Software Group | Tivoli software

48

Abstract Class

• Abstract class cannot be instantiated

• Abstract methods must be overridden in any subclass that extends the abstract class

public abstract class A {

private String name;

public A(String nm) // constructor method{ name=nm; }

public String getName() // non-abstract method{ return (name); }

public abstract void speak(); // note absence of {}}

Page 272: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Interfaces

Java does not allow multiple inheritance. To incorporate elements of multiple classes, Java uses an interface. Interfaces are similar to abstract classes but all methods are abstract and all properties are static final. To build an interface for the subclasses of A, this interface has a method called reverse(). The reverse method must be defined in any class using the A interface.

public interface A{ public void reverse();}

IBM Software Group | Tivoli software

49

Interfaces

• Java does not support multiple inheritance

• Java uses interfaces to allow inheriting multiple functionality

• Interfaces are similar to abstract classes, except all methods are abstract and all properties are static final

• All methods belonging to an interface must be defined in any class that implements the interface

Page 273: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Multiple Inheritance with Interfaces

When you create a class that uses an interface, you reference the interface with the reserved word implements. You can reference more than one interface because multiple interfaces are allowed.

Any class that implements an interface must include code for all methods in the interface.

public class C extends B implements A{ public C(String nm) { super(nm); // constructs the super (parent) class } public void reverse() // this method specific to C { System.out.println("Code reverse"); }}

Interfaces can be inherited by using the extends keyword. Multiple inheritance can be implemented using interfaces.

IBM Software Group | Tivoli software

50

Multiple Inheritance with Interfacespublic class C extends B implements A{

public C(String nm) {super(nm); // builds parent

}public void reverse() { // this method specific to C

System.out.println("Code reverse");} }

interface superBankable {}

interface Bankable extends superBankable{}

public class Banking extends Account implements Bankable { …..}

Page 274: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

• A class can extend a superclass, in addition to implementing an interface:

public class Banking extends Account implements Bankable {

}

• An interface can extend a super interface:

interface superBankable {}

interface Bankable extends superBankable{}

Page 275: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Casting within the Class Hierarchy

By casting an instance to its subclass, you can refer to any property or method. Before performing the typecast, make certain that the cast is valid by using the instanceof operator. The following example uses the A class:

if (ref[x] instanceof A) // ok right type of object{ A aaaa = (A) ref[x]; // cast current instance to subclass aaa.someMethod();}

Casts from a superclass (downcasting) to a subclass must be done explicitly. Casts from a subclass can be done implicitly, but explicit casts are recommended.

IBM Software Group | Tivoli software

51

Casting within the Class Hierarchy

• By casting an instance to a subclass, any property or method can be referenced

if (ref [x] instanceof A) // verify if right type of object{

A aaa = (A) ref [x]; // cast current instance to subclassaaa.someMethod();

}

• Casting from a superclass must be explicit

• Casting from subclasses can be done implicitly

Page 276: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Casting Primitives

It is sometimes necessary to convert a data type to another type. Type conversion can be automatic or explicit. For example, an integer can be converted to a float for a mathematical computation.

int i = 3;double d = i;

This process will not work the other way around. A double cannot be automatically converted to an int because the double requires more storage than the int and information might be lost. To force a conversion, type cast the double to an int.

When casting, the data type that a variable is being cast to is enclosed in parentheses in front of the variable.

double d = 3.3;int i = (int) d;

The double d is temporarily changed to an int when the assignment operation is processed. The cast is only for the duration of the assignment.

Java casts have the form (T) N where T is the type and N is a variable.

IBM Software Group | Tivoli software

52

Casting Primitives

• Sometimes necessary to convert to another primitive data type

int i = 3;double d = i;

• Will not work the other way around with an explicit castdouble d = 3.3;int i = (int) d;

• Syntax is (Type)variable

Page 277: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Automatic Class Conversion

Casting to another data type can be handled with automatic or explicit conversions. Sometimes the type conversion is automatically handled by the compiler. Consider a superclass Passport with a subclass USAPassport:

class Passport { ... }

class USAPassport extends Passport { ... }

If p is of type Passport and usa is of type USAPassport, then you can assign the USAPassport reference to the Passport variable.

class Conversion { Passport p; USAPassport usa;

public void convert () { usa= new USAPassport (); p = usa; } }

The compiler automatically handles the assignment because the types are compatible. They are compatible because the type Passport can be of type USAPassport (a USAPassport is a Passport).

IBM Software Group | Tivoli software

53

Automatic Class Conversionclass Passport { ... }

class USAPassport extends Passport { ... }

Class Conversion { Passport p; USAPassport usa;

public void convert () { usa= new USAPassport (); p = usa;

} }

Page 278: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Automatic Interface Conversion

A related automatic conversion occurs with interfaces. Let the class Violin implement the Instrument interface.

interface Instrument { ... } class Violin implements Instrument { ... }

A variable of type Violin can be automatically converted to a variable of type Instrument because a Violin is an Instrument.

Violin v; Instrument i;

public void convert () { i = v; // automatic conversion from class to interface v = i; // illegal conversion from interface to class }

IBM Software Group | Tivoli software

54

Automatic Interface Conversion

interface Instrument { ... }

class Violin implements Instrument { ... }

Violin v;

Instrument i;

public void convert () {

i = v; // automatic conversion from class to interface

v = i; // illegal conversion from interface to class

}

Page 279: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Explicit Casts

An explicit cast is required where automatic conversion does not apply. For example, let the class B be a subclass of A.

class A { void methodA () { ... }}

class B extends A { void methodB () { ... } }

Another class contains someMethod(A obj) in which both a superclass A and subclass B object is passed as an argument. The method will invoke methodA() regardless of the type of object. If it is a B object, it is possible to downcast and invoke methodB(). Use the instanceof operator to determine the type.

public void someMethod (A obj) { if (obj instanceof B) ((B)obj).methodB (); else obj.methodA ();}

To invoke the methodB(), the cast (B)obj tells the compiler to treat the object obj as a B object.

IBM Software Group | Tivoli software

55

Explicit Casts

class A {void methodA () { ... }

}

class B extends A { void methodB () { ... }

}

public void someMethod (A obj) {if (obj instanceof B)

((B)obj).methodB (); else

obj.methodA ();}

Page 280: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

A superclass reference can be converted into a subclass reference, but this is usually not useful to call the class methods. This conversion is called downcasting.

It is possible to convert the subclass reference to the superclass without an explicit cast because the compiler will automatically convert the data type. This conversion is called upcasting.

Casts permitted at compile time include casting any object to its own class or to one of its subclasses or superclasses or interfaces. The compiler cannot catch every invalid cast attempt. More stringent rules apply at run time. If the object being cast is not compatible with the new type that is being cast, a ClassCastException is thrown at run time.

Page 281: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Upcasting and Downcasting

C c = new C();E e = new E();

Base bc = new C();Base b = new Base();b = c; // upcasting is always safec = (C)bc; // explicit downcasting

bc.f(); // calls f() in object Cbc.g(); // calls g() in object Baseb.f(); // calls f() in object Cb.g(); // calls g() in object Basec.f(); // calls f() in object Cc.g(); // calls g() in object Base

b = e;b.g(); // calls g() in object Eb.h(); // error h() is not defined in Base class

IBM Software Group | Tivoli software

56

Upcasting and Downcasting

Given an instance c of type C and an instance e of type E

Page 282: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Polymorphism

Overloaded methods are methods with the same name but either a different number of parameters or different types in the parameter list.

Overridden methods are methods that are redefined within a subclass and have the same signature.

Polymorphism, the third basic principle of object-oriented programming, is a method’s ability to do different things based on the object upon which it is acting. Overriding supports polymorphism, as does dynamic binding.

IBM Software Group | Tivoli software

57

Polymorphism

• Overloaded methods have the same name but the signature is different

• Overridden methods are methods that have been redefined within a subclass

• Overridden methods have the same signature

• The ability of resolve to the correct method at run time, based on the object, supports the concept of polymorphism

Page 283: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Dynamic Binding

Assume that three subclasses (Cat, Dog, and Mouse) have been created that extend the Animal abstract class. Each subclass has its own speak( ) method.

public class SpeakingAnimal{ public static void main(String args[])

Animal a // set up var for an Animal Cat c = new Cat("Meow"); // makes specific objects Dog d = new Dog("Bark"); Mouse m = new Mouse("Squeak");

// now reference each as an Animal a = c; a.speak(); a = d; a.speak(); a = m; a.speak();}

Although each method reference was to an Animal (and no Animal object exists), the method related to the subclass object is called at run time. This process is called dynamic (or late) binding.

IBM Software Group | Tivoli software

58

Dynamic Bindingpublic class SpeakingAnimal{

public static void main(String args[])Animal a Cat c = new Cat("Meow"); // makes specific objectsDog d = new Dog("Bark");Mouse m = new Mouse("Squeak");

// now reference each as an Animala = c; a.speak();a = d; a.speak();a = m; a.speak();

}

Page 284: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Student Exercise

Open your Student Exercises book and perform the exercises for this unit.

IBM Software Group | Tivoli software

59

Student Exercise

Page 285: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Review Questions

1. What is passing by reference?

2. What is passing by value?

3. What is an abstract class?

4. What is the meaning of public, private, protected, and default modifiers?

5. What is the meaning of the reserve word final?

6. True or false: An abstract class can have only private class members.

7. What is the base class from which all exceptions are subclasses?

8. How do you use a try block?

9. How do you use a catch block?

10. When do you use a finally block?

11. When is an exception considered handled?

Page 286: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Review Answers

1. What is passing by reference?

Passing by reference mean passing the memory location of an object (address) rather than passing the value of the object.

2. What is passing by value?

Passing by value means passing a copy of the value.

3. What is an abstract class?

An abstract class serves as a template and must be extended. Any class with an abstract method is automatically abstract. A class can be declared abstract to prevent it from being instantiated, even if it has no abstract methods

4. What is the meaning of public, private, protected, and default modifiers?

A public class and its methods are visible to other packages. A public variable is visible everywhere if the class is also public.A private variable or method can be used only by an instance of the same class that contains the variable or method. A protected variable or method is available to all classes in the same package and all subclasses of the class that contains the protected feature.By default, it is visible to all within the specific package.

5. What is the meaning of the reserve word final?

A final class cannot be extended, therefore a final class cannot be subclassed. A final method cannot be overridden when its class is inherited. You cannot change the value of a final variable (it is a constant).

6. True or false: An abstract class can have only private class members.

False

7. What is the base class from which all exceptions are subclasses?

All exceptions are subclasses of a class called java.lang.Throwable.

8. How do you use a try block?

You put the processing code in the try block.

9. How do you use a catch block?

You put the code to handle exceptions that might arise in a try block in its corresponding catch block.

Page 287: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

10. When do you use a finally block?

When there is code that must be executed no matter what happens within a try block, it must be put into a finally block.

11. When is an exception considered handled?

When an exception is thrown in a try block and is caught by a matching catch block, the exception has been handled.

Page 288: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 6: Java Exceptions, I/O, and InheritanceInheritance

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

Summary

IBM Software Group | Tivoli software

60

Summary

You should now be able to:

Describe how Java handles access control for data and methods

Overload and override Java methods

Describe the basics of Java I/O classes

Implement exception handling

Page 289: Ibm enterprise it and asset management 7.1 java for customization training

• • • ••

7-1

Unit 7: Design Patterns, Interfaces, and the Collections Framework

© 2009 IBM Corporation

Unit 7: Design Patterns, Interfaces, and the Collections Framework

Page 290: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections Framework

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

Introduction

This unit covers design patterns, interfaces, and the Java Collections Framework.

Objectives

IBM Software Group | Tivoli software

2

Objectives

Upon completion of this unit, you will be able to:Describe the benefits of design patterns

Use interfaces and abstract classes to implement inheritance

Describe the Java Collections Framework

Implement inheritance using abstract classes

Implement polymorphism using interfaces

Page 291: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkDesign Patterns

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

Lesson 1: Design Patterns

A pattern is a generic solution to a problem. Design patterns came to the forefront in 1994. They are a highly effective solution to problems that can be modeled with objects.

IBM Software Group | Tivoli software

3

Design Patterns

• Seen in elegant and effective software design

• Embraced by software industry during the movement to objects

• Represent best solutions to object design problems

Page 292: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkDesign Patterns

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

Terminology

A design pattern is a generic solution to a common software design problem. A design pattern is not code or an algorithm. Algorithms do not solve design problems or help with architecting large-scale applications. Instead, algorithms solve computational problems. A design pattern is a template for a generic solution applicable to many different situations.

Design patterns and idioms describe solutions to common design problems. With a design pattern, both the problem and solution are generic and can be independent of the language that will be used for implementation. The scope of an idiom is more low-level and it is specific to a programming language.

IBM Software Group | Tivoli software

4

Terminology

• Generic solution to a common software industry design problem

• A design pattern is not an algorithm; it is a template

• Twenty-three design patterns presented by GOF

• Design patterns are prevalent in the Java API and can be found in well-designed enterprise applications

Page 293: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkDesign Patterns

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

Many design patterns show up in the Java API. Some of the most well-known patterns are:

• Abstract Factory

• Builder

• Factory

• Singleton

• Adapter

• Composite

• Proxy

• Command

• Iterator

• Mediator

• Observer

• State

Page 294: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkDesign Patterns

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

Singleton Design Pattern

The Singleton design pattern is one of the simplest design patterns. It ensures that a class has only one instance and provides a global point of access to that one instance. Its name is derived from the singleton set, defined to be a set that contains one element.

Singletons are usually accessed by other objects throughout a software system, and therefore require global access.

IBM Software Group | Tivoli software

5

Singleton Design Pattern

• One of the more simple creational patterns

• The class has only one instance

• The single instance has a global point of reference

• Real-world example is the CEO of IBM

• Software example is an instance of a server

Page 295: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkDesign Patterns

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

Using the Singleton

The Singleton class maintains a static reference to the one and only singleton instance and returns that reference using the static getOnly() method.

The following implementation is a classic singleton:

public class Singleton { private static Singleton only = null; protected Singleton() { // Exists only to negate instantiation. } public static Singleton getOnly() { if(only == null) { only = new Singleton(); } return only; }}

IBM Software Group | Tivoli software

6

Using the Singleton

• One instance is created the first time the Singleton.getOnly() method is called

• Constructor is private

Page 296: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkDesign Patterns

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

Proxy Design Pattern

The proxy design pattern provides a surrogate to provide access to an object.

An example of a proxy is a lawyer who can represent a client in a court of law. In the software industry, a protection proxy controls access to the original object. A remote proxy provides a local representation of a remote object, as you will see in Unit 9.

IBM Software Group | Tivoli software

7

Proxy Design Pattern• Provides a surrogate of

the original object

• Proxy contains a reference to the RealSubject

• Interface for Proxy and the Real Subject are the same

Page 297: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkDesign Patterns

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

Adapter Design Pattern

The adapter pattern is sometimes called the wrapper pattern. It converts the interface of a class or data type into another that the client expects, allowing otherwise incompatible types to work together.

Any analog-to-digital converter is a type of adapter. You would use an adapter to allow a digital signal to be converted and viewed on an older, analog monitor.

The Java primitive data types all have corresponding adapter classes so that the primitive data type can behave like an object.

IBM Software Group | Tivoli software

8

Adapter Design Pattern• Converts an interface to another

that can be used by the client

Page 298: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkDesign Patterns

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

Immutable Objects

Immutable objects are objects whose data cannot change after object construction.

To make a class immutable:

• Ensure that the class cannot be overridden by making it final, keeping constructors private, or making the fields private.

• Do not provide any methods that can change the state of the object in any way.

IBM Software Group | Tivoli software

9

Immutable Objects• Objects whose data

cannot be modified

• Private data members

• No public methods that can change the state

Page 299: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkDesign Patterns

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

Iterator Design Pattern

A collection (or container) object such as a list should provide sequential access to its elements without exposing its underlying representation. You might also want to traverse the list in various ways, depending on what must be accomplished. Rather than expanding the List interface with operations for multiple traversals, it is better to have a uniform interface for traversing different types of collection objects.

The iterator pattern defines this type of polymorphic iteration by removing the responsibility for access and traversal from the collection object. An Iterator object defines a standard access and traversal protocol.

IBM Software Group | Tivoli software

10

Iterator Design Pattern

• Provides sequential access to the elements of a collection

• Does not expose the underlying representation

• Defines the standard access and traversal protocol

• Use in the same manner for any container

Page 300: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkDesign Patterns

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

Generic Programming

With generic programming, algorithms are not written for a specific object type. Instead, the object type is provided dynamically, as a parameter.

The iterator pattern defines this type of polymorphic iteration by removing the responsibility for access and traversal from the collection object. An Iterator object defines a standard access and traversal protocol.

The iterator abstraction is key to a subset of generic programming. This technology explicitly separates the algorithm from the data structure. For example, assume there are three algorithms (sort, find, and copy) and five data structures (array, binary tree, linked list, queue, and hash table). One approach would require developing three times five permutations. A generic programming approach would require three plus five implementations.

IBM Software Group | Tivoli software

11

Generic Programming

• Generic programming, or simply generics

• Uses parameterized types

• Iterator abstraction is key to a collection-related subset of generics

• Explicitly abstracts the algorithm from the data

Page 301: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkInterfaces

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

Lesson 2: Interfaces

Using interfaces and abstract classes implements inheritance and polymorphism.

Interfaces provide the types and supertypes for a client to view a different set of objects as though they were the same.

IBM Software Group | Tivoli software

12

Interfaces

• Inheritance and polymorphism are supported by interfaces and abstract classes

• Provide a way for a client to view a set of different objects asthough they were the same type

Page 302: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkInterfaces

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

An Interface

In Java, an interface is similar to an abstract class, but there is no code associated with an interface. It is a list of methods that must be defined by classes that implement that interface. An interface can also define constants (as public static final).

The following example shows an interface definition:

public interface TestInterface { public void action1(ActionEvent e); public int action2(ActionObject ao); public void action3(ActionEvent e);}

IBM Software Group | Tivoli software

13

An Interface

• An interface does not contain any code to implement its methods

• An interface can define constants (static final)

public interface AnyInterface {

public void action1(ActionEvent e);

public int action2(ActionObject ao);

public void action3(ActionEvent e);}

Page 303: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkInterfaces

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

Implementing an Interface

When a class specifies that it implements an interface, it must define all of the methods in that interface.

The syntax is:

public class A implements B {}

Just as you can extend a class to create a new class, you can extend an interface to create a new interface. Although you cannot extend more than one class, you can extend several interfaces. A class can implement any number of interfaces. The class that implements an interface must provide bodies for all methods of that interface.

Instance methods are implicitly public and abstract, but the interfaces themselves do not have to be public. Many interfaces in the standard libraries are not public and are for internal use only.

IBM Software Group | Tivoli software

14

Implementing an Interface

• The implementing class must define all of the methods

• The syntax is:public class A implements B {

}

• An interface can extend another interface

• A class can implement any number of interfaces

Page 304: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkInterfaces

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

Abstract Classes versus Interfaces

A class can implement several interfaces, but it can extend only one abstract class.

An interface cannot provide any code. An abstract class can provide complete code, default code, stubs to override, or a combination of any of these.

You can put shared code into an abstract class, but not into an interface.

Interfaces are most often used to describe the abilities of a class. An abstract class defines the core identity of its subclasses.

If you defined a DriversLicense abstract class, then the TexasLicense subclass would be a DriversLicense. An abstract base class characterizes what a class is. When implemented by a class, interfaces characterize the things the class can do: the abilities of the class.

Be aware that if a new method is added to an interface, you must provide every class that implements that interface with a concrete implementation of that method. When adding a new method to an abstract class, you can provide a default implementation; existing code will then continue to work without requiring modification.

IBM Software Group | Tivoli software

15

Abstract Classes versus Interfaces

• A class can extend only one class but can implement many interfaces

• An interface does not include code

• An abstract class can provide a complete implementation, default code, only a stub, or any combination of these options

• Interfaces characterize what an object does

• Abstract classes characterize what an object is

Page 305: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkInterfaces

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

Implementing Interfaces

Sometimes you want a method or many methods to be common among several branches of classes, rather than only within one branch. Using an interface can stretch the ability of polymorphism over many branches of related classes.

IBM Software Group | Tivoli software

16

Implementing Interfaces

• Use interfaces when a method or many methods are meant to be common among several branches of classes

• In this diagram, four abstract classes implement the same interface

Page 306: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkInterfaces

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

Interfaces and Polymorphism

An interface can be implemented across many related classes, and can support polymorphism throughout the design hierarchy.

IBM Software Group | Tivoli software

17

Interfaces and Polymorphism

Page 307: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkInterfaces

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

Extending Interfaces

Interfaces can be implemented by classes and extended by another interface. Inheritance is supported through a hierarchy of interface types and their supertypes with the extends keyword.

public interface Instrument { public void play();}

public interface Tuneable { public void tune();}

public interface Strikeable extends Instrument, Tuneable { public void strike();

IBM Software Group | Tivoli software

18

Extending Interfacespublic interface Instrument {

public void play();}

public interface Tuneable {public void tune();

}

public interface Strikeable extends Instrument, Tuneable {public void strike();

}

public class Piano implements Strikeable {public void strike() { }public void play() { }public void tune() { } }

Page 308: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkInterfaces

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

Extending Multiple Interfaces

public interface Instrument { public void play();}

public interface Tuneable { public void tune();}

public interface Strikeable extends Instrument, Tuneable { public void strike();}

public class Piano implements Strikeable {public void strike() {}public void play() { }public void tune() { }

}

public interface Portable { public void transport();}

IBM Software Group | Tivoli software

19

Extending Multiple Interfaces

public interface Portable {

public void transport();

}

public class Drums implements Strikeable, Portable {

public void strike() { }

public void play() { }

public void tune() { }

public void transport() { }

}

Page 309: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkInterfaces

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

public class Drums implements Strikeable, Portable { public void strike() {} public void play() { } public void tune() { } public void transport() { }}

Notice that both the class Drums and the interface Strikeable respectively extend and implement multiple interfaces.

Page 310: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkInterfaces

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

Nested and Inner Classes

A class can contain another class within itself. A class defined inside another class can either be a nested class or an inner class.

Nested classes are declared to be static and have access to static variables. The inner class does not have the static restriction.

public class OutClass { private final String name = "Sam"; private String company = "IBM";

class InnerClass { public void someMethod() { System.out.println(company); System.out.println(name); } }

public static void main(String[] args) { OutClass oc = new OutClass(); OutClass.InnerClass ic = oc.new InnerClass(); ic.someMethod(); } }

IBM Software Group | Tivoli software

20

Nested and Inner Classes

public class OuterClass {

private static final String name = "Sam";private static String company = "IBM";

public static class NestedClass {public void someMethod() {

System.out.println(company); // must be staticSystem.out.println(name);

} }

public static void main(String[] args) {NestedClass ic = new NestedClass();ic.someMethod();

} }

Page 311: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Lesson 3: The Collections Framework

With the Java Collections Framework you can represent and manipulate a group of objects.

The Collections Framework is based on nine interfaces, their respective implementations, and the algorithms that manipulate them.

IBM Software Group | Tivoli software

21

The Collections Framework

• Use the Collections Framework to represent and manipulate collections

• Sets, Lists, Map, and so on

• Based on nine interfaces

Page 312: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Java Collections Framework

Generic programming refers to creating code that can be applied to many types of data. The Java Collections Framework supports generic programing. It applies a uniform philosophy that adds operational functionality to object classes. Unification is accomplished through interfaces that each collection object inherits. Various types of objects can be handled in a similar manner within Collections Framework classes.

Additional functionality such as searches, sorts, insertions, and deletions use efficient algorithms.

IBM Software Group | Tivoli software

22

Java Collections Framework

• Supports generic programming

• Collection objects implement interfaces that support generics

• Collections include search, sort, add, and delete functionality

Page 313: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Basic Interfaces

The Collections Framework is made up of a set of interfaces. The four basic interfaces of the framework are:

• Collection: An interface that represents a group of objects, with duplicates allowed.

• List: An interface that extends Collection, allows duplicates, and introduces positional indexing.

• Set: An interface that extends Collection but does not allow duplicates.

• Map: An independent interface that does not extend Collection.

IBM Software Group | Tivoli software

23

Basic Interfaces

Page 314: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Lists

Arrays and lists are fundamental data structures used in programming. They store data within a structure that allows efficient traversal, searches, additions, and deletions during program execution.

IBM Software Group | Tivoli software

24

Lists

• ArrayList is an expandable array

• LinkedList is a chain of nodes; each node is an object

Page 315: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Linked List

A linked list consists of a number of links, each of which has a reference to the next link. The LinkedList class is implemented as a double linked list whereby a link contains a reference to the next and the previous link.

Traversing the list sequentially, and adding and removing elements in the middle of a linked list, is efficient.

IBM Software Group | Tivoli software

25

Linked List

• A linked list is a number of links that reference the next link

• A double linked list references the next and previous links

Page 316: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Sets

Like the mathematical definition, a set is an unordered collection of elements.

A set allows no duplicate elements.

IBM Software Group | Tivoli software

26

Sets

• Collections that allow only one object with a specific value

• An unordered collection of elements

• Mirror the concept of a mathematical set

Page 317: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Maps

A map allows you to store pairs of elements. The pairs are called keys and values, and each key maps to one value.

Duplicate keys are not allowed.

HashMap, HashTable, TreeMap, and SortedMap all implement the Map interface.

The HashMap class is similar to the HashTable class, except that it is unsynchronized and permits nulls for key and value values. The HashTable class does not allow null and is synchronized. There is no guarantee that the order of the map will remain constant over time with a HashMap.

IBM Software Group | Tivoli software

27

Maps

• Maps store key-value pairs

• The Map interface is implemented by HashMap, HashTable, SortedMap, and TreeMap

Page 318: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Collection Interfaces

• The collection interfaces are Collection, List, Set, and SortedSet.

– Collection is at the top of the hierarchy.

– List extends Collection for classes that are a sequence of elements. It overrides appropriate methods and adds get(idx), indexOf(), lastIndexOf(), set(idx), and subList(i1,i2).

– Set extends Collection by overriding the add() method to prevent duplicate objects.

– SortedSet extends Set to keep all of the contained objects ordered. It includes the methods comparator(), first(), headSet(obj), last(), subSet(o1,o2), and tailSet(obj).

• The mapping interfaces are Map and SortedMap.

– Map defines a table that is a one-to-one relationship between a key and an element. No duplicate keys are allowed.

– SortedMap maintains an ordered mapping.

IBM Software Group | Tivoli software

28

Collection Interfaces

Page 319: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Interface Implementations

Concrete collection classes implement the interfaces. They include ArrayList, HashSet, LinkedList, TreeSet, HashMap, and TreeMap.

• ArrayList implements List and is a dynamic array, meaning that its size does not have to be declared at compile time.

• HashSet implements the Set interface and uses a hash table for efficient storage.

• LinkedList implements List. It can be traversed and nodes can be inserted and deleted.

• TreeSet implements a sorted set using a binary tree for storage, which allows fast access to its elements.

• HashMap and TreeMap are concrete mapping classes. TreeMap orders the mapping key; HashMap does not.

Interface Implementation From original 1.0 release

List ArrayList, LinkedList Vector, Stack

Set HashSet, TreeSet

Map HashMap, TreeMap Hashtable, Properties

IBM Software Group | Tivoli software

29

Interface Implementations

Page 320: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Navigating a Collection

An iterator is used to navigate a collection.

The supporting interfaces include Iterator, ListIterator, and Comparator. Their methods can be overridden.

• Iterator and ListIterator specify the objects within a list. Iterator contains the methods next(), hasNext(), and remove(). ListIterator has the additional methods hasPrevious(), previous(), and set().

• Comparator defines how two objects are compared with compare(obj1,obj2) and equals(obj).

IBM Software Group | Tivoli software

30

Navigating a Collection

• An iterator is used to navigate a collection

• Supporting interfaces:

Iterator: next(), hasNext(), and remove()

ListIterator: Same as previous, plus hasPrevious(), previous(),and set()

Comparator: compare(obj1, obj2) and equals(obj)

Page 321: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Original Enumeration Interface

The Enumeration interface allows you to iterate through a collection. This interface has been superseded by the Iterator interface. However, not all libraries support the newer interface, so you might have to use the Enumeration interface.

Iterating through an Enumeration is similar to iterating through an Iterator. However, there is no removal support with Enumeration.

Enumeration enum = ...;while (enum.hasNextElement()) { Object element = iterator.nextElement();// process the element}

IBM Software Group | Tivoli software

31

Original Enumeration Interface

• Iterate through a collection

• Superseded by Iterator interface

Page 322: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Student Exercise

Open your Student Exercises book and perform the exercises for this unit.

IBM Software Group | Tivoli software

32

Student Exercise

Page 323: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Review Questions

1. What is the difference between an interface and an abstract class?

2. True or false: An interface has all public members and no implementation.

3. What is HashMap and Map?

4. What is the difference between HashMap and HashTable?

Page 324: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Review Answers

1. What is the difference between an interface and an abstract class?

An abstract class can have methods that implement a default behavior. An interface can declare constants and methods, but cannot implement default behavior. All methods in an interface are implicitly abstract.

2. True or false: An interface has all public members and no implementation.

True.

3. What is HashMap and Map?

Map is an interface and HashMap is a class that implements the Map interface.

4. What is the difference between HashMap and HashTable?

The HashMap class is similar to HashTable, except that it is unsynchronized and permits nulls for key and value values. HashTable does not allow null and is synchronized.

Page 325: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Summary

IBM Software Group | Tivoli software

33

Summary

You should now be able to:Describe the benefits of design patterns

Use interfaces and abstract classes to implement inheritance

Describe the Java Collections Framework

Implement inheritance using abstract classes

Implement polymorphism using interfaces

Page 326: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 7: Design Patterns, Interfaces, and the Collections FrameworkThe Collections Framework

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

Page 327: Ibm enterprise it and asset management 7.1 java for customization training

• • • ••

8-1

Unit 8: Strings, Arrays, and Collection Classes

© 2009 IBM Corporation

Unit 8: Strings, Arrays, and Collection Classes

Page 328: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection Classes

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

Introduction

This unit examines in more detail some of the Java Collection classes introduced in Unit 7.

Objectives

IBM Software Group | Tivoli software

2

Objectives

Upon completion of this unit, you will be able to:Use the StringBuffer and StringBuilder classes

Use the LinkedList and ArrayList classes

Use the Iterator and ListIterator classes

Page 329: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesStringBuffer and StringBuilder

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

Lesson 1: StringBuffer and StringBuilder

The basic class for a string is the String class. Objects of this type cannot be modified. The StringBuilder and StringBuffer classes are better choices for manipulating strings because their instances can be changed, unlike the immutable String class.

IBM Software Group | Tivoli software

3

StringBuffer and StringBuilder

• String objects are immutable

• Use the StringBuffer class to build and modify a string

• StringBuilder is similar to StringBuffer

• StringBuilder is new to Java 5

Page 330: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesStringBuffer and StringBuilder

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

StringBuilder Class

The StringBuffer and StringBuilder (Java 5) are very similar. The StringBuilder class is unsynchronized, designed for use by a single thread, and faster. These classes will expand in size as necessary. Many methods return the same StringBuilder or StringBuffer, so method chaining is possible.

Constructors

Length

Comparison

sb = new StringBuilder() Builds an empty StringBuilder

sb = new StringBuilder(n) Builds a StringBuilder with an initial size of n

sb = new StringBuilder(s) Builds a StringBuilder initialized to the String value s

len = sb.length() Returns length of the current contents of sb

bool = sb1.equals(sb2) Returns true if sb1 and sb2 contain equal values

IBM Software Group | Tivoli software

4

StringBuilder Class

• Constructorssb = new StringBuilder()

sb = new StringBuilder(n)

sb = new StringBuilder(s)

• Common methodsi = sb.length()

b = sb.equals(sb2)s = sb.toString()

Page 331: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesStringBuffer and StringBuilder

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

Conversion

s = sb.toString() Return a String using the contents of sb

Page 332: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesStringBuffer and StringBuilder

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

StringBuilder Methods and Exceptions

Many methods return the same StringBuilder or StringBuffer, so method chaining is possible.

Returns part of StringBuilder object.

sb = sb.append(y) Appends y (String, char, int, and so on) to end of sb

sb = sb.insert(i, y) Inserts y (String, char, int, and so on) at position i

sb = sb.setCharAt(i, c) Replaces char at index with c

sb = sb.deleteCharAt(i) Deletes char at index i

sb = sb.delete(start, end) Deletes chars at index start thru end

sb = sb.reverse() Reverses the contents of sb

sb = sb.replace(start, end, s) Replaces characters at start through end with String s

c = sb.charAt(i) char at position i

s = sb.substring(i) Substring from index i to the end of sb

s = sb.substring(i, j) Substring from index i to index j of sb, not including j

IBM Software Group | Tivoli software

5

StringBuilder Methods and Exceptions

• sb = sb.append(y)

• sb = sb.insert(offset, y)

• sb = sb.setCharAt(index, c)

• sb = sb.deleteCharAt(i)

• sb = sb.delete(start, end)

• sb = sb.reverse()

• sb = sb.replace(start, end, s)

• c = sb.charAt(i) • s = sb.substring(i) • s = sb.substring(i, j)

• i = sb.indexOf(s) • i = sb.indexOf(s, i) • i = sb.lastIndexOf(s) • i = sb.lastIndexOf(s, i)

Page 333: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesStringBuffer and StringBuilder

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

Searching by index methods returns the index or -1 if the string or character is not found.

i = sb.indexOf(s) index of the first occurrence of substring s in sb

i = sb.indexOf(s, i) index of substring s at or after position i in sb

i = sb.lastIndexOf(s) index of last occurrence of s in sb

i = sb.lastIndexOf(s, i) index of last occurrence of s on or before i in sb

Page 334: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesStringBuffer and StringBuilder

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

StringBuilder Example

Use StringBuilder or StringBuffer to build strings from parts. Their append() method performs default conversions to strings and appends them to the current value.

StringBuilder sb = new StringBuilder();int i = 12;sb.append("int i = ");sb.append(i); sb.append(", and 2.0/7.0 = ");sb.append(2.0/7.0);String s = sb.toString(); System.out.println(s);

// outputs "int i = 12, and 2.0/7.0 = 0.2857142857142857"

IBM Software Group | Tivoli software

6

StringBuilder Example

StringBuilder sb = new StringBuilder();

int i = 12;

sb.append("int i = ");

sb.append(i);

sb.append(", and 2.0/7.0 = ");

sb.append(2.0/7.0);

String s = sb.toString();

System.out.println(s);

// outputs "int i = 12, and 2.0/7.0 = 0.2857142857142857"

Page 335: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesStringBuffer and StringBuilder

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

Immutable Strings

After it is created, a string cannot be changed. The immutability refers to where the String reference points.

public class ImmutableString{ public static void main(String[] args) { String s1 = "Hello"; String s2 = "World"; s1=s2; }}

If you were to print out s1 from this example, the output would be World. When s2 is assigned to s1, the String s1, which referred to the memory containing Hello, is no longer referenced.

Strings s1and s2 now point to the same string. The Hello string has not been modified, but there is no longer a reference pointing to it.

StringBuilder sb = new StringBuilder("Initial String");

String s = sb.toString(); // s is Initial String

s = s + " and append this"; // s is Initial String and append this

IBM Software Group | Tivoli software

7

Immutable Strings

• Strings are immutable

• The reference is mutable

public class ImmutableString{public static void main(String[] args) {

String s1 = "Hello";

String s2 = "World";

s1=s2;

}}

Page 336: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesStringBuffer and StringBuilder

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

s = "Why does this work? "; // s is Why does this work?

String ss = s.concat("Concat this"); // ss is Why does this work? Concat this

s = s.concat(ss); // s is Why does this work? Why does this work? Concat this

Concatenating a string instantiates a new string in the background. After a String object is created, it cannot be changed even if the reference changes and points to another String object. The StringBuffer and StringBuilder classes contain the methods for resizing and changing the contents of your string.

Page 337: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrays

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

Lesson 2: Arrays

An array of characters is similar to a string. Arrays can store primitives or object types and are the best choice when working with a fixed number of elements. An ArrayList from the Collections library of classes is a better choice when the number of elements might vary.

IBM Software Group | Tivoli software

8

Arrays

• Best for working with a fixed number of elements

• Use ArrayList for a variable number of elements

Page 338: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrays

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

Using Arrays

Declaring an array allocates enough space for a reference to the array without creating the array object.

String[] args; // An array of Stringsint[] intList; // An array of intsMyObject[] objList; // objList is an array of MyObject

Create the array object with new:

int[] intArray; // Declare an array of intsintArray = new int[100]; // Allocate memory for 10 ints

Or, combine the declaration and allocation in one line:

int[] intArray = new int[100];

When the array is allocated, the elements are initialized to a default value. The value is 0 if the array type is int, false for boolean, and null for object types.

If you declare and initialize an array in the same statement, do not specify the array size, because Java determines the size from the number of values listed.

int[] intArray = {1, 3, 5, 7, 11};

IBM Software Group | Tivoli software

9

Using Arrays

• Declaring an arrayString[ ] args; // An array of Strings

int[ ] intList; // An array of ints

MyObject[ ] objList; // objList is an array of MyObject

• Allocating an arrayintList = new int[100];objList = new MyObject[5];

• Declaring and allocating an arrayint[] intList = new int[100];

Page 339: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrays

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

Length of an Array

Every array has its length stored in a final instance variable that can be accessed with the array name followed by .length. This variable is commonly used to iterate over the array using a for loop.

int[] intArray = new int[100]; // intArray[0]...intArray[99]

for (int i = 0; i < intArray.length(); i++) { // Assign random value 0-999 to array element intArray[i] = (int)(Math.random() * 1000); }

// Add array elementsint sum = 0;for (int i = 0; i < intArray.length; i++) { sum += intArray[i];}

IBM Software Group | Tivoli software

10

Length of an Array

• Length of array is stored in final (constant) instance variable

• .length is commonly used in for loopint[] intArray = new int[100]; // intArray[0]...intArray[99]

for (int i = 0; i < intArray.length(); i++) {// Assign random value 0-999 to array elementintArray[i] = (int)(Math.random() * 1000);

}

int sum = 0;for (int i = 0; i < intArray.length; i++) {

sum += intArray[i]; // Add array elements}

Page 340: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrays

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

foreach Loop

The foreach loop cannot be used to set values, but it can be used to get the value of each of the array elements. The following code sample compares it to the traditional for loop:

int sum = 0;for (int i = 0; i < intArray.length; i++) { sum += intAray[i];}

// or use the enhanced for

int sum = 0;for (int v : intArray) { sum += v;}

IBM Software Group | Tivoli software

11

foreach Loop

• Is used to get values

• Cannot be used to set valuesint sum = 0;for (int i = 0; i < intArray.length; i++) {

sum += intArray[i];}

// or use the foreach loopint sum = 0;for (int v : intArray) {

sum += v;}

Page 341: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrays

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

Array Methods

Static methods for manipulating arrays are available in the java.util.Arrays and java.System classes.

IBM Software Group | Tivoli software

12

Array Methods

• Static methods are available for adding and removing array elements

• Complete list of methods is available in Javadocs

Page 342: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrays

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

ArrayList Methods

The Arrays class has some useful methods for working with arrays, but there are more options if the array looks like a List. The Collections class has many useful static methods, such as sort, shuffle, reverse, max, and so on.

import java.util.*;. . .List<String> listabc = Arrays.asList(abc); // The Collections methods can now be used with listabc.Collections.shuffle(listabc);System.out.println(listabc);

The list is not a regular ArrayList, because it is based on the original array. You cannot add elements to the list because doing so would cause reallocation of a larger underlying array.

Creating this list does not prevent you from using the underlying array.

The java.util.Arrays.asList(...) method cannot be used with an array of primitive types. It only works for arrays of object types.

IBM Software Group | Tivoli software

13

ArrayList Methods

import java.util.*;

. . .

List<String> listabc = Arrays.asList(abc);

// The Collections methods can now be used with listabc.

Collections.shuffle(labc);

System.out.println(labc);

Page 343: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesCollections Classes

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

Lesson 3: Collections Classes

The term Collections has multiple meanings.

Java data structures and corresponding facilities are known as Collections. In addition to being the term for describing the data structure facilities, java.util.Collection is an interface and java.util.Collections is a class containing data structure utility methods.

IBM Software Group | Tivoli software

14

Collections Classes

• Collection is an interface

• Collections is a class

Page 344: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesCollections Classes

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

Data Structures

Many of the standard data structures and their corresponding algorithms are available in Java class libraries.

Collections data structures work only with objects. You can use the wrapper classes if you need implementations of the data structures for use with primitives.

Before Java 5, an object returned from a data structure must be downcast to whichever type you want. Generic types are in Java 5 to enforce typing and remove the need for explicit downcasting.

IBM Software Group | Tivoli software

15

Data Structures

• Add text

Page 345: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesCollections Classes

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

Collection Interfaces

Data structure classes get most of their methods by implementing interfaces.

• Collection: A set of methods for common to all data structures.

• List: Extends Collection. Contains basic List methods, and elements are accessible sequentially or by index. This interface is implemented by ArrayList and LinkedList.

• Set: Extends Collection and contains only one copy of a value. Contains the basic Set methods and is implemented by HashSet and TreeSet.

• Map: Stores key value pairs. Contains the basic Map methods. This interface is implemented by HashMap and TreeMap.

• SortedMap: Extends Map and adds access in sorted order.

• SortedSet: Extends Set, contains only one copy of a value, and can be accessed in order.

• Deque: Double-ended queue that can be used for both stack (LIFO) and queue (FIFO) implementations.

IBM Software Group | Tivoli software

16

Collection Interfaces

• Collection: A set of methods for working with data structures

• List: Extends Collection. Elements are accessible sequentially or by index

• Set: Extends Collection and contains only one copy of a value

• Map: Stores key value pairs

• SortedMap: Extends Map and adds access in sorted order

• SortedSet: Extends Set, contains only one copy of a value, and can be accessed in order

Page 346: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesCollections Classes

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

Collections Classes and Interfaces

The following classes and interfaces are found in the java.util package:

AbstractCollection<E> implements Collection<E>, Iterable<E> AbstractList<E> implements List<E> ArrayList<E> implements RandomAccess AbstractSequentialList<E> LinkedList<E> implements Deque<E>AbstractSet<E> implements Set<E> HashSet<E> LinkedHashSet<E>

TreeSet<E> implements SortedSet<E>

The most useful classes are:

• ArrayList: Sequence of values stored in a resizable array

• LinkedList: Sequence of values stored in a linked list

• HashSet: Single copy of value stored in a hash table

• TreeSet: Single copy of value stored in a binary tree

The Collections class contains many useful static methods.

IBM Software Group | Tivoli software

17

Collection Classes and Interfaces

• ArrayList: Sequence of values stored in a resizable array

• LinkedList: Sequence of values stored in a linked list

• HashSet: Single copy of value stored in a hash table

• TreeSet: Single copy of value stored in a binary tree

Page 347: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesCollections Classes

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

Map Classes and Interfaces

Other useful classes are HashMap and TreeMap.

AbstractMap<K, V> implements Map<K, V> HashMap<K, V> LinkedHashMap<K, V> // Keys can be iterated in insertion order. TreeMap<K, V> implements SortedMap<K, V>

The most useful classes are:

• HashSet: Key value pair in a hash table

• TreeSet.: Key value pair in a binary tree

IBM Software Group | Tivoli software

18

Map Classes and Interfaces

• HashMap: Key value pair in a hash table

• TreeMap: Key value pair in a binary tree

Page 348: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

Lesson 4: ArrayList<E> Class

Use the ArrayList<E> class in the java.util package for expandable arrays.

An ArrayList automatically expands as data is added, has methods for searching, inserting, and deleting, and can be traversed using indexes, iterators, or a foreach loop.

IBM Software Group | Tivoli software

19

ArrayList<E> Class

• In java.utils package

• An ArrayList expands as data is added

• An ArrayList has methods for searching, inserting, and deleting

• An ArrayList can be traversed using indexes, iterators, or a foreach loop

Page 349: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

Choosing an ArrayList

A simple array might be your best choice if any of the following conditions exists:

• There is a known number of elements

• The size is small and fixed

• The efficiency of using primitive types is important.

Otherwise, an ArrayList (or another Collections class) might be best.

ArrayList is the best choice when there is a large variation in the amount of data that you would put into an array. Arrays should be used when the amount of data is constant. For example, to store information about your company’s course offerings for the current week, use an ArrayList because the number of offerings for the week can change. Use an array for the student list because there is an upper limit of 12 (for example) on the number of students.

The ArrayList holds only object types. To use a primitive type in an ArrayList, you must either put it inside an object or use one of the wrapper classes. The wrapper classes are immutable, so you might prefer to define your own mutable class.

IBM Software Group | Tivoli software

20

Choosing an ArrayList

• Choose an ArrayList for a large, variable quantity

• Use only for object types

• Use an array for a small, fixed number of elements

• Use an array with primitive types

• Use wrapper classes if storing primitives in an ArrayList

Page 350: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

ArrayList Constructors

The following code creates ArrayList a of object type E. The initial default capacity is 10.

ArrayList<E> a = new ArrayList<E>();

The following code creates ArrayList with initial int capacity of size.

ArrayList<E> a = new ArrayList<E>(size);

The following code creates ArrayList from the Collection col.

ArrayList<E> a = new ArrayList<E>(col<E>) ;

IBM Software Group | Tivoli software

21

ArrayList Constructors

• ArrayList<E> a = new ArrayList<E>();

• ArrayList<E> a = new ArrayList<E>(size);

• ArrayList<E> a = new ArrayList<E>(coll <E>);

Page 351: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

Searching, Adding, and Deleting

There are many methods available to search, add, and delete from lists.

a.add(e) Adds e to end of ArrayList a

a.add(i, e) Inserts e at index i, shifting elements as necessary

a.set(i,e) Sets the element at index i to e

e = a.get(i) Returns the object at index i

iter = a.iterator() Returns an Iterator for forward traversal

liter = a.listIterator() Returns a ListIterator for forward, backward, or modifying traversal

liter = a.listIterator(i) Returns a ListIterator for forward, backward, or modifying traversal, starting at index i

liter = a.listIterator(a.size()) Returns a ListIterator for forward, backward, or modifying traversal, starting from the end

b = a.contains(e) Returns true if ArrayList a contains e

i = a.indexOf(e) Returns index of first occurrence of e, or -1 if not found

i = a.lastIndexOf(e) Returns index of last occurrence of e, or -1 if not found

IBM Software Group | Tivoli software

22

Searching, Adding, and Deleting

• a.add(e)

• a.add(i, e)

• a.set(i,e)

• e = a.get(i)

• iter = a.iterator()

• liter = a.listIterator()

• liter = a.listIterator(i)

• liter = a.listIterator(a.size())

• b = a.contains(e)

• i = a.indexOf(e)

• i = a.lastIndexOf(e)

• a.clear()

• a.remove(i)

• a.removeRange(i,j)

• i = a.size()

Page 352: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

a.clear() Removes all elements from ArrayList a

a.remove(i) Removes the element at position i

a.removeRange(i, j) Removes the elements from positions i thru j

a.size() Returns the number of elements in ArrayList a

Page 353: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

Looping over an ArrayList

Use one of the following ways to loop over an array list:

• foreach loop: Fast, but only traverses sequentially forward. This loop does not allow deletions, additions, or multiple references.

• for loop with an integer index: Fast and bidirectional traversal.

• Iterator: An Iterator<E> allows forward traversal. hasNext() returns true if there are more elements, and next() returns the next element.

• ListIterator: A ListIterator<E> allows traversal of the ArrayList with more options than an Iterator. It allows insertions, deletions, and bidirectional traversal.

The following example uses a simple MyObject class that contains a public integer x, and a default constructor that initializes x to 0.

ArrayList<MyObject> a = new ArrayList<MyObject>();MyObject o = new MyObject();a.add(o);

for (MyObject s : a) { System.out.println(s.x);}

IBM Software Group | Tivoli software

23

Looping over an ArrayListArrayList<String> a = new ArrayList<String>();String str = "Hello";a.add(str);

for (String s : a) {System.out.println(s);

}for (int i = 0; i < a.size(); i++) {

System.out.println(a.get(i));}for (Iterator<String> iter = a.iterator(); iter.hasNext(); ) {

System.out.println(iter.next());}

Page 354: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

for (int i = 0; i < a.size(); i++) { System.out.println(a.get(i).x);}

for (Iterator<MyObject> iter = a.iterator(); iter.hasNext(); ) { System.out.println(iter.next().x);}

Page 355: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

Iterator

Iterators are objects that allow you to traverse all the elements of a collection in sequence. The Iterator<E> interface in the java.util package provides one-way traversal. It replaces the Enumeration class, which was used before collections were added to the language.

The collections provide the iterators. They are created by calling the iterator() method of the data collection with iterators.

IBM Software Group | Tivoli software

24

Iterator

• Allows traversal of collection elements

• Traverses in sequence and one-way

• Collections provide the iterators

• Iterator is created by calling the iterator() method

Page 356: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

Iterator Methods

Iterator defines two methods and an optional third method:

• The hasNext() method returns a Boolean result. The return value is true if there are more elements for iteration.

• The next() method returns the next object. If a generic collection is being traversed, the return value will be the collection type. The pregeneric iterators required typecasting because the return value was of type Object.

• The remove() method removes the last element returned by the next() method. An UnsupportedOperationException is thrown if the collection does not support this method.

IBM Software Group | Tivoli software

25

Iterator Methods

• hasNext() method returns true if there are more elements

• next() method returns the next element

• remove() removes the last element returned by the iterator from the collection

Page 357: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

Iterator Example

For versions before Java 5, an explicit downcast is required to use the object that the next() method returns.

// Pre Java 5ArrayList aList = new ArrayList(); // . . . Add Strings to aList of type Object

for (Iterator iter = aList.iterator(); iter.hasNext(); ) { String s = (String)iter.next(); // Casting is required System.out.println(s);}

// Java 5 using genericsArrayList<String> aList = new ArrayList<String>(); // Add Strings to aList of type String

for (Iterator<String> iter = aList.iterator(); iter.hasNext();) { String s = iter.next(); System.out.println(s);}

// this foreach loop replicates the for loop abovefor (String s : aList) { System.out.println(s);}

IBM Software Group | Tivoli software

26

Iterator ExampleArrayList aList = new ArrayList(); // . . . Add Strings to aList of type Object

for (Iterator iter = aList.iterator(); iter.hasNext(); ) {String s = (String)iter.next(); // Casting is required System.out.println(s); }

// Using genericsArrayList<String> aList = new ArrayList<String>(); // Add Strings to aList of type String

for (Iterator<String> iter = aList.iterator(); iter.hasNext();) {String s = iter.next(); System.out.println(s); }

Page 358: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

ListIterator

The ListIterator is used by classes that implement the List interface, such as ArrayList and LinkedList.

The iterator is created by calling the listIterator() method of the data collection.

List iterator gives access to elements inside a linked list and protects the linked list while giving access.

IBM Software Group | Tivoli software

27

ListIterator

• Implemented by classes that implement the List interface

LinkedList, ArrayList, and so on

• Created by calling the listIterator() method

Page 359: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

ListIterator Methods

• The ListIterator contains the hasNext() and next() methods similar to those in Iterator.

• For traversing the list backwards, use the hasPrevious() method, which returns true if there is a previous element. The previous() method returns the previous element.

• The nextIndex() method returns the index of the element that would be returned by a subsequent call to the next() method.

• The previousIndex() method returns the index of the element that would be returned by a subsequent call to the previous() method.

• The add(obj) method adds obj into the collection before what would be the element returned by next() and after the element that would be returned by previous().

• The set() method replaces the last element returned by next() or previous().

• The remove() method removes the last element returned by next() or previous().

IBM Software Group | Tivoli software

28

ListIterator Methods

• bool = it.hasNext()

• obj = it.next()

• bool = it.hasPrevious()

• obj = it.previous()

• index = it.nextIndex()

• index = it.previousIndex()

• it.add(obj)

• it.set()

• it.remove()

Page 360: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

Using an Iterator and Indexing

A list can be traversed in a loop using an iterator or an index, but do not combine the two. After the hasNext() method returns true, the iterator is advanced by calling the next() method.

IBM Software Group | Tivoli software

29

Using an Iterator and Indexing

// Use iterator

for (Iterator<String> iter = aList.iterator(); iter.hasNext(); ) {

System.out.println(iter.next());

}

// Use indexing

for (int index=0; index < aList.size(); index++) {

System.out.println(aList.get(index));

}

Page 361: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

LinkedList Class Methods

The LinkedList class behaves as a double linked list. The following methods offer easy access to the first and last elements of the list:

• addFirst(E obj)

• addLast(E obj)

• getFirst()

• getLast()

• removeFirst()

• removeLast()

Other methods include:

• add(E obj)

• contains(Object 0bj)

• get(int index)

• remove(int index)

IBM Software Group | Tivoli software

30

LinkedList Class Methods

• addFirst(E obj): Adds element to the beginning of the list

• addLast(E obj): Adds element to the end of the list

• getFirst(): Returns element at the beginning of the list

• getLast(): Returns element at the end of the list

• removeFirst(): Removes element at the beginning of the list

• removeLast(): Removes element at the end of the list

• add(E obj): Adds element to the end of the list

• contains(Object 0bj): True if list contains the specified element

• get(int index): Returns element at the index position in the list

• remove(int index): Removes element at the index position

Page 362: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

LinkedList Example

The following code uses a specified text file and copies each line from the file into a linked 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 exist");

IBM Software Group | Tivoli software

31

LinkedList Examplepublic class LList {

public static void main(String[] args) { File inFile = new File(args[0]);

try {fillList(inFile);

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

}}

Page 363: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

System.exit(1); }

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

Page 364: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

Adding to a Linked List with fillList()

The fillList() method adds each String that represents a line for text from the input file to the LinkedList object.

IBM Software Group | Tivoli software

32

Adding to a LinkedList with fillList()

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

}……..

Page 365: Ibm enterprise it and asset management 7.1 java for customization training

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

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

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

Iterating through a LinkedList

The code in the slide illustrates using a ListIterator to traverse the LinkedList.

The following code includes two iterations through the list. The first uses a foreach loop and the second uses an iterator.

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()); }}}

IBM Software Group | Tivoli software

33

Iterating through a LinkedListpublic 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();

for (ListIterator<String> it = lst.listIterator(); it.hasNext();) {System.out.println(it.next());

} }

Page 366: Ibm enterprise it and asset management 7.1 java for customization training

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

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Autoboxing

Autoboxing (Java 5) is the automatic conversion made by the Java compiler between the primitive types and their corresponding wrapper classes. With autoboxing you can avoid the casting typically required by the Java Collections classes that cannot be used with the primitive types.

// Autoboxing

int i;Integer j;i = 4;j = 5;i = j;j = i;

// Without autoboxing

int i;Integer j;i = 4;j = new Integer(5);i = j.intValue();j = new Integer(i);

IBM Software Group | Tivoli software

34

Autoboxing

// Autoboxing

int i;Integer j;i = 4;j = 5;i = j;j = i;

// Without autoboxing

int i;Integer j;i = 4;j = new Integer(5);i = j.intValue();j = new Integer(i);

Page 367: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-41

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Student Exercise

Open your Student Exercises book and perform the exercises for this unit.

IBM Software Group | Tivoli software

35

Student Exercise

Page 368: Ibm enterprise it and asset management 7.1 java for customization training

8-42 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Review Questions

1. What is the difference between the StringBuffer and StringBuilder classes?

2. When should you use a StringBuffer object instead of an object of type String?

3. True or false: An ArrayList can contain both primitive and object types.

Page 369: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-43

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Review answers appear on next page.

Page 370: Ibm enterprise it and asset management 7.1 java for customization training

8-44 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Review Answers

1. What is the difference between the StringBuffer and StringBuilder classes?

The StringBuilder class, which is new to Java 5, is unsynchronized and faster. Otherwise, the two classes serve the same purpose.

2. When should you use a StringBuffer object instead of an object of type String?

A String object is immutable. If you intend to modify the object after creation, opt to use a StringBuffer or StringBuilder object.

3. True or false: An ArrayList can contain both primitive and object types.

False. An ArrayList can only contain object types.

Page 371: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 8-45

• • •••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Summary

IBM Software Group | Tivoli software

36

Summary

You should now be able to:Use the StringBuffer and StringBuilder classes

Use the LinkedList and ArrayList classes

Use the Iterator and ListIterator classes

Page 372: Ibm enterprise it and asset management 7.1 java for customization training

8-46 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 8: Strings, Arrays, and Collection ClassesArrayList<E> Class

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Page 373: Ibm enterprise it and asset management 7.1 java for customization training

• • • ••

9-1

Unit 9: Threads

© 2009 IBM Corporation

Unit 9: Threads

Page 374: Ibm enterprise it and asset management 7.1 java for customization training

9-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Introduction

This unit focuses on extending the Thread class to create multiple threads, and implementing the Runnable interface.

Objectives

IBM Software Group | Tivoli software

3

Threading Basics

• A thread is not a program

• A thread runs within a program

• A thread is a single sequential flow of control within a program

• Multiple threads allow two or more tasks to be running at the same time

Page 375: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-3

• • •••

Unit 9: ThreadsThreading Basics

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Lesson 1: Threading Basics

A thread is a process that appears to run in parallel with the main program, but it can be manipulated separately. Unlike another instance of the same program, a thread shares resources with the rest of the program. When a program starts a new thread, there is no longer a single path of execution.

IBM Software Group | Tivoli software

3

Threading Basics

• A thread is not a program

• A thread runs within a program

• A thread is a single sequential flow of control within a program

• Multiple threads allow two or more tasks to be running at the same time

Page 376: Ibm enterprise it and asset management 7.1 java for customization training

9-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsThreading Basics

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Multithreaded Programming

With multithreaded programming, two or more activities can perform in parallel within the same application. Each activity performs its tasks in its own thread. Each thread is a single path of execution with its own call stack and CPU state.

Threads run within the context of a process. Each process defines an address space within which the code and data exist and the thread executes, forming the basis for a multithreaded environment.

Effective multithreaded programming involves writing your application to use multiple threads in a manner whereby execution time is more efficient than a single-threaded application. You must understand how the JVM will handle your program when other programs are running simultaneously.

IBM Software Group | Tivoli software

4

Multithreaded Programming

Page 377: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-5

• • •••

Unit 9: ThreadsThreading Basics

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Advantages and Disadvantages of Using Multiple Threads

Some advantages of using multiple threads in your application include:

• Increased parallelization. Suppose your program must accomplish more than one task as a result of some event (like a service request coming across the network from another machine). If these tasks are essentially independent, with multithreading you can improve the performance of an application by having a separate thread perform each activity.

• In a single-threaded application, the time required to accomplish multiple tasks is the sum of the time that it takes to accomplish each task individually. In a multithreaded application, the total time required to accomplish all of the tasks should be the time it takes to complete the longest individual tasks.

• A multithreaded program can use threads to simplify the design of the program by assigning a thread to each well-defined, independent task.

• You can use multiple threads to separate the user interface from the rest of your application processing. Multithreading can improve the response time to the user if the application is still doing something in the background.

At times there are disadvantages to using multiple threads, especially when the overhead of additional threads outweighs the work performed without multiple threads.

IBM Software Group | Tivoli software

5

Advantages and Disadvantages of Using Multiple Threads• Advantages of using multiple threads:

Increased parallelization

Simplifies the design of the program

Improves response time

• Disadvantage to using multiple threads

Page 378: Ibm enterprise it and asset management 7.1 java for customization training

9-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsThreading Basics

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

The Life Cycle of a Thread

To create a thread, you instantiate an object of type Thread and send it the start() message. The start() message can be sent to any object that implements the Runnable interface.

Each thread has a run() method containing the thread’s behavior. A thread will continue running until the run() method returns, at which point the thread terminates.

A call to the sleep(), yield(), or wait() method moves the thread from a running state into a runnable state.

IBM Software Group | Tivoli software

6

The Life Cycle of a Thread

Page 379: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-7

• • •••

Unit 9: ThreadsThreading Basics

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Threads and the Operating System

In the JVM, the main memory is shared by all threads. In addition to the main memory, each thread also has its own private working memory. Where the working memory of the thread is located depends on the virtual machine implementation. A thread’s working memory is accessible only to the thread that owns it. Shared object data resides on the heap.

There are two possible threading models used by operating systems:

• Preemptive

• Cooperative

The choice is up to the implementers of the virtual machine and can vary. The choice also depends on the platform and how its thread scheduling system is implemented.

In the preemptive mode, threads can be interrupted in the middle of a section of code.

Cooperative threading allows the threads to decide when to yield the CPU to other threads that are waiting. The threads performing concurrently appear to be running at the same time. However, they are taking turns performing their bytecode instructions. The threads share the CPU and the time slicing is managed by the scheduler.

Java threads map to OS-level threads, so the scheduler decides, based on priority and other factors, which task should execute next. Therefore, threading is ultimately handled by the operating system.

IBM Software Group | Tivoli software

7

Threads and the Operating System

• Main memory is shared by all

• Each thread has its own working memory

• Two threading models:Preemptive (Time-slicing)

Cooperative (Non-time-slicing)

• Threads are ultimately handled by the operating system

Page 380: Ibm enterprise it and asset management 7.1 java for customization training

9-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsThreading Basics

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Preemptive Threading

The JVM is preemptive. Threads preempt other threads based on their relative priority to each other.

However, the system implementation of threads underlying the Thread class can indirectly support time slicing. Each thread gets a set amount of CPU time for executing. After it has used up its time with the CPU, it is removed from accessing the CPU and any other waiting threads get a chance at CPU time. When each thread has had its chance with the CPU, the cycle starts again. This implementation ensures that each thread will get at least some time executing.

IBM Software Group | Tivoli software

8

Preemptive Threading

• JVM is preemptive

• Threads preempt others based on relative priorities

Page 381: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-9

• • •••

Unit 9: ThreadsThreading Basics

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Priorities

A non-time-slicing implementation for the threading system is cooperative. A priority system determines which thread will run.

The thread with the highest priority gets the CPU. Programs under this system must be written so that the threads voluntarily yield access to the CPU.

A thread inherits its priority from the thread that created it. You can modify a thread’s priority at any time after its creation by using the setPriority method. Thread priorities are integers that range between MIN_PRIORITY and MAX_PRIORITY, which are constants defined in the Thread class. Use the getPriority method to determine the priority of a thread.

When multiple threads are ready to be executed, the runtime system chooses the thread with the highest priority. When that thread moves out of the run state (yields, waits, sleeps), a lower-priority thread can run.

IBM Software Group | Tivoli software

9

Priorities

• Priority is inherited

• setPriority()

• MIN_PRIORITY and MAX_PRIORITY

• getPriority()

Page 382: Ibm enterprise it and asset management 7.1 java for customization training

9-10 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsThreading Basics

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Thread States

A thread has many states:

• Ready: Waiting for CPU time whenever the scheduler will permit

• Running: The scheduler has permitted the thread to run and the instructions in the run() method are being executed

• Sleeping: When the Thread.sleep() method is called

• Blocked: When the thread is blocked for some resource

• Waiting: When the wait() method is called

IBM Software Group | Tivoli software

10

Thread States

• Ready

• Running

• Sleeping

• Blocked

• Waiting

Page 383: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-11

• • •••

Unit 9: ThreadsThreading Basics

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Blocking and Yielding

A thread that cannot execute is said to be blocked. Handling blocking can be accomplished in various ways.

The thread might be blocked because:

• It has been put to sleep.

• It has been suspended with a call to wait(). It will become runnable with a notify() or notifyAll( ) message.

• It has been suspended with a call to suspend(). This method and resume() have been depreciated.

Java threading is platform-dependent, and you cannot be certain if a thread will ever yield the CPU to other threads. The threading system might or might not give different threads a share of the CPU time. For this reason, the Thread class has a static method called yield(). The yield( ) method causes the currently running thread to yield its hold on the CPU and return to the ready state. The thread scheduling system then can give other threads the CPU, if there are other threads in the ready state.

IBM Software Group | Tivoli software

11

Blocking and Yielding

• A thread that is unable to execute is blocked

• sleep()

• wait()

• yield()

• suspend()

Page 384: Ibm enterprise it and asset management 7.1 java for customization training

9-12 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsThreading Basics

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Locks and Critical Sections

A lock specifies that access was granted to a thread that has entered a synchronized method or block. A critical section is a synchronized method or block of code that can be executed by only one thread at a time. Although a thread has acquired the lock, the lock is associated with an instance of an object or a specific class.

Each object has a lock associated with it. Critical sections of the code are protected by monitors. A monitor is essentially a synchronized method or block. To enter a critical section, a thread must acquire the corresponding lock. Whenever a resource could possibly be accessed by more than one thread, the access to that resource should be controlled with monitors. Only one thread can acquire the lock on an object and gain access to the critical section at any point of time.

Methods, or synchronized blocks of code, can only be executed by one thread at a time for a given instantiation of a class. The reason is that code requires obtaining the object’s lock before execution.

A lock is associated with an Object and a thread can possess a lock of any object. If a thread possesses a lock, the lock is not relinquished if the thread moves into a sleep or blocked state. The lock is relinquished if the thread goes into a wait state.

IBM Software Group | Tivoli software

12

Locks and Critical Sections

• Critical sections of code are synchronized methods or blocks of code

• Critical sections are protected by a monitor

• A thread acquires a lock

• A lock is associated with an object or class

• A lock is not relinquished by a sleeping or blocked thread

• A lock is relinquished by a thread that enters the wait state

Page 385: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-13

• • •••

Unit 9: ThreadsThreading Basics

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Deadlock

Deadlock is a classic multithreading problem in which all work is incomplete because different threads are waiting for locks that will never be released.

If all four of the following conditions is present, a deadlock condition exists:

• Process has exclusive control of a resource or resources

• Process is holding a resource and waiting for another

• Resource cannot be removed from a process

• Circular wait exists, whereby each process holds one or more resources requested by another process

Take prevention and detection steps. Some possible strategies are:

• Acquire all resources first

• Acquire in a set order

• Detect, end some or all processes, and clean up

IBM Software Group | Tivoli software

13

Deadlock• Four conditions for deadlock

• Take steps for prevention and detection

Page 386: Ibm enterprise it and asset management 7.1 java for customization training

9-14 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsThreading Basics

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Semaphore

A semaphore manages a certain number of permissions to a shared resource. A thread requests a permission before accessing the resource. When the thread has finished with the resource, it releases the permission. If a thread requests a permission and the maximum number of permissions have been granted to other threads, the requesting thread will block until a permission is available.

IBM Software Group | Tivoli software

14

Semaphore

• A shared resource with a specified number of permissions

• Thread requests a permission

• When completed with shared resource, thread releases permission

• Requesting threads block until permission is granted

Page 387: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-15

• • •••

Unit 9: ThreadsThreading Basics

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Starvation

Starvation occurs when one thread cannot access the CPU because one or more other threads are monopolizing it. Low-priority threads starve if the higher-priority threads do not yield control of the CPU appropriately.

For threads to cooperate, the programmer must ensure that threads do not monopolize the processor and deprive other threads of CPU time. If thread priorities are set inappropriately, a thread can starve other threads.

The application developer determines when threads will yield to other threads, allowing them to work with one another. One way to do this is to call yield(), which moves the current thread off the CPU. You can also call sleep(), so that the thread gives up the CPU and does not allow it to run until the time specified to sleep has passed. Another solution is to call wait(), so that the CPU will give up the lock belonging to the current object.

IBM Software Group | Tivoli software

15

Starvation

• Occurs when thread cannot access CPU

• High-priority threads can monopolize the CPU

• Thread priorities must be set appropriately

• yield()

• sleep()

• wait()

Page 388: Ibm enterprise it and asset management 7.1 java for customization training

9-16 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Lesson 2: Implementing Threads

There are two methods of creating a new thread:

• Extend the Thread class.

• Create a class that implements the Runnable interface.

IBM Software Group | Tivoli software

16

Implementing Threads

• Extend Thread class

• Implement Runnable interface

Page 389: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-17

• • •••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

The Thread Class

One way to create threads is to extend the Thread class and override the run() method:

class TestThread extends Thread{ public void run() { // thread processing }}

When you create a thread by extending the Thread class, you cannot inherit from any other class because Java is restricted to single inheritance. You are restricted from inheriting the functionality of another class.

IBM Software Group | Tivoli software

17

The Thread Class

class TestThread extends Thread {

public void run() {

// thread processing

}

}

Page 390: Ibm enterprise it and asset management 7.1 java for customization training

9-18 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

The Runnable Interface

You would typically implement the Runnable interface rather than extending Thread, because the goal is not to provide some new Thread functionality.

Instead, you want the code to have the capability of running independently. You want to create something that can be run in a thread, not a new kind of thread.

class TestThread implements Runnablepublic void run() { // thread processing }}

The following code creates two threads:

TestThread tt1 = new TestThread();TestThread tt2 = new TestThread();Thread t1 = new Thread(tt1);Thread t2 = new Thread(tt2);

Your class that implements Runnable is passed as a parameter to the constructor of the Thread class. Thread creation requires the creation of a Thread instance.

IBM Software Group | Tivoli software

18

The Runnable Interface

class TestThread implements Runnablepublic void run()

{

// thread processing

}}

• Creating thread:TestThread tt1 = new TestThread();Thread t1 = new Thread(tt1);

Page 391: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-19

• • •••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Starting a Thread

The code that your thread executes is in the run() method, but this method is not called directly. Instead, you call the start() method of the thread class. If you call the run() method directly, it will execute like any other method rather than part of a thread of execution.

The Runnable interface does not contain a start() method, so you must pass your class that implements the Runnable interface to an instance of the Thread class. The following code is an example of executing threads from a class that implements Runnable:

TestThread tt1 = new TestThread();TestThread tt2 = new TestThread();Thread t1 = new Thread(tt1);Thread t2 = new Thread(tt2);t1.start();t2.start();

IBM Software Group | Tivoli software

19

Starting a Thread

• Do not call run() method directly

• start()

TestThread tt1 = new TestThread();TestThread tt2 = new TestThread();Thread t1 = new Thread(tt1);Thread t2 = new Thread(tt2);t1.start();t2.start();

Page 392: Ibm enterprise it and asset management 7.1 java for customization training

9-20 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Thread Example

Next you will examine a class that extends the Thread class. Its run() method will assign random points to a specific location.

IBM Software Group | Tivoli software

20

Thread Example

• Four locations

• Assign points randomly to each location

• Execute a thread for each location

Page 393: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-21

• • •••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Extending the Thread Class

The slide contains the run() method for a class that extends the Thread class. The run() method assigns a random number of points and prints the name of the class. The number of points is dictated by the random value of the maxLoop variable.

IBM Software Group | Tivoli software

21

Extending the Thread Class

public void run() {int points = 0; int maxLoop = (int)(Math.random()*10 + 1);

for (int i=0; i < maxLoop; i++) {try {

sleep((long) (Math.random() * 1000));points++;

} catch (InterruptedException e) {}

}System.out.println(getName() + " points " + points);

}

Page 394: Ibm enterprise it and asset management 7.1 java for customization training

9-22 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Running the Thread Class

The start() method starts the thread’s run() method.

public class SimpleThread extends Thread {

public SimpleThread(String threadName) { super(threadName); }

public void run() { int points = 0; int maxLoop = (int)(Math.random()*10 + 1);

for (int i=0; i < maxLoop; i++) { try { sleep((long) (Math.random() * 1000)); points++; } catch (InterruptedException e) {} } System.out.println(getName() + " points " + points); }}

IBM Software Group | Tivoli software

22

Running the Thread Class

public class ExtendThreadDemo {

public static void main(String[] args) {

new SimpleThread("Italy").start();

new SimpleThread("Kenya").start();

new SimpleThread("India").start();

new SimpleThread("Mexico").start();

}

}

Page 395: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-23

• • •••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

The following example shows output from running this program three times:

Italy points 3Kenya points 4India points 8Mexico points 7

Mexico points 1Kenya points 2Italy points 2India points 7

India points 1Mexico points 3Italy points 8Kenya points 4

Page 396: Ibm enterprise it and asset management 7.1 java for customization training

9-24 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Implementing the Runnable Interface

The illustrated code belongs to the run() method of a class that implements the Runnable interface. The only difference from the previous run() method example (belonging to the SimpleThread class) is the retrieval of the thread’s name. In this case, the thread’s name is retrieved by chaining the getName() method to the currentThread() method. The currentThread() method returns a reference to the currently executing thread.

IBM Software Group | Tivoli software

23

Implementing the Runnable Interface

public void run() {int points = 0; int maxLoop = (int)(Math.random()*10 + 1);

for (int i=0; i < maxLoop; i++) {try {

Thread.sleep((long) (Math.random() * 1000));points++;

}catch (InterruptedException e) {}

}System.out.println(Thread.currentThread().getName() + " points " + points);

}

Page 397: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-25

• • •••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Running the Class

Running this program three times produces the following output:

Mexico points 2India points 10Italy points 10Kenya points 10

Italy points 3Mexico points 5India points 9Kenya points 10

India points 1Italy points 2Mexico points 6Kenya points 9

IBM Software Group | Tivoli software

24

Running the Class

public class RunnableThreadDemo {

public static void main(String[] args) {SimpleRunnable s1 = new SimpleRunnable();SimpleRunnable s2 = new SimpleRunnable();SimpleRunnable s3 = new SimpleRunnable();SimpleRunnable s4 = new SimpleRunnable();new Thread(s1, "Italy").start();new Thread(s2, "Kenya").start();new Thread(s3 ,"India").start();new Thread(s4, "Mexico").start();

}}

Page 398: Ibm enterprise it and asset management 7.1 java for customization training

9-26 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Synchronization

The ability of a thread to execute in parallel with the main or other threads or with other threads is a source of problems for programmers. You must ensure proper sharing of the resources used by different threads. The threads must be synchronized at certain points to ensure proper functioning of the system. Avoid conflicts of several threads simultaneously performing the same operation, such as writing to a buffer, modifying a common variable, and so on. With synchronization, a thread must wait for another thread to leave these critical sections of code, if it has already entered this section. It also means that the thread must enter into this section using some security measures.

IBM Software Group | Tivoli software

25

Synchronization

• Threads must synchronize the use of shared resources

• Threads should not be writing to the same buffer or changing a variable at the same time

• One thread must wait for another to finish

• Synchronize threads to avoid unexpected program results

Page 399: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-27

• • •••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Synchronization Example

Without synchronization, this programs prints different results. A thread performs its task regardless of what other threads in the same application are doing. If threads are time-sliced, they can run at arbitrary times as directed by the operating system.

In this example, two threads use the same object and modify the same variable. This modification should not be performed simultaneously by different processes, but the program imposes no restriction on the two processes. Because the two processes perform the incrementation simultaneously, the resulting output is unpredictable.

package exercises.threads;

public class CounterThread extends Thread { Counter ctr; public static void main(String[] args) { Counter ctr = new Counter(); CounterThread ct1 = new CounterThread(ctr); CounterThread ct2 = new CounterThread(ctr); ct1.start(); ct2.start(); try{ ct1.join(); ct2.join(); } catch (InterruptedException e) {System.out.println("join() error");}

IBM Software Group | Tivoli software

26

Synchronization Examplepublic class CounterThread extends Thread {

Counter ctr; public static void main(String[] args) {

Counter ctr = new Counter();CounterThread ct1 = new CounterThread(ctr);CounterThread ct2 = new CounterThread(ctr);ct1.start();ct2.start();try{ct1.join();ct2.join();

} catch (InterruptedException e) {System.out.println("join() error");}System.out.println("The counter = "+ ctr.get()+ ", the expected value i= 20");

} public void run() {ctr.count(); } }

Page 400: Ibm enterprise it and asset management 7.1 java for customization training

9-28 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009• • • ••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

System.out.println("The counter = "+ ctr.get()+ ", the expected value i= 20");}

public CounterThread(Counter ctr) { this.ctr = ctr; }

public void run() { ctr.count(); } }

class Counter { int i = 0;

public void count() { for (int j=0; j<10; j++){ i=inc(i); try{ Thread.sleep((int) (Math.random()*10)); } catch (InterruptedException e) {System.out.println("count():sleep() error");} } }

public int get(){ return i; }

private int inc(int n){ try{ Thread.sleep((int) (Math.random()*5)); } catch (InterruptedException e) {System.out.println("inc():sleep() error");} return n+1; }}

Page 401: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-29• • •••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

The Producer-Consumer Example

The Producer-Consumer example has two classes, Producer and Consumer, and a SharedData class that stores an integer value. The Producer writes integer values into the SharedData object and the Consumer reads these values.

You want to synchronize the Producer and Consumer so that the values will be consistent. Their consistency must be maintained even when the Producer performs multiple writes consecutively and when the Consumer performs multiple reads.

public class ProducerConsumerSynch {

public static void main(String[] args) { SharedData data; Thread ProducerThread; Thread ConsumerThread;

data = new SharedData(); ProducerThread=new Thread (new Producer(data)); ProducerThread.setPriority(Thread.MAX_PRIORITY); ProducerThread.start();

ConsumerThread = new Thread (new Consumer(data)); ConsumerThread.setPriority(Thread.MIN_PRIORITY);

IBM Software Group | Tivoli software

27

The Producer-Consumer Example

• Producer class

• Consumer class

• SharedData class

• A driver with main() defined

Page 402: Ibm enterprise it and asset management 7.1 java for customization training

9-30 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009• • • ••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

ConsumerThread.start(); }}

class Producer implements Runnable { SharedData data; public Producer(SharedData data) { this.data=data; } public void run() { int i; for(i=0; ; i++) { data.put(i); System.out.println("Producer "+ i); try {

Thread.sleep((int) (Math.random()*10)); } catch (InterruptedException e) { System.out.println("Producer error\n"); } } }}

class Consumer implements Runnable{ SharedData data; public Consumer(SharedData data) { this.data=data; } public void run() { for(;;) { System.out.println(" Consumer: "+ data.get()); try { Thread.sleep((int) (Math.random()*100)); } catch (InterruptedException e) { System.out.println("Consumer error\n"); } } }}

public class SharedData { protected int Data; public void put(int Data) { this.Data=Data; }

Page 403: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-31• • •••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

public int get() { return this.Data; }}

Page 404: Ibm enterprise it and asset management 7.1 java for customization training

9-32 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009• • • ••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Synchronized Methods

Use the synchronized keyword to synchronize a method or a block of code.

IBM Software Group | Tivoli software

28

Synchronized Methods

public synchronized void put(int Data) {

while (data2Consume) {

try {

wait();

} catch (InterruptedException e) {}

}

this.Data=Data;

data2Consume = true;

notifyAll();

}

Page 405: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-33

• • •••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Using wait() and notify()

The wait() and notify() methods can be used within a synchronized block of code to control thread execution. The wait() method causes the thread to wait until another thread invokes the notify() or notifyAll() method for the object.

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) {

IBM Software Group | Tivoli software

29

Using wait() and notify()

public synchronized int get() {

int Data;

while(!data2Consume) {

try {

wait();

} catch (InterruptedException e) {}

}

Data = this.Data;

data2Consume = false;

notifyAll();

return Data;

}

Page 406: Ibm enterprise it and asset management 7.1 java for customization training

9-34 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

try { wait(); } catch (InterruptedException e) {} } Data = this.Data; data2Consume = false; notifyAll(); return Data; }}

Page 407: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-35

• • •••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Student Exercise

Open your Student Exercises book and perform the exercises for this unit.

IBM Software Group | Tivoli software

30

Student Exercise

Page 408: Ibm enterprise it and asset management 7.1 java for customization training

9-36 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Review Questions

1. In multithreaded programming, what is synchronization?

2. True or false: With synchronization, one thread can modify a shared variable while another thread is using or updating the same shared variable.

3. What are two ways to implement a thread?

4. What is the advantage of using an interface versus inheriting from the Thread class?

5. What are the recommended ways to block a thread?

Page 409: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-37

• • •••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Review answers appear on next page.

Page 410: Ibm enterprise it and asset management 7.1 java for customization training

9-38 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Review Answers

1. In multithreaded programming, what is synchronization?

Synchronization is the ability to control the access for multiple threads to shared resources.

2. True or false: With synchronization, one thread can modify a shared variable while another thread is using or updating the same shared variable.

False. Without synchronization, threads can access shared resources without access control and the results might be unpredictable.

3. What are two ways to implement a thread?

Using the Runnable interface or inheriting from the Thread class

4. What is the advantage of using an interface versus inheriting from the Thread class?

The Runnable interface can mimic multiple inheritance.

5. What are the recommended ways to block a thread?

sleep() and wait/notify. suspend() has been depreciated and is not recommended.

Page 411: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 9-39

• • •••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Summary

IBM Software Group | Tivoli software

31

Summary

You should now be able to:Create threads

Determine and set thread priorities

Synchronize threads

Block threads

Page 412: Ibm enterprise it and asset management 7.1 java for customization training

9-40 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 9: ThreadsImplementing Threads

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Page 413: Ibm enterprise it and asset management 7.1 java for customization training

• • • ••

10-1

Unit 10: Serialization and Remote Method Invocation

© 2009 IBM Corporation

Unit 10: Serialization and Remote Method Invocation

Page 414: Ibm enterprise it and asset management 7.1 java for customization training

10-2 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 10: Serialization and Remote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Introduction

This unit covers object serialization and Remote Method Invocation. Using serialization, you can save and reconstruct an object’s state. This process is used when implementing Remote Method Invocation.

Objectives

IBM Software Group | Tivoli software

2

Objectives

Upon completion of this unit, you will be able to:Describe the benefits of using serialization

Create an object and serialize its state

Implement Remote Method Invocation (RMI)

Page 415: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-3

• • •••

Unit 10: Serialization and Remote Method InvocationSerialization

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Lesson 1: Serialization

Serialization is the process whereby an object’s current state is saved as a stream of data. An object’s variables define its state. Reversing the serialization process is called deserialization.

IBM Software Group | Tivoli software

3

Serialization

• Converts an object’s state

• Reconstructs an object’s state

Page 416: Ibm enterprise it and asset management 7.1 java for customization training

10-4 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 10: Serialization and Remote Method InvocationSerialization

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Serialization of an Object

Serializing an object transforms the current information contained in the object into a byte stream. In this form, the stream can be sent over the wire, stored to a file, or manipulated as a stream of data.

Serialization can be used to save variables or to communicate through network connections. In this manner, information can persist outside of the program that created it.

IBM Software Group | Tivoli software

4

Serialization of an Object

• Process that saves an instance’s current state to a stream

• Reconstructing the object is deserialization

• The stream can optionally be sent across a socket or to a file, or manipulated as a data stream

• Supports the persistence of objects

Page 417: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-5

• • •••

Unit 10: Serialization and Remote Method InvocationSerialization

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Why Use Serialization

Serialization is used by Remote Method Invocation (RMI) to pass objects between JVMs.

Without serialization, a client’s passing of an instance of an object to a server implies that the server can use the object. The RMI runtime layer will construct a stub of the object instance and use it like the real object. Every time the server invokes one of the object’s methods, a method call will be sent across the network.

A better solution is to copy the object instance as a whole and send it to the server. The client would have the original instance and the server would have a serialized copy of the instance.

The objects are passed as arguments in a method invocation from a client to a server, or they are the return values from a method invocation. With serialization, information that is a complete representation of an object’s current state can be written. No further network calls are needed.

IBM Software Group | Tivoli software

5

Why Use Serialization

• Used to pass objects between JVMs

• Server must invoke methods on client object

• Copy client instance and pass current state to server

Page 418: Ibm enterprise it and asset management 7.1 java for customization training

10-6 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 10: Serialization and Remote Method InvocationSerialization

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Static and Transient Variables

A static variable cannot be serialized. A static variable is associated with a class, rather than with an instance.

The reserved word transient is used to identify a variable in a serializable object as nonpersistent. The variable marked as transient will not be serialized.

IBM Software Group | Tivoli software

6

Static and Transient Variables

• Static variables cannot be serialized

• Variable that are marked with the transient keyword are ignored by the serialization process

Page 419: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-7

• • •••

Unit 10: Serialization and Remote Method InvocationSerialization

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Making a Class Serializable

There are four basic steps to implementing serialization:

1. Implement the Serializable interface.

2. Verify that the instance is properly serialized.

3. Verify that superclasses are properly serialized.

4. Override the equals() and hashCode() methods.

IBM Software Group | Tivoli software

7

Making a Class Serializable

• Implement the Serializable interface

• Verify that the instance level is serialized

• Verify that the superclass is serialized properly

• Override equals() and hashCode() methods

Page 420: Ibm enterprise it and asset management 7.1 java for customization training

10-8 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 10: Serialization and Remote Method InvocationSerialization

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Implementing the Serializable Interface

The Serializable interface is an empty interface. Add implements Serializable to the class declaration to make the class serializable.

IBM Software Group | Tivoli software

8

Implementing the Serializable Interface

• Is an empty interface

• Add implements Serializable to the class declaration

Page 421: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-9

• • •••

Unit 10: Serialization and Remote Method InvocationSerialization

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Instance and Superclass State

An object’s variables define its state. If all of the object variables are primitives or serializable objects, the serialization mechanism will work without taking additional steps.

Otherwise, you must ensure that the instance-level, locally defined state is serialized properly. You must also provide any extra information so that the fields that cannot be serialized are handled properly.

If some objects are not serializable, try using one of the following options:

• The variable can be transient. The serialization mechanism ignores variables that are marked with the keyword transient.

• If the data cannot be ignored, use the writeObject() and readObject() methods to save and restore the variable’s state.

• Use serialPersistentFields to explicitly identify a variable that should be serialized. Unlike the transient variable, you do not have to have access to the code to declare a field as serialPersistentFields.

In addition to the locally declared state of the instance, verify that the variable declared in the superclass or superclasses is serialized properly.

IBM Software Group | Tivoli software

9

Instance and Superclass State

• Declare transient fields when necessary

• If data cannot be ignored, use the writeObject() and readObject() methods

• Use serialPersistentFields to explicitly identify variables whose state should be serialized

• Determine whether the state of the superclass variables is serialized properly

Page 422: Ibm enterprise it and asset management 7.1 java for customization training

10-10 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 10: Serialization and Remote Method InvocationSerialization

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

equals() and hashCode()

The equals() and hashCode() methods are inherited from Object. Usually the Object implementation is not suitable for serialization and you must override both of these methods.

IBM Software Group | Tivoli software

10

equals() and hashCode()

• equals() and hashCode() methods are inherited from Object

• Usually the inherited methods are not appropriate for serialization

• Override equals() and hashCode()

Page 423: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-11

• • •••

Unit 10: Serialization and Remote Method InvocationSerialization

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Serialization Classes

Serialization is implemented using an output and input stream. The classes support a complex process, but were designed to make the process of serialization as transparent as possible to the developer.

ObjectOutputStream and ObjectInputStream are defined in the java.io package. The ObjectOutputStream stream implements the writing tasks of the serialization process. ObjectInputStream implements the reading part of the serialization process. Objects serialized with ObjectOutputStream can be deserialized with ObjectInputStream.

Methods implemented by ObjectOutputStream can be classified as:

• Methods that write information to the stream

• Methods that control the stream’s behavior

• Methods to customize the serialization process

Methods implemented by ObjectInputStream can be classified as:

• Methods that read information from the stream

• Methods that control the stream’s behavior

• Methods to customize the serialization process

IBM Software Group | Tivoli software

11

Serialization Classes

• ObjectOutputStream– Methods that write information to the stream– Methods that control the stream’s behavior– Methods to customize the serialization process

• ObjectInputStream– Methods that read information from the stream– Methods that control the stream’s behavior– Methods to customize the serialization process

Page 424: Ibm enterprise it and asset management 7.1 java for customization training

10-12 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 10: Serialization and Remote Method InvocationSerialization

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

writeObject() and readObject()

When the serialization process starts, it checks whether the class implements writeObject() and calls it.

Create an instance of ObjectOutputStream and implement the writeObject() method to serialize an object. Create an instance of ObjectInputStream and implement the readObject() method to read a serialized object. If you perform any serialization customization to either writeObject() or readObject(), be sure to implement customizations to both.

IBM Software Group | Tivoli software

12

writeObject() and readObject()

• Serialization process checks whether class implements writeObject()

• Create instance of ObjectOutputStream and implement writeObject()

• Create instance of ObjectInputStream and implement readObject()

• Do not customize writeObject() without also customizing readObject(), and vice versa

Page 425: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-13

• • •••

Unit 10: Serialization and Remote Method InvocationSerialization

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Serialization Implementation Summary

To make a class serializable:

• The class must implement the Serializable interface.

• The instance-level state and superclass state must be properly serialized.

• If necessary, implement the writeObject() method to serialize an object and the readObject() object to read a serialized object.

• If necessary, override the equals() and hashCode() methods found in Object.

IBM Software Group | Tivoli software

13

Serialization Implementation Summary

• The class must implement the Serializable interface

• The instance-level state and superclass state must be properly serialized

• If necessary, implement the writeObject( ) method to serialize an object and the readObject( ) object to read a serialized object

• If necessary, override the equals( ) and hashCode( )methods found in Object

Page 426: Ibm enterprise it and asset management 7.1 java for customization training

10-14 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 10: Serialization and Remote Method InvocationSerialization

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Serialization Example

The FileOutputStream and FileInputStream constructors are overloaded to accept a File object or a String representing a file name. The following code writes the state of so to a file and then reads the serialized data back into the so object:

SerialObject so = new SerialObject();File serialFile = new File("c:\\Serial.txt";); // create a file stream for writingFileOutputStream fos = new FileOutputStream(serialFile);// create object to write to fosObjectOutputStream oStream = new ObjectOutputStream(fos);// save object stateoStream.writeObject(so);oStream.flush(); // create a file stream for readingFileInputStream fis = new FileInputStream("c:\\Serial.txt";);// create object to read fisObjectInputStream iStream = new ObjectInputStream(fis);// retrieve the object's serialized stateso = (SerialObject)iStream.readObject();

IBM Software Group | Tivoli software

14

Serialization Example

SerialObject so = new SerialObject();

File serialFile = new File("c:\\Serial.txt";);

FileOutputStream fos = new FileOutputStream(serialFile);ObjectOutputStream oStream = new ObjectOutputStream(fos);oStream.writeObject(so);oStream.flush();

FileInputStream fis = new FileInputStream("c:\\Serial.txt";);ObjectInputStream iStream = new ObjectInputStream(fis);so = (SerialObject)iStream.readObject();

Page 427: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-15

• • •••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Lesson 2: Remote Method Invocation

Using Remote Method Invocation (RMI), Java programmers can develop distributed programs.

The RMI specification takes into consideration how objects communicate in a multiple JVM environment, and how those objects are defined to behave.

IBM Software Group | Tivoli software

15

Remote Method Invocation

• Allows development of distributed Java programs

• Environment includes multiple JVMs

• RMI specification defines:– How objects communicate– Exceptions– How parameters are passed to and returned from remote

methods– Memory management in a distributed environment

Page 428: Ibm enterprise it and asset management 7.1 java for customization training

10-16 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Distributed Computing and RMI

With distributed computing, networking computers can share resources and data between themselves. RMI is the basis for object-oriented distributed computing. You can use RMI and connect to Java components running on another JVM.

Although RMI was designed to use the same syntax and semantics as local programs, there are some differences:

• A remote object’s behavior is defined by an interface that extends the Remote interface.

• A remote object is accessed using an object reference that points to a proxy stub implementation of the object’s remote interface. The stub contains the information to connect to the remote object, which has the method implementations.

• RMI forces distributed applications to handle any RemoteException objects that are thrown.

• Memory management must account for both local and remote references to an object before it is reclaimed by garbage collection.

IBM Software Group | Tivoli software

16

Distributed Objects and RMI

• Remote object’s exported behavior is defined by an interface that extends the Remote interface

• Object reference points to a proxy stub that contains information to connect to the method implementations on the remote object

• RemoteException objects must be handled

• Garbage collection takes local and remote references into account

Page 429: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-17

• • •••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Interfaces

The code that defines behavior and the code that implements that behavior are separate and can run on separate JVMs.

The definition of a remote service is coded in an interface and the implementation of the remote service is coded in a class. Remember that interfaces define behavior and classes are implementations.

The client side concerns itself with the service definition, while the server side provides the service itself.

IBM Software Group | Tivoli software

17

Interfaces

• Interfaces define behavior

• Classes are implementations of behavior

• Client is focused on the service definitions

• Server provides the class implementation

Page 430: Ibm enterprise it and asset management 7.1 java for customization training

10-18 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Client and Server Programs

A Java interface cannot contain executable code; a class must implement the code. RMI supports two classes that implement the same remote interface. One class runs on the server and implements the behavior. The other class runs on the client and is a proxy stub for the remote service.

The client program calls methods on the proxy stub, and RMI sends the request to the remote server that contains the implementation. If the implementation provides a return value, it is returned to the proxy stub and forwarded to the client program.

IBM Software Group | Tivoli software

18

Client and Server Programs

• Two classes implement the same remote interface – One implements the behavior and runs on the server – The other runs on the client and is a proxy for the remote service

• The client programs calls methods on the proxy and the request goes to the remote server that contains the implementation

Page 431: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-19• • •••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

RMI Architecture

RMI is composed of three layers of abstraction. The first contains stubs and this layer accepts method calls made by the client and redirects them to a remote service.

The next layer is the remote reference layer. This layer interprets and manages references made from clients to remote service objects.

The transport layer provides basic connectivity and is based on the TCP/IP connections across the network.

IBM Software Group | Tivoli software

19

RMI Architecture

• Three layers of abstraction– Stubs– Remote reference layer– Transport layer

• Significant changes after Java 1.1

Page 432: Ibm enterprise it and asset management 7.1 java for customization training

10-20 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009• • • ••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Proxy Stubs

RMI uses the Proxy design pattern for the stub layer. In the Proxy design pattern, an object is represented by a surrogate object in another context. The proxy forwards method calls between objects.

Within the architecture of RMI, the stub class is the proxy. The remote service implementation is the RealSubject.

The remote service can communicate with the stub across the connection. It can get parameters for the method call and send the return values back to the stub.

IBM Software Group | Tivoli software

20

Proxy Stubs

Page 433: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-21• • •••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Remote Reference and Transport Layers

The transport layer connects the JVMs through their host computer’s TCP/IP network protocol stack.

TCP/IP connections are used for all machine-to-machine connections. The connections are based on an IP address (or DNS name) and a port number at each end.

The remote reference layer interprets and manages references made from clients to remote service objects. Once a reference is obtained, methods invocations are forwarded to the remote reference and on to the remote object.

IBM Software Group | Tivoli software

21

Remote Reference and Transport Layers

Page 434: Ibm enterprise it and asset management 7.1 java for customization training

10-22 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009• • • ••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Finding RMI Remote Services

A client finds an RMI remote service from a naming or directory service running on a known host and port number.

RMI can use one of many directory services, such as the Java Naming and Directory Interface (JNDI). RMI includes its own directory service called the RMI Registry, rmiregistry.

On the server, a program creates a local object that implements the remote service. When that object is exported, RMI creates a service that listens for clients to connect and request the service. After the service is exported, the server registers the object in the directory service under a public name.

On the client, the RMI Registry is accessed using the lookup() method in the static class Naming. The client provides the lookup() method with a URL to query the registry and the method returns a remote reference to the service object. The URL takes the following form:

rmi://<host_name> [:<name_service_port>] /<service_name>

The host_name is a name on the local area network or a DNS name on the Internet. Specify the name_service_port if the naming service is not running on the default port 1099.

IBM Software Group | Tivoli software

22

Finding RMI Remote Services

• RMI remote services are published in a naming or directory service

• Can use JNDI

• RMI has its own RMI Registry

• Server program creates local object that implements a remote service

• The client program uses the lookup() method to query the registry for the service

Page 435: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-23

• • •••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

RMI System

An RMI system is composed of:

• Interface definitions for the remote services.

• Classes that implement the remote services.

• Stub files: Generate stub class files from the implementation classes using rmic.

• A server to host the remote services: Write code for a remote service host program.

• An RMI Registry or naming service with which clients can find the remote services.

• A class file provider (an HTTP or FTP server).

• A client program that needs the remote services: Develop code for the client program.

IBM Software Group | Tivoli software

23

RMI System

• Interface definitions for the remote services

• Implementations of the remote services

• Stub files

• A server to host the remote services – An RMI Registry or naming service – A class file provider

• A client program to request the remote services

Page 436: Ibm enterprise it and asset management 7.1 java for customization training

10-24 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

HelloRemote Interface

This interface defines all of the remote methods offered by this service. The interface must extend Remote and each method must throw a RemoteException.

IBM Software Group | Tivoli software

24

HelloRemote Interface

import java.rmi.Remote;

import java.rmi.RemoteException;

public interface HelloRemote extends Remote {

public String sayHello(String name) throws RemoteException;

}

Page 437: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-25

• • •••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Hello Class

The Hello class extends the UnicastRemoteObject, which is used for exporting a remote object and getting a stub that communicates with that remote object. When extending UnicastRemoteObject, a constructor must be provided with a call to super() to link into the RMI system.

The Hello class must also implement the HelloRemote interface that extends Remote.

public class Hello extends UnicastRemoteObject implements HelloRemote {

private static String thisHostName = null;

public Hello() throws RemoteException { super(); try { // get the host where this is running thisHostName = InetAddress.getLocalHost().getHostName(); } catch(Exception e) {

e.printStackTrace(); } } public String sayHello(String name) throws RemoteException { return "Hello! " + name + " I am " + thisHostName; }}

IBM Software Group | Tivoli software

25

Hello Classpublic class Hello extends UnicastRemoteObject implements HelloRemote {

public Hello() throws RemoteException {super();

try {thisHostName = InetAddress.getLocalHost().getHostName();

}catch(Exception e) {

e.printStackTrace();}

}public String sayHello(String name) throws RemoteException {

return "Hello! " + name + " I am " + thisHostName;} )

Page 438: Ibm enterprise it and asset management 7.1 java for customization training

10-26 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

RMIServer Class

This is a simple server that hosts a remote RMI service.

public class RMIServer { // set up the computer name private static String hostName = null;

public static void main(String[] args) throws RemoteException, MalformedURLException { Registry reg = null;

// Set the port number int portNumber = Registry.REGISTRY_PORT; // take default 1099 if(args.length > 0) { portNumber = Integer.parseInt(args[0]); }

try { // Get the current host name hostName = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { System.out.println("RMI Server for host:" + hostName + " could not be created"); e.printStackTrace(); System.exit(1); }

IBM Software Group | Tivoli software

26

RMIServer Class

public class RMIServer {private static String hostName = null;public static void main(String[] args) throws RemoteException, MalformedURLException {

Registry reg = null;int portNumber = Registry.REGISTRY_PORT; hostName = InetAddress.getLocalHost().getHostName(); try {reg = LocateRegistry.createRegistry(portNumber);

}catch (ExportException e) {

System.out.println("port:" + portNumber + " already created for registry");}HelloRemote hello = new Hello();String urlString = "rmi://" + hostName + ":" + portNumber + "/" + "Hello";Naming.rebind(urlString.trim(), hello);

} }

Page 439: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-27• • •••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

try { reg = LocateRegistry.createRegistry(portNumber); } catch (ExportException e){ System.out.println("port:" + portNumber + " already created for registry"); }

System.out.println("Registry created on host computer " + hostName + " on port " + portNumber);

// Create an instance of the remote object implementation HelloRemote hello = new Hello();

// create registration name String urlString = "rmi://" + hostName + ":" + portNumber + "/" + "Hello";

// Register the remote object so it // can be accessed from other computers ystem.out.println("Binding:" + "[" + urlString + "]");

Naming.rebind(urlString.trim(), hello);

System.out.println("Remote Object:" + urlString + " ready for remote access"); }}

Page 440: Ibm enterprise it and asset management 7.1 java for customization training

10-28 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009• • • ••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

RMIClient Class

This client invokes a service on the server.

public class RMIClient { private static int portNumber = Registry.REGISTRY_PORT; private static String thisHostName=null; private static String remoteHostName=null; public static void main( String[] args ) throws java.net.UnknownHostException { // get the name of our local computer thisHostName = InetAddress.getLocalHost().getHostName();

if(args.length == 0) { // no hostname given assume local host remoteHostName = thisHostName; } else { if(args.length > 0) { remoteHostName = args[0]; // host name given as argument } if(args.length > 1) { //port number given portNumber = Integer.parseInt(args[1]); } } if(remoteHostName.equalsIgnoreCase("localhost")) {

IBM Software Group | Tivoli software

27

RMIClient Class

public class RMIClient {........ String resName = "rmi://" + remoteHostName + ":" + portNumber + "/" + "Hello";

try {HelloRemote hello = (HelloRemote)Naming.lookup(resName.trim());

// invoke the remote methodString hi = hello.sayHello(thisHostName);

}catch ( Exception e ) {

System.out.println( "Error invoking remote object Hello" );e.printStackTrace();

} } }

Page 441: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-29• • •••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

remoteHostName = thisHostName; } System.out.println("Using host:" + remoteHostName + " port:" + portNumber); String resName = "rmi://" + remoteHostName + ":" + portNumber + "/" + "Hello"; System.out.println("looking for:[" + resName + "]"); try { // Find the object in the remote host // and get a remote reference to it HelloRemote hello = (HelloRemote)Naming.lookup(resName.trim()); // invoke the remote method String hi = hello.sayHello(thisHostName); System.out.println("\n" + remoteHostName + " says: \n " + hi ); } catch ( Exception e ) { System.out.println( "Error invoking remote object Hello" ); e.printStackTrace(); } }}

Page 442: Ibm enterprise it and asset management 7.1 java for customization training

10-30 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009• • • ••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Invoking Remote Service

The output in the slide corresponds to starting the server services and running the client. Even though these programs are running on the local host, the communication is between multiple JVMs using the network stack.

IBM Software Group | Tivoli software

28

Invoking Remote Service

• The registry is created on the host machine• The HelloRemote service is invoked on the host machine• RMI uses the network stack and TCP/IP to communicate

between the client and the server JVMs

Page 443: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-31• • •••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Student Exercise

Open your Student Exercises book and perform the exercises for this unit.

IBM Software Group | Tivoli software

29

Student Exercise

Page 444: Ibm enterprise it and asset management 7.1 java for customization training

10-32 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009• • • ••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Review Questions

1. What is a transient variable?

2. Why does RMI use serialized objects?

Page 445: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-33• • •••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Review answers appear on next page.

Page 446: Ibm enterprise it and asset management 7.1 java for customization training

10-34 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009• • • ••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Review Answers

1. What is a transient variable?

A transient variable is a variable that cannot be serialized.

2. Why does RMI use serialized objects?

The client object is serialized and a copy is sent to the server, so it is not necessary to make more than one call to the client.

Page 447: Ibm enterprise it and asset management 7.1 java for customization training

©Copyright IBM Corp. 2009 IBM Enterprise IT and Asset Management 7.1: Java for Customization 10-35

• • •••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Summary

IBM Software Group | Tivoli software

30

Summary

You should now be able to:Describe the benefits of using serialization

Create an object and serialize its state

Implement Remote Method Invocation (RMI)

Page 448: Ibm enterprise it and asset management 7.1 java for customization training

10-36 IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Unit 10: Serialization and Remote Method InvocationRemote Method Invocation

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

Page 449: Ibm enterprise it and asset management 7.1 java for customization training

• • • ••

I

Tivoli Professional Certification

“As an individual, becoming a Tivoli Certified Professional has helped me to progress further in my career and gain job satisfaction. To the company, it has helped build up the confidence and trust to the customer. At the end of the day, you win, the company wins, and the customer wins.”

Special Offer for Having Taken This CourseNow through 31 January 2010: For having completed this course, you are entitled to a 15% discount on your next exam at any Thomson Prometric testing center worldwide. Use this special promotion code when registering online or by telephone to receive the discount: 15CSWR. (This offer might be withdrawn. Check with the testing center as described later in this section.)

Reasons for Certification• It is a demonstration of value to your customer through increased overall

performance with shorter time cycles to deliver applications.

• Technical certifications assist technical professionals to obtain more visibility to potential customers.

• Differentiate your skills and knowledge from other non-IBM Certified professionals.

Role-based CertificationAll IBM certifications are based on job roles. They focus on a job a person must do with a product, not just the product’s features and functions. The job roles used by Tivoli Professional Certification include:

• IBM Certified Advanced Deployment Professional

• IBM Certified Deployment Professional

• IBM Certified Administrator

• IBM Certified Solution Advisor

• IBM Certified Specialist

• IBM Certified Operator

Page 450: Ibm enterprise it and asset management 7.1 java for customization training

II IBM Enterprise IT and Asset Management 7.1: Java for Customization ©Copyright IBM Corp. 2009

• • • ••

Tivoli Professional Certification

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

When to Attempt a Certification ExamAfter completing this course, you should review the test objectives and sample test on the IBM Certification Web site (URL follows) that correspond with the exam you want to take. Exams are based on real-world and hands-on experience for the specific certification role. As an example, for the Deployment Certifications a general guideline is to play a major role in at least two product deployments, so that you have as much hands-on experience working with the product as possible before you attempt a deployment exam. Exam questions are written by experts in the deployment of this product and most of the material covered is taken from their experience working with the product in real world commercial environments. You will find supplemental readings and other study material on the Web site as well.

Location and CostAll IBM certification exams are available at Thomson Prometric testing centers worldwide. In addition, testing is offered at a discount or for free at many IBM conferences and events, including many Tivoli User Group (TUG) meetings. Exam costs vary in different parts of the world. See the Thomson Prometric Web sites for the exact cost at the testing center you plan to use.

IBM employees receive a special discount if they take an exam using the PRIME tool at any IBM location.

A PRIME proctor is required and not all locations have proctors. For more information and a current list of proctors, see the PRIME URL that follows.

Sources of Additional Information• The Tivoli Certification Program

http://www.ibm.com/certify/ or e-mail at [email protected]

• The Tivoli Certification e-Newsletter (sent out monthly)Subscribe at [email protected]

• Tivoli Certification Study Guideshttp://www.redbooks.ibm.com (search for “certification study guide”)

• Tivoli Support Technical Exchange Callshttp://www.ibm.com/software/sysmgmt/products/support/supp_tech_exch.html

• Tivoli Certification Study GroupsSend an e-mail inquiry to [email protected]

• Thomson Prometric testing centershttp://www.prometric.com

• IBM PRIME testing and proctor information (IBM employees only)http://w3-103.ibm.com/software/xl/portal/viewcontent?type=doc&srcID=XT&docID=P101658X09146A52

Page 451: Ibm enterprise it and asset management 7.1 java for customization training
Page 452: Ibm enterprise it and asset management 7.1 java for customization training

S150-3087-00

C T5

DG

EN

IBM

Printed in Ireland

®