Java must read for everyone

485
Sun Educational Services Java™ Programming Language Java™ Programming Language SL-275-SE6

description

BASIC JAVA FOR EVERYONE.

Transcript of Java must read for everyone

Page 1: Java must read for everyone

Sun

Java™ Programmi

Ja guage

Educational Services

ng Language

va™ Programming Lan

SL-275-SE6

Page 2: Java must read for everyone

Copyrig

This pro lation. No part of this product or document maybe repro

Third-p

Sun, Sun emarks of Sun Microsystems, Inc. in the U.S. andother co

UNIX is

Netscap

The OPE es the pioneering efforts of Xerox in researchingand dev ox to the Xerox Graphical User Interface, whichlicense a

U.S. Gov

RESTRI nd FAR 52.227-19(6/87), or DFAR 252.227-7015(b)(6/95

DOCUM IES, INCLUDING ANY IMPLIED WARRANTYOF MER HE EXTENT THAT SUCH DISCLAIMERS AREHELD T

Export C

ht 2007 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved.

duct or document is protected by copyright and distributed under licenses restricting its use, copying, distribution, and decompiduced in any form by any means without prior written authorization of Sun and its licensors, if any.

arty software, including font technology, is copyrighted and licensed from Sun suppliers.

Microsystems, the Sun Logo, Java, JavaBeans, JavaOS, JDBC, JDK, JVM, J2SE, Jini, and Solaris are trademarks or registered traduntries.

a registered trademark in the U.S. and other countries, exclusively licensed through X/Open Company, Ltd.

e Navigator is a trademark of Netscape Communications Corporation.

N LOOK and Sun Graphical User Interface was developed by Sun Microsystems, Inc. for its users and licensees. Sun acknowledgeloping the concept of visual or graphical user interfaces for the computer industry. Sun holds a non-exclusive license from Xerlso covers Sun’s licensees who implement OPEN LOOK GUIs and otherwise comply with Sun’s written license agreements.

ernment approval might be required when exporting the product.

CTED RIGHTS: Use, duplication, or disclosure by the U.S. Government is subject to restrictions of FAR 52.227-14(g)(2)(6/87) a) and DFAR 227.7202-3(a).

ENTATION IS PROVIDED “AS IS” AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS, AND WARRANTCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO TO BE LEGALLY INVALID.

ommodity Classification Number Assigned: 2 February 2002

Page 3: Java must read for everyone

Copyrig

Ce prod ution, et la décompilation. Aucune partie de ceproduit e Sun et de ses bailleurs de licence, s’il y en a.

Le logic é par des fournisseurs de Sun.

Sun, Sun es marques déposées de Sun Microsystems, Inc.aux Etat

UNIX es

Netscap

L’interfa . Sun reconnaît les efforts de pionniers de Xeroxpour lar n détient une licence non exclusive de Xerox surl’interfa tion graphique OPEN LOOK et qui en outre seconform

L’accord

LA DOC ESSES OU TACITES SONT FORMELLEMENTEXCLU RELATIVE A LA QUALITE MARCHANDE, AL’APTIT

ht 2007 Sun Microsystems Inc., 4150 Network Circle, Santa Clara, California 95054, Etats-Unis. Tous droits réservés.

uit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, la copie, la distribou document ne peut être reproduite sous aucune forme, par quelque moyen que ce soit, sans l’autorisation préalable et écrite d

iel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par un copyright et licenci

Microsystems, the Sun Logo, Java, JavaBeans, JavaOS, JDBC, JDK, JVM, J2SE, Jini, et Solaris sont des marques de fabrique ou ds-Unis et dans d’autres pays.

t une marques déposée aux Etats-Unis et dans d’autres pays et licenciée exclusivement par X/Open Company, Ltd.

e Navigator est une marque de Netscape Communications Corporation aux Etats-Unis et dans d’autres pays.

ces d’utilisation graphique OPEN LOOK et Sun™ a été développée par Sun Microsystems, Inc. pour ses utilisateurs et licenciésecherche et le développement du concept des interfaces d’utilisation visuelle ou graphique pour l’industrie de l’informatique. Suce d’utilisation graphique Xerox, cette licence couvrant également les licenciés de Sun qui mettent en place l’interface d’utilisaent aux licences écrites de Sun.

du gouvernement américain est requis avant l’exportation du produit.

UMENTATION EST FOURNIE “EN L’ETAT” ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET GARANTIES EXPRES, DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITEUDE A UNE UTILISATION PARTICULIERE OU A L’ABSENCE DE CONTREFAÇON.

Page 4: Java must read for everyone

Java™ Programmi ivCopyright 2007 Sun Mi

....................... Preface-xvi

...................................Preface-xvii

....................................Preface-xix

..................................... Preface-xx

....................................Preface-xxi

...................................Preface-xxii

..................................Preface-xxiii

..................................Preface-xxiv....................................Preface-xxv

..................................... 1-1

.................................................. 1-2

.................................................. 1-3

.................................................. 1-4

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

.................................................. 1-8

................................................ 1-11

................................................ 1-12

................................................ 1-13................................................. 1-14................................................ 1-15................................................ 1-16................................................ 1-17................................................ 1-18................................................ 1-19................................................ 1-20

ng Languagecrosystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Course Contents

About This Course ..............................................................Course Goals ..........................................................................................Course Overview ..................................................................................Course Map ............................................................................................Topics Not Covered ..............................................................................How Prepared Are You? ......................................................................Introductions .........................................................................................How to Use the Icons ............................................................................Typographical Conventions and Symbols .......................................

Getting Started ....................................................................Objectives ...............................................................................................Relevance ................................................................................................What Is the Java™ Technology? .........................................................Primary Goals of the Java Technology ..............................................The Java Virtual Machine ....................................................................Garbage Collection ...............................................................................The Java Runtime Environment ..........................................................Operation of the JRE With a Just-In-Time (JIT) Compiler ..............JVM™ Tasks ..........................................................................................The Class Loader ...................................................................................The Bytecode Verifier ...........................................................................A Simple Java Application ...................................................................The TestGreeting Application .........................................................The Greeting Class ..............................................................................Compiling and Running the TestGreeting Program ....................

Page 5: Java must read for everyone

Java™ vCopyrig

................................................ 1-21

................................................ 1-22

................................................ 1-23

..................................... 2-1

.................................................. 2-2

.................................................. 2-3

.................................................. 2-4

.................................................. 2-5

.................................................. 2-6

.................................................. 2-7

.................................................. 2-8

.................................................. 2-9

................................................ 2-10

................................................ 2-11

................................................ 2-12

................................................ 2-14

................................................ 2-15

................................................ 2-16

................................................ 2-17

................................................ 2-18

................................................ 2-19

................................................ 2-20

................................................ 2-21

................................................ 2-22

................................................ 2-23

................................................ 2-24

................................................ 2-25

................................................ 2-26

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Compile-Time Errors ............................................................................Runtime Errors ......................................................................................Java Technology Runtime Environment ...........................................

Object-Oriented Programming ...........................................Objectives ...............................................................................................Relevance ................................................................................................Software Engineering ...........................................................................The Analysis and Design Phase ..........................................................Abstraction .............................................................................................Classes as Blueprints for Objects ........................................................Declaring Java Technology Classes ....................................................Declaring Attributes .............................................................................Declaring Methods ................................................................................Accessing Object Members ..................................................................Information Hiding ...............................................................................Encapsulation ........................................................................................Declaring Constructors ........................................................................The Default Constructor ......................................................................Source File Layout ................................................................................Software Packages ................................................................................The package Statement ........................................................................The import Statement ..........................................................................Directory Layout and Packages ..........................................................Development .........................................................................................Compiling Using the -d Option .........................................................Terminology Recap ...............................................................................Using the Java Technology API Documentation ..............................Java Technology API Documentation ...............................................

Page 6: Java must read for everyone

Java™ viCopyrig

..................................... 3-1

.................................................. 3-2

.................................................. 3-4

.................................................. 3-5................................................... 3-6.................................................. 3-9................................................ 3-10................................................ 3-11................................................ 3-12................................................ 3-13................................................ 3-14................................................ 3-15................................................ 3-17................................................ 3-19................................................ 3-20................................................ 3-21................................................ 3-22................................................ 3-23................................................ 3-24................................................ 3-25................................................ 3-26................................................ 3-27................................................ 3-32................................................ 3-36

..................................... 4-1

.................................................. 4-2

.................................................. 4-4

.................................................. 4-5

.................................................. 4-6

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Identifiers, Keywords, and Types ......................................Objectives ...............................................................................................Relevance ................................................................................................Comments ..............................................................................................Semicolons, Blocks, and White Space ...............................................Identifiers ...............................................................................................Java Programming Language Keywords ..........................................Primitive Types .....................................................................................Logical – boolean .................................................................................Textual – char .......................................................................................Textual – String ...................................................................................Integral – byte, short, int, and long ...............................................Floating Point – float and double ....................................................Variables, Declarations, and Assignments ........................................Java Reference Types ............................................................................Constructing and Initializing Objects ................................................Memory Allocation and Layout ..........................................................Explicit Attribute Initialization ...........................................................Executing the Constructor ...................................................................Assigning a Variable .............................................................................Assigning References ............................................................................Pass-by-Value ........................................................................................The this Reference ...............................................................................Java Programming Language Coding Conventions ........................

Expressions and Flow Control ..........................................Objectives ...............................................................................................Relevance ................................................................................................Variables and Scope ..............................................................................Variable Scope Example .......................................................................

Page 7: Java must read for everyone

Java™ viiCopyrig

.................................................. 4-7

.................................................. 4-8

.................................................. 4-9

................................................ 4-10

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

................................................ 4-12

................................................ 4-13

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

................................................ 4-15

................................................ 4-16................................................. 4-17................................................ 4-18................................................ 4-19................................................ 4-21................................................ 4-24................................................ 4-27................................................ 4-28................................................ 4-29................................................ 4-30................................................ 4-31

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

.................................................. 5-2

.................................................. 5-3

.................................................. 5-4

.................................................. 5-5

.................................................. 5-7

.................................................. 5-9

................................................ 5-10

................................................ 5-12

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Variable Initialization ...........................................................................Initialization Before Use Principle ......................................................Operator Precedence ............................................................................Logical Operators ..................................................................................Bitwise Logical Operators ....................................................................Right-Shift Operators >> and >>> .......................................................Left-Shift Operator << ..........................................................................Shift Operator Examples ......................................................................String Concatenation With + ...............................................................Casting ....................................................................................................Promotion and Casting of Expressions .............................................Simple if, else Statements ..............................................................Complex if, else Statements ..........................................................Switch Statements .................................................................................Looping Statements ..............................................................................Special Loop Flow Control ..................................................................The break Statement ............................................................................The continue Statement .....................................................................Using break Statements with Labels .................................................Using continue Statements with Labels ..........................................

Arrays ...................................................................................Objectives ...............................................................................................Relevance ................................................................................................Declaring Arrays ...................................................................................Creating Arrays .....................................................................................Creating Reference Arrays ...................................................................Initializing Arrays .................................................................................Multidimensional Arrays .....................................................................Array Bounds ........................................................................................

Page 8: Java must read for everyone

Java™ viiiCopyrig

................................................ 5-13

................................................ 5-14

................................................ 5-15

..................................... 6-1

.................................................. 6-2

.................................................. 6-3

.................................................. 6-4

.................................................. 6-7

.................................................. 6-9

................................................ 6-10

................................................ 6-12

................................................ 6-13

................................................ 6-15

................................................ 6-17

................................................ 6-18

................................................ 6-19

................................................ 6-20

................................................ 6-21

................................................ 6-23

................................................ 6-24

................................................ 6-25

................................................ 6-27

................................................ 6-28

................................................ 6-30

................................................ 6-31

................................................ 6-34

................................................ 6-35

................................................ 6-36

................................................ 6-40

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Using the Enhanced for Loop ............................................................Array Resizing .......................................................................................Copying Arrays .....................................................................................

Class Design ........................................................................Objectives ...............................................................................................Relevance ................................................................................................Subclassing .............................................................................................Single Inheritance ..................................................................................Access Control .......................................................................................Overriding Methods .............................................................................Overridden Methods Cannot Be Less Accessible .............................Invoking Overridden Methods ...........................................................Polymorphism .......................................................................................Virtual Method Invocation ..................................................................Heterogeneous Collections ..................................................................Polymorphic Arguments .....................................................................The instanceof Operator ...................................................................Casting Objects ......................................................................................Overloading Methods ..........................................................................Methods Using Variable Arguments .................................................Overloading Constructors ...................................................................Constructors Are Not Inherited ..........................................................Invoking Parent Class Constructors ...................................................Constructing and Initializing Objects: A Slight Reprise ..................Constructor and Initialization Examples ...........................................The Object Class ..................................................................................The equals Method ..............................................................................An equals Example .............................................................................The toString Method .........................................................................

Page 9: Java must read for everyone

Java™ ixCopyrig

................................................. 6-41................................................ 6-43

..................................... 7-1

.................................................. 7-2

.................................................. 7-3

.................................................. 7-4

.................................................. 7-5

.................................................. 7-7

................................................ 7-10

................................................ 7-12

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

................................................ 7-14

................................................ 7-15

................................................ 7-19

................................................ 7-23

................................................ 7-25................................................. 7-27................................................ 7-31................................................ 7-34................................................ 7-35................................................ 7-42................................................ 7-44

..................................... 8-1

.................................................. 8-2

.................................................. 8-3................................................... 8-4.................................................. 8-5.................................................. 8-6

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Wrapper Classes ...................................................................................Autoboxing of Primitive Types ...........................................................

Advanced Class Features ..................................................Objectives ...............................................................................................Relevance ................................................................................................The static Keyword ...........................................................................Class Attributes .....................................................................................Class Methods .......................................................................................Static Initializers ....................................................................................The final Keyword .............................................................................Final Variables .......................................................................................Blank Final Variables ............................................................................Old-Style Enumerated Type Idiom ....................................................The New Enumerated Type ................................................................Advanced Enumerated Types .............................................................Static Imports .........................................................................................Abstract Classes ....................................................................................The Solution ...........................................................................................Interfaces ................................................................................................The Flyer Example ................................................................................Multiple Interface Example .................................................................Uses of Interfaces ..................................................................................

Exceptions and Assertions ................................................Objectives ...............................................................................................Relevance ................................................................................................Exceptions and Assertions ..................................................................Exceptions ..............................................................................................Exception Example ...............................................................................

Page 10: Java must read for everyone

Java™ xCopyrig

.................................................. 8-7

................................................ 8-10

................................................ 8-11

................................................ 8-12

................................................ 8-13

................................................ 8-14

................................................ 8-15

................................................ 8-17

................................................ 8-18

................................................ 8-20

................................................ 8-21

................................................ 8-22

................................................ 8-23................................................. 8-24................................................ 8-25

..................................... 9-1

.................................................. 9-2

.................................................. 9-3

.................................................. 9-7

.................................................. 9-8

.................................................. 9-9

................................................ 9-10

................................................ 9-12

................................................ 9-13

................................................ 9-14

................................................ 9-16

................................................ 9-20................................................. 9-21................................................. 9-25

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The try-catch Statement ...................................................................Call Stack Mechanism ..........................................................................The finally Clause .............................................................................Exception Categories ............................................................................Common Exceptions .............................................................................The Handle or Declare Rule ................................................................Method Overriding and Exceptions ...................................................Creating Your Own Exceptions ..........................................................Handling a User-Defined Exception ..................................................Assertions ...............................................................................................Recommended Uses of Assertions .....................................................Internal Invariants .................................................................................Control Flow Invariants .......................................................................Postconditions and Class Invariants .................................................Controlling Runtime Evaluation of Assertions ................................

Collections and Generics Framework ...............................Objectives ...............................................................................................The Collections API ..............................................................................A List Example ....................................................................................The Map Interface ...................................................................................The Map Interface API ...........................................................................A Map Example ......................................................................................Legacy Collection Classes ....................................................................Ordering Collections ............................................................................The Comparable Interface ...................................................................Example of the Comparable Interface ...............................................The Comparator Interface ...................................................................Example of the Comparator Interface ..............................................Generics .................................................................................................

Page 11: Java must read for everyone

Java™ xiCopyrig

................................................ 9-27

................................................ 9-28

................................................ 9-29

................................................ 9-31

................................................ 9-32

................................................ 9-33

................................................ 9-34

................................................ 9-35

................................................ 9-36

................................................ 9-37

................................................ 9-38

................................... 10-1

................................................ 10-2

................................................ 10-3

................................................ 10-5

................................................ 10-6

................................................ 10-9

.............................................. 10-10

.............................................. 10-11

.............................................. 10-12

.............................................. 10-13

.............................................. 10-14

.............................................. 10-15

.............................................. 10-16

.............................................. 10-17

.............................................. 10-19............................................... 10-21.............................................. 10-22.............................................. 10-24

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Generic Set Example ............................................................................Generic Map Example ..........................................................................Generics: Examining Type Parameters ..............................................Wild Card Type Parameters ................................................................The Type-Safety Guarantee .................................................................The Invariance Challenge ....................................................................The Covariance Response ....................................................................Generics: Refactoring Existing Non-Generic Code ..........................Iterators ...................................................................................................Generic Iterator Interfaces ...................................................................The Enhanced for Loop ......................................................................

I/O Fundamentals ................................................................Objectives ...............................................................................................Command-Line Arguments ................................................................System Properties ..................................................................................The Properties Class .........................................................................I/O Stream Fundamentals ...................................................................Fundamental Stream Classes ..............................................................Data Within Streams .............................................................................The InputStream Methods .................................................................The OutputStream Methods ...............................................................The Reader Methods ............................................................................The Writer Methods ............................................................................Node Streams .........................................................................................A Simple Example .................................................................................Buffered Streams ...................................................................................I/O Stream Chaining ...........................................................................Processing Streams ...............................................................................The InputStream Class Hierarchy ....................................................

Page 12: Java must read for everyone

Java™ xiiCopyrig

.............................................. 10-25............................................ 10-26

.............................................. 10-30

.............................................. 10-32

.............................................. 10-34

.............................................. 10-35

................................... 11-1

................................................ 11-2

................................................ 11-3

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

................................................ 11-5

................................................ 11-7

................................................ 11-8

................................................ 11-9

.............................................. 11-10

.............................................. 11-11

.............................................. 11-13

.............................................. 11-14

.............................................. 11-15

.............................................. 11-16

................................... 12-1

................................................ 12-2

................................................ 12-3

................................................ 12-4

................................................ 12-5

................................................ 12-6

................................................ 12-7

................................................ 12-9

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The OutputStream Class Hierarchy ..................................................The ObjectInputStream and The ObjectOutputStream ClassesThe SerializeDate Class ...................................................................The DeSerializeDate Class ..............................................................The Reader Class Hierarchy ...............................................................The Writer Class Hierarchy ...............................................................

Console I/O and File I/O ......................................................Objectives ...............................................................................................Console I/O ...........................................................................................Writing to Standard Output ................................................................Reading From Standard Input ............................................................Simple Formatted Output ....................................................................Simple Formatted Input .......................................................................Files and File I/O ..................................................................................Creating a New File Object ...............................................................The File Tests and Utilities ................................................................File Stream I/O ......................................................................................File Input Example ................................................................................Printing a File .........................................................................................File Output Example .............................................................................

Building Java GUIs Using the Swing API .........................Objectives ...............................................................................................What Are the Java Foundation Classes (JFC)? ..................................What Is Swing? ......................................................................................Swing Architecture ...............................................................................Swing Packages .....................................................................................Examining the Composition of a Java Technology GUI .................Swing Containers ..................................................................................

Page 13: Java must read for everyone

Java™ xiiiCopyrig

.............................................. 12-10

.............................................. 12-11

.............................................. 12-12

.............................................. 12-13

.............................................. 12-14

.............................................. 12-15

.............................................. 12-16

.............................................. 12-17

.............................................. 12-18

.............................................. 12-19

.............................................. 12-21

.............................................. 12-22

.............................................. 12-24

.............................................. 12-25

.............................................. 12-27

.............................................. 12-29

.............................................. 12-30

.............................................. 12-31

.............................................. 12-34

................................... 13-1

................................................ 13-2

................................................ 13-3

................................................ 13-4

................................................ 13-6

................................................ 13-8

................................................ 13-9

.............................................. 13-13

.............................................. 13-17

.............................................. 13-18

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Top-Level Containers ...........................................................................Swing Components ...............................................................................Swing Component Hierarchy .............................................................Text Components ..................................................................................Swing Component Properties .............................................................Common Component Properties ........................................................Component-Specific Properties ..........................................................Layout Managers ..................................................................................The BorderLayout Manager .............................................................BorderLayout Example .......................................................................The FlowLayout Manager ..................................................................FlowLayout Example ...........................................................................The BoxLayout Manager .....................................................................The CardLayout Manager ...................................................................GridLayout Example ...........................................................................The GridBagLayout Manager ............................................................GUI Construction ..................................................................................Programmatic Construction ................................................................Key Methods ..........................................................................................

Handling GUI-Generated Events ........................................Objectives ...............................................................................................What Is an Event? .................................................................................Delegation Model ..................................................................................A Listener Example ...............................................................................Event Categories ...................................................................................Method Categories and Interfaces ......................................................Complex Example .................................................................................Multiple Listeners .................................................................................Event Adapters ......................................................................................

Page 14: Java must read for everyone

Java™ xivCopyrig

............................................... 13-19

............................................... 13-21

................................... 14-1

................................................ 14-2

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

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

................................................ 14-5

................................................ 14-6

................................................ 14-8

.............................................. 14-10

.............................................. 14-12

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

................................................ 15-2

................................................ 15-3

................................................ 15-4

................................................ 15-5

................................................ 15-7

................................................ 15-8

................................................ 15-9

.............................................. 15-10

.............................................. 15-12

.............................................. 15-13

.............................................. 15-14

.............................................. 15-15

.............................................. 15-16

.............................................. 15-17

.............................................. 15-20

.............................................. 15-21

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Event Handling Using Inner Classes ................................................Event Handling Using Anonymous Classes ....................................

GUI-Based Applications .....................................................Objectives ...............................................................................................Relevance ................................................................................................How to Create a Menu .........................................................................Creating a JMenuBar .............................................................................Creating a JMenu ...................................................................................Creating a JMenuItem ..........................................................................Creating a JCheckBoxMenuItem .........................................................Controlling Visual Aspects ..................................................................

Threads ................................................................................Objectives ...............................................................................................Relevance ................................................................................................Threads ...................................................................................................Creating the Thread ..............................................................................Starting the Thread ...............................................................................Thread Scheduling ................................................................................Thread Scheduling Example ...............................................................Terminating a Thread ...........................................................................Basic Control of Threads ......................................................................The join Method ..................................................................................Other Ways to Create Threads ............................................................Selecting a Way to Create Threads .....................................................Using the synchronized Keyword ...................................................The Object Lock Flag ............................................................................Releasing the Lock Flag ........................................................................Using synchronized – Putting It Together ......................................

Page 15: Java must read for everyone

Java™ xvCopyrig

.............................................. 15-23

.............................................. 15-25

.............................................. 15-26

.............................................. 15-27

.............................................. 15-28

.............................................. 15-30

.............................................. 15-31

.............................................. 15-33

.............................................. 15-35

.............................................. 15-36

.............................................. 15-37

.............................................. 15-38

.............................................. 15-39

................................... 16-1

................................................ 16-2

................................................ 16-3

................................................ 16-4

................................................ 16-6

................................................ 16-7

................................................ 16-8

.............................................. 16-11

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Thread State Diagram With Synchronization ...................................Deadlock .................................................................................................Thread Interaction – wait and notify ..............................................Thread Interaction .................................................................................Thread State Diagram With wait and notify ................................Monitor Model for Synchronization ..................................................The Producer Class ..............................................................................The Consumer Class ..............................................................................The SyncStack Class ............................................................................The pop Method ....................................................................................The push Method ..................................................................................The SyncTest Class ..............................................................................The SyncTest Class ..............................................................................

Networking ...........................................................................Objectives ...............................................................................................Relevance ................................................................................................Networking ............................................................................................Networking With Java Technology ....................................................Java Networking Model .......................................................................Minimal TCP/IP Server .......................................................................Minimal TCP/IP Client ........................................................................

Page 16: Java must read for everyone

Sun

Java™ Programmi

Educational Services

ng Language

Preface

About This Course

Page 17: Java must read for everyone

Java™ Preface, slide xvii of xxviiCopyrig

Th d skills to:

hat leverage theuage, such asrphismrom the

ressionsructs

sing exception

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Course Goals

is course provides you with knowledge an

• Create Java™ technology applications tobject-oriented features of the Java langencapsulation, inheritance, and polymo

• Execute a Java technology application fcommand-line

• Use Java technology data types and exp• Use Java technology flow control const• Use arrays and other data collections• Implement error-handling techniques u

handling

Page 18: Java must read for everyone

Java™ Preface, slide xviii of xxviiCopyrig

nterface (GUI)ents: panels,s

nality to read

rotocol/ommunicates

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Course Goals

• Create an event-driven graphical user iby using Java technology GUI componbuttons, labels, text fields, and text area

• Implement input/output (I/O) functiofrom and write to data and text files

• Create multithreaded programs• Create a simple Transmission Control P

Internet Protocol (TCP/IP) client that cthrough sockets

Page 19: Java must read for everyone

Java™ Preface, slide xix of xxviiCopyrig

Th

nguage to the Java

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Course Overview

is course describes the following areas:

• The syntax of the Java programming la• Object-oriented concepts as they apply

programming language• GUI programming• Multithreading• Networking

Page 20: Java must read for everyone

Sun Educational Services

Course Map

The Java Programming Language Basics

More Object-Oriented Programming

Exceptions, Collections, and I/O

Developing Graphical User Interfaces

Advanced Java Programming

Getting StartedObject-Oriented

Programming

Identifiers,

Keywords, and

Types

Arrays

Class DesignAdvanced

Class Features

Collections and

Console I/O and

File I/O

GUI Event

Handling

GUI-Based

Applications

I/O

Threads Networking

Expressions

and Flow Control

Exceptions

and Assertions Generics Framework Fundamentals

Java™ Programming Language About This Course, xx of xxviiCopyright Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Page 21: Java must read for everyone

Java™ Preface, slide xxi of xxviiCopyrig

overed inlysis and Design

red in SL-110: Language

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Topics Not Covered

• Object-oriented analysis and design – COO-226: Object-Oriented Application AnaUsing UML

• General programming concepts – CoveFundamentals of the Java™ Programming

Page 22: Java must read for everyone

Java™ Preface, slide xxii of xxviiCopyrig

Bef completedSL g Language, orhav

or C++t editorser, such as

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

How Prepared Are You?

ore attending this course, you should have-110: Fundamentals of the Java™ Programmin

e:

• Created and compiled programs with C• Created and edited text files using a tex• Used a World Wide Web (WWW) brow

Netscape Navigator™

Page 23: Java must read for everyone

Java™ Preface, slide xxiii of xxviiCopyrig

in this course

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Introductions

• Name• Company affiliation• Title, function, and job responsibility• Experience related to topics presented • Reasons for enrolling in this course• Expectations for this course

Page 24: Java must read for everyone

Java™ Preface, slide xxiv of xxviiCopyrig

?

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

How to Use the Icons

Additional resources

Discussion

Note

Caution

Visual Aid

!

Page 25: Java must read for everyone

Java™ Preface, slide xxv of xxviiCopyrig

T ymbols

ands, files,mmingtput.d numbers thating code that is

and command-a real name or

esent variablesudent as part of

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

ypographical Conventions and S

• Courier is used for the names of commdirectories, programming code, prograconstructs, and on-screen computer ou

• Courier bold is used for characters anyou type, and for each line of programmreferenced in a textual description.

• Courier italics is used for variablesline place holders that are replaced withvalue.

• Courier italics bold is used to reprwhose values are to be entered by the stan activity.

Page 26: Java must read for everyone

Java™ Preface, slide xxvi of xxviiCopyrig

T ymbols

w words or

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

ypographical Conventions and S

• Palatino italics is used for book titles, neterms, or words that are emphasized.

Page 27: Java must read for everyone

Java™ Preface, slide xxvii of xxviiCopyrig

Jav e followingadd

ethods, and

es unless an.rations,e.g System

soft Windows

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Additional Conventions

a programming language examples use thitional conventions:

• Courier is used for the class names, mkeywords.

• Methods are not followed by parenthesformal or actual parameter list is show

• Line breaks occur where there are sepaconjunctions, or white space in the cod

• If a command on the Solaris™ Operatin(Solaris OS) is different from the Microplatform, both commands are shown.

Page 28: Java must read for everyone

Sun

Java™ Programmi

Educational Services

ng Language

Module 1

Getting Started

Page 29: Java must read for everyone

Java™ Module 1, slide 2 of 23Copyrig

ologyechnology

l Machine

a platform that

ne” and “JVM”platform.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Describe the key features of Java techn• Write, compile, and run a simple Java t

application• Describe the function of the Java Virtua

(JVM™)• Define garbage collection• List the three tasks performed by the Jav

handle code security

NOTE: The terms “Java Virtual Machimean a Virtual Machine for the Java™

Page 30: Java must read for everyone

Java™ Module 1, slide 3 of 23Copyrig

mplete programs for

g language? improve on

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Relevance

• Is the Java programming language a colanguage or is it useful only for writingthe Web?

• Why do you need another programmin• How does the Java technology platform

other language platforms?

Page 31: Java must read for everyone

Java™ Module 1, slide 4 of 23Copyrig

gy?

d applications.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

What Is the Java™ Technolo

• Java technology is:• A programming language• A development environment• An application environment• A deployment environment

• It is similar in syntax to C++.• It is used for developing both applets an

Page 32: Java must read for everyone

Java™ Module 1, slide 5 of 23Copyrig

ology

uages

and clear coder:

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Primary Goals of the Java Techn

• Provides an easy-to-use language by:• Avoiding many pitfalls of other lang• Being object-oriented• Enabling users to create streamlined

• Provides an interpreted environment fo• Improved speed of development• Code portability

Page 33: Java must read for everyone

Java™ Module 1, slide 6 of 23Copyrig

ology

ead of activitye time they are

ally duringate sources

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Primary Goals of the Java Techn

• Enables users to run more than one thr• Loads classes dynamically; that is, at th

actually needed• Supports changing programs dynamic

runtime by loading classes from dispar• Furnishes better security

Page 34: Java must read for everyone

Java™ Module 1, slide 7 of 23Copyrig

ology

Th

1.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Primary Goals of the Java Techn

e following features fulfill these goals:

• The Java Virtual Machine (JVM™)1

• Garbage collection• The Java Runtime Environment (JRE)• JVM tool interface

The terms "Java Virtual Machine" and "JVM" mean a Virtual Machine for the Java platform

Page 35: Java must read for everyone

Java™ Module 1, slide 8 of 23Copyrig

ons

revelopment tool

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Java Virtual Machine

• Provides hardware platform specificati• Reads compiled byte codes that are

platform-independent• Is implemented as software or hardwa• Is implemented in a Java technology de

or a Web browser

Page 36: Java must read for everyone

Java™ Module 1, slide 9 of 23Copyrig

JVM

[CPU])

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Java Virtual Machine

provides definitions for the:

• Instruction set (central processing unit • Register set• Class file format• Stack• Garbage-collected heap• Memory area• Fatal error reporting• High-precision timing support

Page 37: Java must read for everyone

Java™ Module 1, slide 10 of 23Copyrig

hen the code is

y Suncompliant class

environments.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Java Virtual Machine

• The majority of type checking is done wcompiled.

• Implementation of the JVM approved bMicrosystems must be able to run any file.

• The JVM executes on multiple operating

Page 38: Java must read for everyone

Java™ Module 1, slide 11 of 23Copyrig

ded should be

rogrammer’s

des alocation.aracteristics:ger needed

plementations

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Garbage Collection

• Allocated memory that is no longer needeallocated.

• In other languages, deallocation is the presponsibility.

• The Java programming language provisystem-level thread to track memory al

• Garbage collection has the following ch• Checks for and frees memory no lon• Is done automatically• Can vary dramatically across JVM im

Page 39: Java must read for everyone

Java™ Module 1, slide 12 of 23Copyrig

ent

Th s follows:

ser

deer

ter

e

are

e

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Java Runtime Environm

e Java application environment performs aCompile

TestGreeting.java

TestGreeting.class

Load from

Clasload

Bytecoverifi

Interpre

Runtim

Hardw

Runtim

javac

java

hard disk,network,or othersource

Page 40: Java must read for everyone

Java™ Module 1, slide 13 of 23Copyrig

O In-Time

e

codeenerator

JIT

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

peration of the JRE With a Just-(JIT) Compiler

Compile

TestGreeting.java

TestGreeting.class

Classloader

Bytecodeverifier

Interpreter

Runtime

Hardwar

Runtime

javac

java

g

Load fromhard disk,network,or othersource

Page 41: Java must read for everyone

Java™ Module 1, slide 14 of 23Copyrig

Th

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

JVM™ Tasks

e JVM performs three main tasks:

• Loads code• Verifies code• Executes code

Page 42: Java must read for everyone

Java™ Module 1, slide 15 of 23Copyrig

ution of a

in separate

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Class Loader

• Loads all classes necessary for the execprogram

• Maintains classes of the local file systemnamespaces

• Prevents spoofing

Page 43: Java must read for everyone

Java™ Module 1, slide 16 of 23Copyrig

En

ion.rity.flows or

code are

sion of integers

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Bytecode Verifier

sures that:

• The code adheres to the JVM specificat• The code does not violate system integ• The code causes no operand stack over

underflows.• The parameter types for all operational

correct.• No illegal data conversions (the conver

to pointers) have occurred.

Page 44: Java must read for everyone

Java™ Module 1, slide 17 of 23Copyrig

Th

123456789

Th

12345

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

A Simple Java Application

e TestGreeting.java Application

//// Sample "Hello World" application//public class TestGreeting{public static void main (String[] args) {

Greeting hello = new Greeting(); hello.greet(); }}

e Greeting.java Class

public class Greeting {public void greet() {

System.out.println(“hi”); }}

Page 45: Java must read for everyone

Java™ Module 1, slide 18 of 23Copyrig

ion

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The TestGreetingApplicat

• Comment lines• Class declaration• The main method• Method body

Page 46: Java must read for everyone

Java™ Module 1, slide 19 of 23Copyrig

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The GreetingClass

• Class declaration• The greet method

Page 47: Java must read for everyone

Java™ Module 1, slide 20 of 23Copyrig

C reeting

atically.ing command:

rrors.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

ompiling and Running the TestGProgram

• Compile TestGreeting.java:javac TestGreeting.java

• The Greeting.java is compiled autom• Run the application by using the follow

java TestGreeting

• Locate common compile and runtime e

Page 48: Java must read for everyone

Java™ Module 1, slide 21 of 23Copyrig

symbolang.String)ream

estGreetingd

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Compile-Time Errors

• javac: Command not found

• Greeting.java:4: cannot resolvesymbol : method printl (java.llocation: class java.io.PrintStSystem.out.printl("hi");

^

• TestGreet.java:4: Public class Tmust be defined in a file calle"TestGreeting.java".

Page 49: Java must read for everyone

Java™ Module 1, slide 22 of 23Copyrig

in

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Runtime Errors

• Can’t find class TestGreeting

• Exception in thread "main"java.lang.NoSuchMethodError: ma

Page 50: Java must read for everyone

Java™ Module 1, slide 23 of 23Copyrig

nment

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Java Technology Runtime Enviro

Com

pile

TestGreeting.java

TestGreeting.class

Run

time

Greeting.class

Greeting.java

JVM

UNIX® DOS JavaOS™

JVMJVM

javac

java

Also compiles

Also loads

Can run on multiple platforms

Page 51: Java must read for everyone

Sun

Java™ Programmi

ming

Educational Services

ng Language

Module 2

Object-Oriented Program

Page 52: Java must read for everyone

Java™ Module 2, slide 2 of 26Copyrig

ncapsulation,

ogy application

onstructor, and

public assulation

ogramming

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Define modeling concepts: abstraction, eand packages

• Discuss why you can reuse Java technolcode

• Define class, member, attribute, method, cpackage

• Use the access modifiers private andappropriate for the guidelines of encap

• Invoke a method on a particular object• Use the Java technology application pr

interface (API) online documentation

Page 53: Java must read for everyone

Java™ Module 2, slide 3 of 26Copyrig

e analysis and

and code reuse?ing language

language?

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Relevance

• What is your understanding of softwardesign?

• What is your understanding of design• What features does the Java programm

possess that make it an object-oriented• Define the term object-oriented.

Page 54: Java must read for everyone

Java™ Module 2, slide 4 of 26Copyrig

0s–Up)

oft Windows

penLook

JDBC™

Java

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Software Engineering

Machine Code (Late 1940s–Up)

High-Level Languages (1950s–Up) Operating Systems (196

Libraries / Functional APIs (1960s–Early 1980s)

Object-Oriented Languages (1980s–Up)

Toolkits / Frameworks / Object APIs (1990s–Up)

Fortran LISP C UNIX MicrosMacOS

NASTRAN X-Windows

COBOL

TCP/IP ISAM O

SELF Smalltalk Common Lisp Object System Eiffel

AWT / J.F.C./Swing Jini™ JavaBeans™Java 2 SDK

C++

OS/360

Page 55: Java must read for everyone

Java™ Module 2, slide 5 of 26Copyrig

se

ds to do:tors and

t:ractionsstemimplify the

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Analysis and Design Pha

• Analysis describes what the system neeModeling the real-world, including acactivities, objects, and behaviors

• Design describes how the system does i• Modeling the relationships and inte

between objects and actors in the sy• Finding useful abstractions to help s

problem or solution

Page 56: Java must read for everyone

Java™ Module 2, slide 6 of 26Copyrig

e used in many

tes and

of objects thats can be usedbehavior

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Abstraction

• Functions – Write an algorithm once to bsituations

• Objects – Group a related set of attribubehaviors into a class

• Frameworks and APIs – Large groups support a complex activity; Frameworkas is or be modified to extend the basic

Page 57: Java must read for everyone

Java™ Module 2, slide 7 of 26Copyrig

ects

s a device fromructed.n object:object includes.each object

e key features:

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Classes as Blueprints for Obj

• In manufacturing, a blueprint describewhich many physical devices are const

• In software, a class is a description of a• A class describes the data that each • A class describes the behaviors that

exhibits.• In Java technology, classes support thre

of object-oriented programming (OOP)• Encapsulation• Inheritance• Polymorphism

Page 58: Java must read for everyone

Java™ Module 2, slide 8 of 26Copyrig

sses

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Declaring Java Technology Cla

• Basic syntax of a Java class:<modifier>* class <class_name> {

<attribute_declaration>*<constructor_declaration>*<method_declaration>*

}

• Example:1 public class Vehicle {2 private double maxLoad;3 public void setMaxLoad(double value) {4 maxLoad = value;5 }6 }

Page 59: Java must read for everyone

Java™ Module 2, slide 9 of 26Copyrig

e>];

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Declaring Attributes

• Basic syntax of an attribute:<modifier>* <type> <name> [ = <initial_valu

• Examples:1 public class Foo {2 private int x;3 private float y = 10000.0F;4 private String name = "Bates Motel";5 }

Page 60: Java must read for everyone

Java™ Module 2, slide 10 of 26Copyrig

t>* ) {

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Declaring Methods

• Basic syntax of a method:<modifier>* <return_type> <name> ( <argumen

<statement>*}

• Examples:1 public class Dog {2 private int weight;3 public int getWeight() {4 return weight;5 }6 public void setWeight(int newWeight) {7 if ( newWeight > 0 ) {8 weight = newWeight;9 }10 }11 }

Page 61: Java must read for everyone

Java™ Module 2, slide 11 of 26Copyrig

s

r>

ncluding

s public

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Accessing Object Member

• The dot notation is: <object>.<membe• This is used to access object members, i

attributes and methods.• Examples of dot notation are:

d.setWeight(42);d.weight = 42; // only permissible if weight i

Page 62: Java must read for everyone

Java™ Module 2, slide 12 of 26Copyrig

Th

+

+

+

t access to to a MyDate

ound

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Information Hiding

e problem:

MyDate

day : int

month : int

year : int

Client code has direcinternal data (d refersobject):

d.day = 32;// invalid day

d.month = 2; d.day = 30;// plausible but wrong

d.day = d.day + 1;// no check for wrap ar

Page 63: Java must read for everyone

Java™ Module 2, slide 13 of 26Copyrig

Th setters andnal data:

false

e if wrap around

+

+

+

+

+

+

-d

-m

-y

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Information Hiding

e solution:Client code must usegetters to access inter

MyDate d = new MyDate();

d.setDay(32);// invalid day, returns

d.setMonth(2);d.setDay(30);// plausible but wrong,// setDay returns false

d.setDay(d.getDay() + 1);// this will return fals// needs to occur

setDay(int) : boolean

setYear(int) : boolean

setMonth(int) : boolean

getDay() : int

getMonth() : int

getYear() : int

MyDate

ay : int

onth : int

ear : int

Verify days in month

Page 64: Java must read for everyone

Java™ Module 2, slide 14 of 26Copyrig

lasscess data

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Encapsulation

• Hides the implementation details of a c• Forces the user to use an interface to ac• Makes the code more maintainable

+setDay(int) : boolean

+setYear(int) : boolean

+setMonth(int) : boolean

+getDay() : int

+getMonth() : int

+getYear() : int

MyDate

-date : long

-isDayValid(int) : boolean

Page 65: Java must read for everyone

Java™ Module 2, slide 15 of 26Copyrig

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Declaring Constructors

• Basic syntax of a constructor:[<modifier>] <class_name> ( <argument>* ) {<statement>*

}

• Example:1 public class Dog {23 private int weight;45 public Dog() {6 weight = 42;7 }8 }

Page 66: Java must read for everyone

Java™ Module 2, slide 16 of 26Copyrig

in every class.ructors, thecally:umentstyinstances withnstructor.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Default Constructor

• There is always at least one constructor• If the writer does not supply any const

default constructor is present automati• The default constructor takes no arg• The default constructor body is emp

• The default enables you to create objectnew Xxx()without having to write a co

Page 67: Java must read for everyone

Java™ Module 2, slide 17 of 26Copyrig

ort.java file

{...}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Source File Layout

• Basic syntax of a Java source file is:[<package_declaration>]<import_declaration>*<class_declaration>+

• For example, the VehicleCapacityRepis:1 package shipping.reports;23 import shipping.domain.*;4 import java.util.List;5 import java.io.*;67 public class VehicleCapacityReport {8 private List vehicles;9 public void generateReport(Writer output)10 }

Page 68: Java must read for everyone

Java™ Module 2, slide 18 of 26Copyrig

ystems.ackages.

icle

RiverBarge

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Software Packages

• Packages help manage large software s• Packages can contain classes and sub-p

Veh

Truck

Company Owns 0..*

shipping

domaingui

reports

Page 69: Java must read for everyone

Java™ Module 2, slide 19 of 26Copyrig

is:

eginning of the

ce file. is placed into

d separated by

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The packageStatement

• Basic syntax of the package statement package <top_pkg_name>[.<sub_pkg_name>]*;

• Examples of the statement are:package shipping.gui.reportscreens;

• Specify the package declaration at the bsource file.

• Only one package declaration per sour• If no package is declared, then the class

the default package.• Package names must be hierarchical an

dots.

Page 70: Java must read for everyone

Java™ Module 2, slide 20 of 26Copyrig

:name>;

g:

ses

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The importStatement

• Basic syntax of the import statement isimport <pkg_name>[.<sub_pkg_name>]*.<class_ORimport <pkg_name>[.<sub_pkg_name>]*.*;

• Examples of the statement are:import java.util.List;import java.io.*;import shipping.gui.reportscreens.*;

• The import statement does the followin• Precedes all class declarations• Tells the compiler where to find clas

Page 71: Java must read for everyone

Java™ Module 2, slide 21 of 26Copyrig

es

containing the

packages.

.class

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Directory Layout and Packag

• Packages are stored in the directory treepackage name.

• An example is the shipping applicationshipping/

domain/

gui/

reports/

Vehicle.classRiverBarge.classTruck.class

VehicleCapacityReport

Company.class

Page 72: Java must read for everyone

Java™ Module 2, slide 22 of 26Copyrig

J

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

DevelopmentavaProjects/

ShippingPrj/

src/

docs/

shipping/

domain/gui/reports/

classes/

shipping/

domain/gui/reports/

Page 73: Java must read for everyone

Java™ Module 2, slide 23 of 26Copyrig

on

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Compiling Using the -dOpti

cd JavaProjects/ShippingPrj/srcjavac -d ../classes shipping/domain/*.java

Page 74: Java must read for everyone

Java™ Module 2, slide 24 of 26Copyrig

run-time object

;iable, and data

bject;roceduresed to initialize

b-packages

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Terminology Recap

• Class – The source-code blueprint for a• Object – An instance of a class;

also known as instance• Attribute – A data element of an object

also known as data member, instance varfield

• Method – A behavioral element of an oalso known as algorithm, function, and p

• Constructor – A method-like construct ua new object

• Package – A grouping of classes and su

Page 75: Java must read for everyone

Java™ Module 2, slide 25 of 26Copyrig

PI

HTML) files

s hyperlinks tot package.rarchy, avariables, a list

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Using the Java Technology ADocumentation

• A set of Hypertext Markup Language (provides information about the API.

• A frame describes a package and containinformation describing each class in tha

• A class document includes the class hiedescription of the class, a list of memberof constructors, and so on.

Page 76: Java must read for everyone

Sun Educational Services

Java Technology APIDocumentation

Java™ Programming Language Module 2, slide 26 of 26Copyright Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Page 77: Java must read for everyone

Sun

Java™ Programmi

Id Types

Educational Services

ng Language

Module 3

entifiers, Keywords, and

Page 78: Java must read for everyone

Java™ Module 3, slide 2 of 37Copyrig

identifiers

xtual typeseference variable

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Use comments in a source program• Distinguish between valid and invalid • Recognize Java technology keywords• List the eight primitive types• Define literal values for numeric and te• Define the terms primitive variable and r

Page 79: Java must read for everyone

Java™ Module 3, slide 3 of 37Copyrig

variableiables of class

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Declare variables of class type• Construct an object using new• Describe default initialization• Describe the significance of a reference• State the consequences of assigning var

type

Page 80: Java must read for everyone

Java™ Module 3, slide 4 of 37Copyrig

n variableswith object

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Relevance

• Do you know the primitive Java types?• Can you describe the difference betwee

holding primitive values as compared references?

Page 81: Java must read for everyone

Java™ Module 3, slide 5 of 37Copyrig

Th ava technologypro

// c

/* c* o*/

/** * */

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Comments

e three permissible styles of comment in a Jgram are:

omment on one line

omment on oner more lines

documentation commentcan also span one or more lines

Page 82: Java must read for everyone

Java™ Module 3, slide 6 of 37Copyrig

Space

terminated by

nd by opening

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Semicolons, Blocks, and White

• A statement is one or more lines of codea semicolon (;):totals = a + b + c

+ d + e + f;

• A block is a collection of statements bouand closing braces:{ x = y + 1; y = x + 1;}

Page 83: Java must read for everyone

Java™ Module 3, slide 7 of 37Copyrig

Space

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Semicolons, Blocks, and White

• A class definition uses a special block:public class MyDate { private int day; private int month; private int year;}

• You can nest block statements.while ( i < large ) {a = a + i;// nested blockif ( a == max ) {b = b + a;a = 0;

}i = i + 1;

}

Page 84: Java must read for everyone

Java™ Module 3, slide 8 of 37Copyrig

Space

in a Java

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Semicolons, Blocks, and White

• Any amount of white space is permittedprogram.For example:{int x;x=23*54;}

is equivalent to:{int x;

x = 23 * 54;}

Page 85: Java must read for everyone

Java™ Module 3, slide 9 of 37Copyrig

Ide

methodcore (_), or

m length

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Identifiers

ntifiers have the following characteristics:

• Are names given to a variable, class, or• Can start with a Unicode letter, unders

dollar sign ($)• Are case-sensitive and have no maximu• Examples:

identifieruserNameuser_name_sys_var1$change

Page 86: Java must read for everyone

Java™ Module 3, slide 10 of 37Copyrig

ywords

Re e

abs switch

ass synchronized

boo this

bre d throw

byt throws

cas transient

cat try

cha void

cla volatile

con while

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Java Programming Language Ke

served literal words: null, true, and fals

tract continue for new

ert default goto package

lean do if private

ak double implements protecte

e else import public

e enum instanceof return

ch extends int short

r final interface static

ss finally long strictfp

st float native super

Page 87: Java must read for everyone

Java™ Module 3, slide 11 of 37Copyrig

Th t primitivetyp

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Primitive Types

e Java programming language defines eighes:

• Logical – boolean• Textual – char• Integral – byte, short, int, and long

• Floating – double and float

Page 88: Java must read for everyone

Java™ Module 3, slide 12 of 37Copyrig

Th acteristics:

, true and

type and assigns

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Logical – boolean

e boolean primitive has the following char

• The boolean data type has two literalsfalse.

• For example, the statement:boolean truth = true;

declares the variable truth as booleanit a value of true.

Page 89: Java must read for everyone

Java™ Module 3, slide 13 of 37Copyrig

Th characteristics:

quotes (’ ’)

is replaced with

letter phi [Φ].

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Textual – char

e textual char primitive has the following

• Represents a 16-bit Unicode character• Must have its literal enclosed in single • Uses the following notations:

'a' The letter a

'\t' The tab character

'\u????' A specific Unicode character, ????, exactly four hexadecimal digits .For example, ’\u03A6’ is the Greek

Page 90: Java must read for everyone

Java™ Module 3, slide 14 of 37Copyrig

Th aracteristics:

s (" ")

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Textual – String

e textual String type has the following ch

• Is not a primitive data type; it is a class• Has its literal enclosed in double quote

"The quick brown fox jumps over the lazy dog."

• Can be used as follows:String greeting = "Good Morning !! \n";String errorMessage = "Record Not Found !";

Page 91: Java must read for everyone

Java™ Module 3, slide 15 of 37Copyrig

long

Th aracteristics:

mal, octal, or

ng.

e.

al value.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Integral – byte, short, int, and

e integral primitives have the following ch

• Integral primates use three forms: Decihexadecimal

• Literals have a default type of int.

• Literals with the suffix L or l are of type lo

2 The decimal form for the integer 2.

077 The leading 0 indicates an octal valu

0xBAAC The leading 0x indicates a hexadecim

Page 92: Java must read for everyone

Java™ Module 3, slide 16 of 37Copyrig

long

ranges:

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Integral – byte, short, int, and

• Integral data types have the following

Integer Length Name or Type Range

8 bits byte -27 to 27-1

16 bits short -215 to 215 -1

32 bits int -231 to 231 -1

64 bits long -263 to 263 -1

Page 93: Java must read for everyone

Java™ Module 3, slide 17 of 37Copyrig

uble

Th ngcha

ecimal point or

ouble)

dant D

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Floating Point – floatand do

e floating point primitives have the followiracteristics:

• Floating-point literal includes either a done of the following:• E or e (add exponential value)• F or f (float)• D or d (double)

3.14 A simple floating-point value (a d

6.02E23 A large floating-point value

2.718F A simple float size value

123.4E+306D A large double value with redun

Page 94: Java must read for everyone

Java™ Module 3, slide 18 of 37Copyrig

uble

owing sizes:

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Floating Point – floatand do

• Literals have a default type of double.• Floating-point data types have the foll

Float Length Name or Type

32 bits float

64 bits double

Page 95: Java must read for everyone

Sun Educational Services

Variables, Declarations, andAssignments

1 public class Assign {2 public static void main (String args []) {3 // declare integer variables4 int x, y;5 // declare and assign floating point6 float z = 3.414f;7 // declare and assign double8 double w = 3.1415;9 // declare and assign boolean10 boolean truth = true;11 // declare character variable12 char c;13 // declare String variable14 String str;15 // declare and assign String variable16 String str1 = "bye";17 // assign value to char variable18 c = 'A';19 // assign value to String variable20 str = "Hi out there!";21 // assign values to int variables22 x = 6;23 y = 1000;24 }25 }

Java™ Programming Language Module 3, slide 19 of 37Copyright Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Page 96: Java must read for everyone

Java™ Module 3, slide 20 of 37Copyrig

pes all others

n object.

r) { ... }

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Java Reference Types

• In Java technology, beyond primitive tyare reference types.

• A reference variable contains a handle to a• For example:

1 public class MyDate {2 private int day = 1;3 private int month = 1;4 private int year = 2000;5 public MyDate(int day, int month, int yea6 public String toString() { ... }7 }

1 public class TestMyDate {2 public static void main(String[] args) {3 MyDate today = new MyDate(22, 7, 1964);4 }5 }

Page 97: Java must read for everyone

Java™ Module 3, slide 21 of 37Copyrig

jects

ing actions:

rformed.

the new

o a variable.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Constructing and Initializing Ob

• Calling new Xyz() performs the followa. Memory is allocated for the object.b. Explicit attribute initialization is pec. A constructor is executed.d. The object reference is returned by

operator.• The reference to the object is assigned t• An example is:

MyDate my_birth = new MyDate(22, 7, 1964);

Page 98: Java must read for everyone

Java™ Module 3, slide 22 of 37Copyrig

ut

a reference:

for MyDate:

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Memory Allocation and Layo

• A declaration allocates storage only forMyDate my_birth = new MyDate(22, 7, 1964);

• Use the new operator to allocate space MyDate my_birth = new MyDate(22, 7, 1964);

my_birth ????

my_birth ????

day

month

year

0

0

0

Page 99: Java must read for everyone

Java™ Module 3, slide 23 of 37Copyrig

n

ttribute

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Explicit Attribute Initializatio

• Initialize the attributes as follows:MyDate my_birth = new MyDate(22, 7, 1964);

• The default values are taken from the adeclaration in the class.

my_birth ????

day

month

year

1

1

2000

Page 100: Java must read for everyone

Java™ Module 3, slide 24 of 37Copyrig

llows:

r, the first

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Executing the Constructor

• Execute the matching constructor as foMyDate my_birth = new MyDate(22, 7, 1964);

• In the case of an overloaded constructoconstructor can call another.

my_birth ????

day

month

year

22

7

1964

Page 101: Java must read for everyone

Java™ Module 3, slide 25 of 37Copyrig

eference

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Assigning a Variable

• Assign the newly created object to the rvariable as follows:MyDate my_birth = new MyDate(22, 7, 1964);

my_birth 0x01abcdef

day

month

year

22

7

1964

Page 102: Java must read for everyone

Java™ Module 3, slide 26 of 37Copyrig

nt to two

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Assigning References

• Two variables refer to a single object:1 int x = 7;2 int y = x;3 MyDate s = new MyDate(22, 7, 1964);4 MyDate t = s;

• Reassignment makes two variables poiobjects:5 t = new MyDate(22, 12, 1964);

x 7

y 7

s 0x01234567

t 0x01234567

22 7 1964

x 7

y 7

s 0x01234567

t 0x12345678

22 7 1964

22 12 1964

Page 103: Java must read for everyone

Java™ Module 3, slide 27 of 37Copyrig

ogramminglue. argument to areference to the

d in the callede is never

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Pass-by-Value

• In a single virtual machine, the Java prlanguage only passes arguments by va

• When an object instance is passed as anmethod, the value of the argument is aobject.

• The contents of the object can be changemethod, but the original object referencchanged.

Page 104: Java must read for everyone

Java™ Module 3, slide 28 of 37Copyrig

123456789101112

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Pass-by-Value

public class PassTest {

// Methods to change the current values public static void changeInt(int value) { value = 55; } public static void changeObjectRef(MyDate ref) { ref = new MyDate(1, 1, 2000); } public static void changeObjectAttr(MyDate ref){ ref.setDay(4); }

Page 105: Java must read for everyone

Java™ Module 3, slide 29 of 37Copyrig

1314151617181920212223

Th

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Pass-by-Value

public static void main(String args[]) { MyDate date; int val;

// Assign the int val = 11; // Try to change it changeInt(val); // What is the current value? System.out.println("Int value is: " + val);

e result of this output is:

Int value is: 11

Page 106: Java must read for everyone

Java™ Module 3, slide 30 of 37Copyrig

24252627282930

Th

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Pass-by-Value

// Assign the date date = new MyDate(22, 7, 1964); // Try to change it changeObjectRef(date); // What is the current value?

System.out.println("MyDate: " + date);

e result of this output is:

MyDate: 22-7-1964

Page 107: Java must read for everyone

Java™ Module 3, slide 31 of 37Copyrig

3132333435363738

Th

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Pass-by-Value

// Now change the day attribute // through the object reference changeObjectAttr(date); // What is the current value?

System.out.println("MyDate: " + date);}

}

e result of this output is:

MyDate: 4-7-1964

Page 108: Java must read for everyone

Java™ Module 3, slide 32 of 37Copyrig

He

variables and

er to another

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The thisReference

re are a few uses of the this keyword:

• To resolve ambiguity between instanceparameters

• To pass the current object as a parametmethod or constructor

Page 109: Java must read for everyone

Java™ Module 3, slide 33 of 37Copyrig

123456789101112131415

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The thisReference

public class MyDate { private int day = 1; private int month = 1; private int year = 2000;

public MyDate(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } public MyDate(MyDate date) { this.day = date.day; this.month = date.month; this.year = date.year; }

Page 110: Java must read for everyone

Java™ Module 3, slide 34 of 37Copyrig

1617181920212223242526

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The thisReference

public MyDate addDays(int moreDays) { MyDate newDate = new MyDate(this); newDate.day = newDate.day + moreDays; // Not Yet Implemented: wrap around code... return newDate; }public String toString() {

return "" + day + "-" + month + "-" + year; }}

Page 111: Java must read for everyone

Java™ Module 3, slide 35 of 37Copyrig

12345678

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The thisReference

public class TestMyDate { public static void main(String[] args) { MyDate my_birth = new MyDate(22, 7, 1964); MyDate the_next_week = my_birth.addDays(7);

System.out.println(the_next_week); }}

Page 112: Java must read for everyone

Java™ Module 3, slide 36 of 37Copyrig

oding

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Java Programming Language CConventions

• Packages:com.example.domain;

• Classes, interfaces, and enum types:SavingsAccount

• Methods:getAccount()

• Variables:currentCustomer

• Constants:HEAD_COUNT

Page 113: Java must read for everyone

Java™ Module 3, slide 37 of 37Copyrig

oding

on.

ss members.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Java Programming Language CConventions

• Control structures:if ( condition ) {statement1;

} else {statement2;

}

• Spacing:• Use one statement per line.• Use two or four spaces for indentati

• Comments:• Use // to comment inline code.• Use /** documentation */ for cla

Page 114: Java must read for everyone

Sun

Java™ Programmi

ontrol

Educational Services

ng Language

Module 4

Expressions and Flow C

Page 115: Java must read for everyone

Java™ Module 4, slide 2 of 31Copyrig

variablesablesence before

are operatorsssignments of

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Distinguish between instance and local• Describe how to initialize instance vari• Identify and correct a Possible refer

assignment compiler error• Recognize, describe, and use Java softw• Distinguish between legal and illegal a

primitive types

Page 116: Java must read for everyone

Java™ Module 4, slide 3 of 31Copyrig

requirements

d required casts

structions andnue as flow

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Identify boolean expressions and theirin control constructs

• Recognize assignment compatibility anin fundamental types

• Use if, switch, for, while, and do conthe labelled forms of break and conticontrol structures in a program

Page 117: Java must read for everyone

Java™ Module 4, slide 4 of 31Copyrig

ogrammers?th the same

ed in otherguages use to

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Relevance

• What types of variables are useful to pr• Can multiple classes have variables wi

name and, if so, what is their scope?• What types of control structures are us

languages? What methods do these lancontrol flow?

Page 118: Java must read for everyone

Java™ Module 4, slide 5 of 31Copyrig

Lo

od and arek variableshod is executedd

Va :

ation.atically.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Variables and Scope

cal variables are:

• Variables that are defined inside a methcalled local, automatic, temporary, or stac

• Variables that are created when the metare destroyed when the method is exite

riable initialization comprises the following

• Local variables require explicit initializ• Instance variables are initialized autom

Page 119: Java must read for everyone

Java™ Module 4, slide 6 of 31Copyrig

pub p

p

} p

}}

pubp

}}

Heap Memory

ScopeExample

i 1

ck

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Variable Scope Examplelic class ScopeExample {rivate int i=1;

ublic void firstMethod() { int i=4, j=5;

this.i = i + j; secondMethod(7);

ublic void secondMethod(int i) {int j=8; this.i = i + j;

lic class TestScoping {ublic static void main(String[] args) {ScopeExample scope = new ScopeExample();

scope.firstMethod();

main

firstMethod

i

j

secondMethod

i

j

this

this

scope

4

5

7

8

Execution Sta

Page 120: Java must read for everyone

Java™ Module 4, slide 7 of 31Copyrig

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Variable Initialization

Variable Value

byte 0

short 0

int 0

long 0L

float 0.0F

double 0.0D

char '\u0000'

boolean false

All reference types null

Page 121: Java must read for everyone

Java™ Module 4, slide 8 of 31Copyrig

iple

Th ave beenini

javaTest en initialized 1 er

345678910 ation11

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Initialization Before Use Princ

e compiler will verify that local variables htialized before used.

c TestInitBeforeUse.javaInitBeforeUse.java:10: variable y might not have bez = y + x; // Possible use before initialization ^ror

public void doComputation() { int x = (int)(Math.random() * 100); int y; int z; if (x > 50) { y = 9; } z = y + x; // Possible use before initializ }

Page 122: Java must read for everyone

Java™ Module 4, slide 9 of 31Copyrig

Op ssociative++ to L* to R+ to R<< to R< to R== to R& to R^ to R| to R&& to R|| to R<b to L= * to L

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Operator Precedence

erators A-- + unary - unary ~ ! (<data_type>) R/ % L- L>> >>> L> <= >= instanceof L!= L

LLLLL

oolean_expr> ? <expr1> : <expr2> R= /= %= += -= <<= >>= >>>= &= ^= |= R

Page 123: Java must read for everyone

Java™ Module 4, slide 10 of 31Copyrig

e:

:

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Logical Operators

• The boolean operators are:! – NOT & – AND| – OR ^ – XOR

• The short-circuit boolean operators ar&& – AND || – OR

• You can use these operators as followsMyDate d = reservation.getDepartureDate();if ( (d != null) && (d.day > 31) {// do something with d

}

Page 124: Java must read for everyone

Java™ Module 4, slide 11 of 31Copyrig

0 1

1 1

0 1

0 1

1 1

1 1

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Bitwise Logical Operators

• The integer bitwise operators are:~ – Complement & – AND^ – XOR | – OR

• Byte-sized examples include:

0 0 01 1 1 1 1

1 1 10 0 0 0 0

~

0 0 01 1 1

0 0 01 1 1

0 0 0 0 1 1

&

0 0 01 1 1

0 0 01 1 1|

0 01 1 1 1

0 0 0 01 1 1 1

0 0 01 1 1 1 1

0 0 0 00 11 1

^

Page 125: Java must read for everyone

Java™ Module 4, slide 12 of 31Copyrig

>>>

rator:

ft.rator:. shift.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Right-Shift Operators >>and

• Arithmetic or signed right shift (>>) ope• Examples are:

128 >> 1 returns 128/21 = 64256 >> 4 returns 256/24 = 16-256 >> 4 returns -256/24 = -16

• The sign bit is copied during the shi• Logical or unsigned right-shift (>>>) ope

• This operator is used for bit patterns• The sign bit is not copied during the

Page 126: Java must read for everyone

Java™ Module 4, slide 13 of 31Copyrig

s:

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Left-Shift Operator <<

• Left-shift (<<) operator works as follow128 << 1 returns 128 * 21 = 25616 << 2 returns 16 * 22 = 64

Page 127: Java must read for everyone

Java™ Module 4, slide 14 of 31Copyrig

0 10 0 1 1

1 1

0

00

11

1111

0

00

13

-13

135

-135

13

-13

1111 00011 1

1 1001

0 0111 0000 0

10 1 10

0 0111 0000 0

1111 00011 1

0 00 0 0

0 00 0 0

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Shift Operator Examples

1

1

0

0

00 0 000 0 000 0 000 0 0

11 1 1 11 1 111 1 1 11 1 1 11 1 1

00 0 01357 =

-1357 =

57 >> 5 =

57 >> 5 =

7 >>> 5 =

7 >>> 5 =

57 << 5 =

57 << 5 =

11 1 1 111 1 1 11 1 1 11 1 1

1111 00011 1 1 11 1 111 1 11 1 1

000 0 000 0 000 0 000 0 0

0 0111 0000 0 000 0 000 0 000 0

0 00 0 0

11 1 11

000 0 000 0 000 0 000 0 00 00 0 0

11 1 1 111 1 1 11 1 1 11 1 10 00 0 0

Page 128: Java must read for everyone

Java™ Module 4, slide 15 of 31Copyrig

+

.bjects

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

String Concatenation With

• The + operator works as follows:• Performs String concatenation• Produces a new String:

String salutation = "Dr.";String name = "Pete" + " " + "Seymour";String title = salutation + " " + name;

• One argument must be a String object• Non-strings are converted to String o

automatically.

Page 129: Java must read for everyone

Java™ Module 4, slide 16 of 31Copyrig

nment, theent with a cast. requires an

a cast

a cast

ger literal

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Casting

• If information might be lost in an assigprogrammer must confirm the assignm

• The assignment between long and intexplicit cast.long bigValue = 99L;int squashed = bigValue; // Wrong, needsint squashed = (int) bigValue; // OK

int squashed = 99L; // Wrong, needsint squashed = (int) 99L; // OK, but...int squashed = 99; // default inte

Page 130: Java must read for everyone

Java™ Module 4, slide 17 of 31Copyrig

ssions

o a longer form

e variable type bits) as the

l

egal

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Promotion and Casting of Expre

• Variables are promoted automatically t(such as int to long).

• Expression is assignment-compatible if this at least as large (the same number ofexpression type.long bigval = 6; // 6 is an int type, OKint smallval = 99L; // 99L is a long, illega

double z = 12.414F; // 12.414F is float, OKfloat z1 = 12.414; // 12.414 is double, ill

Page 131: Java must read for everyone

Java™ Module 4, slide 18 of 31Copyrig

ts

Th

if <

Ex

if (Sy

or

if (Sy

}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Simple if, elseStatemen

e if statement syntax:

( <boolean_expression> )statement_or_block>

ample:

x < 10 )stem.out.println("Are you finished yet?");

(recommended):

x < 10 ) {stem.out.println("Are you finished yet?");

Page 132: Java must read for everyone

Java™ Module 4, slide 19 of 31Copyrig

nts

Th

if <

els<

Ex

if (Sy

} elSy

}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Complex if, elseStateme

e if-else statement syntax:

( <boolean_expression> )statement_or_block>estatement_or_block>

ample:

x < 10 ) {stem.out.println("Are you finished yet?");se {stem.out.println("Keep working...");

Page 133: Java must read for everyone

Java™ Module 4, slide 20 of 31Copyrig

nts

Th

if <

els<

Ex

int sif (Sy ;

} elSy

} elSy

}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Complex if, elseStateme

e if-else-if statement syntax:

( <boolean_expression> )statement_or_block>e if ( <boolean_expression> )statement_or_block>

ample:

count = getCount(); // a method defined in the clascount < 0) {stem.out.println("Error: count value is negative.")se if (count > getMaxCount()) {stem.out.println("Error: count value is too big.");se {stem.out.println("There will be " + count +

" people for lunch today.");

Page 134: Java must read for everyone

Java™ Module 4, slide 21 of 31Copyrig

Th

swic

c

d

}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Switch Statements

e switch statement syntax:

tch ( <expression> ) {ase <constant1>:<statement_or_block>*[break;]

ase <constant2>:<statement_or_block>*[break;]

efault:<statement_or_block>*[break;]

Page 135: Java must read for everyone

Java™ Module 4, slide 22 of 31Copyrig

A s

switca

ca

de

}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Switch Statements

witch statement example:

ch ( carModel ) {se DELUXE:addAirConditioning();addRadio();addWheels();addEngine();break;se STANDARD:addRadio();addWheels();addEngine();break;fault:addWheels();addEngine();

Page 136: Java must read for everyone

Java™ Module 4, slide 23 of 31Copyrig

Th vious example:

switca

ca

de

}

Wi falls througheac

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Switch Statements

is switch statement is equivalent to the pre

ch ( carModel ) {se DELUXE:addAirConditioning();se STANDARD:addRadio();fault:addWheels();addEngine();

thout the break statements, the execution h subsequent case clause.

Page 137: Java must read for everyone

Java™ Module 4, slide 24 of 31Copyrig

Th

for<

Ex

for Sy

or

for Sy

}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Looping Statements

e for loop:

( <init_expr>; <test_expr>; <alter_expr> )statement_or_block>

ample:

( int i = 0; i < 10; i++ )stem.out.println(i + " squared is " + (i*i));

(recommended):

( int i = 0; i < 10; i++ ) {stem.out.println(i + " squared is " + (i*i));

Page 138: Java must read for everyone

Java™ Module 4, slide 25 of 31Copyrig

Th

whi<

Ex

int whilSyi+

}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Looping Statements

e while loop:

le ( <test_expr> )statement_or_block>

ample:

i = 0;e ( i < 10 ) {stem.out.println(i + " squared is " + (i*i));+;

Page 139: Java must read for everyone

Java™ Module 4, slide 26 of 31Copyrig

Th

do<

whi

Ex

intdo {Syi+

} wh

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Looping Statements

e do/while loop:

statement_or_block>le ( <test_expr> );

ample:

i = 0;

stem.out.println(i + " squared is " + (i*i));+;ile ( i < 10 );

Page 140: Java must read for everyone

Java™ Module 4, slide 27 of 31Copyrig

l

dand, where

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Special Loop Flow Contro

• The break [<label>]; command• The continue [<label>]; comman• The <label> : <statement> comm

<statement> should be a loop

Page 141: Java must read for everyone

Java™ Module 4, slide 28 of 31Copyrig

1234567

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The breakStatement

do {statement;if ( condition ) {break;

}statement;

} while ( test_expr );

Page 142: Java must read for everyone

Java™ Module 4, slide 29 of 31Copyrig

1234567

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The continueStatement

do {statement;if ( condition ) {continue;

}statement;

} while ( test_expr );

Page 143: Java must read for everyone

Java™ Module 4, slide 30 of 31Copyrig

abels

123456789101112

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Using breakStatements with L

outer:do {statement1;do {statement2;if ( condition ) {break outer;

}statement3;

} while ( test_expr );statement4;

} while ( test_expr );

Page 144: Java must read for everyone

Java™ Module 4, slide 31 of 31Copyrig

U Labels

123456789101112

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

sing continueStatements with

test:do {statement1;do {statement2;if ( condition ) {continue test;

}statement3;

} while ( test_expr );statement4;

} while ( test_expr );

Page 145: Java must read for everyone

Sun

Java™ Programmi

Educational Services

ng Language

Module 5

Arrays

Page 146: Java must read for everyone

Java™ Module 5, slide 2 of 15Copyrig

class, or array

nitializedf an arrayn array

ne array to

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Declare and create arrays of primitive, types

• Explain why elements of an array are i• Explain how to initialize the elements o• Determine the number of elements in a• Create a multidimensional array• Write code to copy array values from o

another

Page 147: Java must read for everyone

Java™ Module 5, slide 3 of 15Copyrig

Wh

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Relevance

at is the purpose of an array?

Page 148: Java must read for everyone

Java™ Module 5, slide 4 of 15Copyrig

es:

new.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Declaring Arrays

• Group data objects of the same type.• Declare arrays of primitive or class typ

char s[];Point p[];

char[] s;Point[] p;

• Create space for a reference.• An array is an object; it is created with

Page 149: Java must read for everyone

Java™ Module 5, slide 5 of 15Copyrig

Us .

For

12345678910

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Creating Arrays

e the new keyword to create an array object

example, a primitive (char) array:

public char[] createArray() {char[] s;

s = new char[26];for ( int i=0; i<26; i++ ) {s[i] = (char) (’A’ + i);

}

return s;}

Page 150: Java must read for everyone

Java™ Module 5, slide 6 of 15Copyrig

C imitives

ory

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

reating an Array of Character Pr

main

createArray s

this

char[]

A

Execution Stack

Heap Mem

B

C

D

Z

Page 151: Java must read for everyone

Java™ Module 5, slide 7 of 15Copyrig

An

12345678910

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Creating Reference Arrays

other example, an object array:

public Point[] createArray() {Point[] p;

p = new Point[10];for ( int i=0; i<10; i++ ) {p[i] = new Point(i, i+1);

}

return p;}

Page 152: Java must read for everyone

Java™ Module 5, slide 8 of 15Copyrig

C imitives

nt

0

1

Point

x

y

1

2

int

2

3

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

reating an Array of Character PrWith PointObjects

main

createArray p

this

Point[]

Execution Stack

Heap Memory

Poi

x

y

Po

x

y

Page 153: Java must read for everyone

Java™ Module 5, slide 9 of 15Copyrig

Strnamnamnamnam

{

MyDdatdatdatdat

{, 7, 1964), 1, 2000),, 12, 1964)

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Initializing Arrays

• Initialize an array element.• Create an array with initial values.ing[] names;es = new String[3];es[0] = "Georgianna";es[1] = "Jen";es[2] = "Simon";

String[] names = "Georgianna","Jen","Simon"

};

ate[] dates;es = new MyDate[3];es[0] = new MyDate(22, 7, 1964);es[1] = new MyDate(1, 1, 2000);es[2] = new MyDate(22, 12, 1964);

MyDate[] dates = new MyDate(22new MyDate(1,new MyDate(22

};

Page 154: Java must read for everyone

Java™ Module 5, slide 10 of 15Copyrig

Ar

int[twoDtwoD

int[

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Multidimensional Arrays

rays of arrays:

][] twoDim = new int[4][];im[0] = new int[5];im[1] = new int[5];

][] twoDim = new int[][4]; // illegal

Page 155: Java must read for everyone

Java™ Module 5, slide 11 of 15Copyrig

h:

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Multidimensional Arrays

• Non-rectangular arrays of arrays:twoDim[0] = new int[2];twoDim[1] = new int[4];twoDim[2] = new int[6];twoDim[3] = new int[8];

• Array of four arrays of five integers eacint[][] twoDim = new int[4][5];

Page 156: Java must read for everyone

Java™ Module 5, slide 12 of 15Copyrig

All

publfo

}}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Array Bounds

array subscripts begin at 0:

ic void printElements(int[] list) {r (int i = 0; i < list.length; i++) {System.out.println(list[i]);

Page 157: Java must read for everyone

Java™ Module 5, slide 13 of 15Copyrig

op

Jav rsion 5.0int over arrays:

publfo

}}

Th in list do.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Using the Enhanced forLo

a 2 Platform, Standard Edition (J2SE™) veroduced an enhanced for loop for iterating

ic void printElements(int[] list) {r ( int element : list ) {System.out.println(element);

e for loop can be read as for each element

Page 158: Java must read for everyone

Java™ Module 5, slide 14 of 15Copyrig

e to refer to an

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Array Resizing

• You cannot resize an array.• You can use the same reference variabl

entirely new array, such as:int[] myArray = new int[6];myArray = new int[10];

Page 159: Java must read for everyone

Java™ Module 5, slide 15 of 15Copyrig

Th rays is:

123456789 h);

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Copying Arrays

e System.arraycopy() method to copy ar

//original arrayint[] myArray = { 1, 2, 3, 4, 5, 6 };

// new larger arrayint[] hold = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

// copy all of the myArray array to the hold// array, starting with the 0th indexSystem.arraycopy(myArray, 0, hold, 0, myArray.lengt

Page 160: Java must read for everyone

Sun

Java™ Programmi

Educational Services

ng Language

Module 6

Class Design

Page 161: Java must read for everyone

Java™ Module 6, slide 2 of 43Copyrig

ding, overriding,

nd the default

d method

on and

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Define inheritance, polymorphism, overloaand virtual method invocation

• Use the access modifiers protected a(package-friendly)

• Describe the concepts of constructor anoverloading

• Describe the complete object constructiinitialization operation

Page 162: Java must read for everyone

Java™ Module 6, slide 3 of 43Copyrig

Ho pport objectinh

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Relevance

w does the Java programming language sueritance?

Page 163: Java must read for everyone

Java™ Module 6, slide 4 of 43Copyrig

Th

";

ls() {...}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Subclassing

e Employee class is shown here.

public class Employee { public String name = " public double salary; public Date birthDate;

public String getDetai}

Employee

+name : String = ""

+salary : double

+birthDate : Date

+getDetails() : String

Page 164: Java must read for everyone

Java™ Module 6, slide 5 of 43Copyrig

Th

";

nt;

ls() {...}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Subclassing

e Manager class is shown here.

public class Manager { public String name = " public double salary; public Date birthDate; public String departme

public String getDetai}

Manager

+name : String = ""

+salary : double

+birthDate : Date

+department : String

+getDetails() : String

Page 165: Java must read for everyone

Java™ Module 6, slide 6 of 43Copyrig

C Manager

";

ls() {...}

ends Employee {nt;

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

lass Diagrams for EmployeeandUsing Inheritance

public class Employee { public String name = " public double salary; public Date birthDate;

public String getDetai}

public class Manager ext public String departme}

Manager

+department : String

Employee

+name : String = ""

+salary : double

+birthDate : Date

+getDetails() : String

Page 166: Java must read for everyone

Java™ Module 6, slide 7 of 43Copyrig

ss, it is called

le inheritance

s>] {

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Single Inheritance

• When a class inherits from only one clasingle inheritance.

• Interfaces provide the benefits of multipwithout drawbacks.

• Syntax of a Java class is as follows:<modifier> class <name> [extends <superclas<declaration>*

}

Page 167: Java must read for everyone

Java™ Module 6, slide 8 of 43Copyrig

cretary

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Single Inheritance

Manager

+department : String = ""

Employee

+name : String = ""

+salary : double

+birthDate : Date

Director

+carAllowance : double

Engineer Se

+getDetails() : String

+increaseAllowance()

Page 168: Java must read for everyone

Java™ Module 6, slide 9 of 43Copyrig

Ac s are listed here.

Mo ass Universe

pri

def

pro

pub Yes

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Access Control

cess modifiers on class member declaration

difier Same Class Same Package Subcl

vate Yes

ault Yes Yes

tected Yes Yes Yes

lic Yes Yes Yes

Page 169: Java must read for everyone

Java™ Module 6, slide 10 of 43Copyrig

ed from a

fferent but with the

1.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Overriding Methods

• A subclass can modify behavior inheritparent class.

• A subclass can create a method with difunctionality than the parent’s methodsame:• Name• Return type1

• Argument list

In J2SE version 5, the return type can be a subclass of the overridden return type.

Page 170: Java must read for everyone

Java™ Module 6, slide 11 of 43Copyrig

12345678910

123456789

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Overriding Methods

public class Employee {protected String name;protected double salary;protected Date birthDate;

public String getDetails() {return “Name: “ + name + “\n” +

“Salary: “ + salary;}

}

public class Manager extends Employee {protected String department;

public String getDetails() {return “Name: “ + name + “\n” +

“Salary: “ + salary + "\n" +“Manager of: “ + department;

}}

Page 171: Java must read for everyone

Java™ Module 6, slide 12 of 43Copyrig

Less

123

123

12345678

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Overridden Methods Cannot BeAccessible

public class Parent {public void doSomething() {}

}

public class Child extends Parent {private void doSomething() {} // illegal

}

public class UseBoth {public void doOtherThing() {Parent p1 = new Parent();Parent p2 = new Child();p1.doSomething();p2.doSomething();

}}

Page 172: Java must read for everyone

Java™ Module 6, slide 13 of 43Copyrig

ds

A s ethod using thesup

refer to its

the members ofthods.the superclass;

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Invoking Overridden Metho

ubclass method may invoke a superclass mer keyword:

• The keyword super is used in a class tosuperclass.

• The keyword super is used to refer tosuperclass, both data attributes and me

• Behavior invoked does not have to be init can be further up in the hierarchy.

Page 173: Java must read for everyone

Java™ Module 6, slide 14 of 43Copyrig

ds

123456789

123456789

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Invoking Overridden Metho

public class Employee {private String name;private double salary;private Date birthDate;

public String getDetails() {return "Name: " + name + "\nSalary: " + salary;

}}

public class Manager extends Employee {private String department;

public String getDetails() {// call parent methodreturn super.getDetails()

+ “\nDepartment: " + department;}

}

Page 174: Java must read for everyone

Java™ Module 6, slide 15 of 43Copyrig

y differentas access to

of different

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Polymorphism

• Polymorphism is the ability to have manforms; for example, the Manager class hmethods from Employee class.

• An object has only one form.• A reference variable can refer to objects

forms.

Page 175: Java must read for everyone

Java™ Module 6, slide 16 of 43Copyrig

Empl

// e.de// t// e

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Polymorphism

oyee e = new Manager(); // legal

illegal attempt to assign Manager attributepartment = "Sales";he variable is declared as an Employee type,ven though the Manager object has that attribute

Page 176: Java must read for everyone

Java™ Module 6, slide 17 of 43Copyrig

d as follows:

vocations have

of the declared has a method

based on theManager classtails method.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Virtual Method Invocation

• Virtual method invocation is performeEmployee e = new Manager();e.getDetails();

• Compile-time type and runtime type inthe following characteristics:• The method name must be a member

variable type; in this case Employeecalled getDetails.

• The method implementation used isruntime object’s type; in this case thehas an implementation of the getDe

Page 177: Java must read for everyone

Java™ Module 6, slide 18 of 43Copyrig

s

ss type areple:

ss types aremple:

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Heterogeneous Collection

• Collections of objects with the same clacalled homogeneous collections. For examMyDate[] dates = new MyDate[2];dates[0] = new MyDate(22, 12, 1964);dates[1] = new MyDate(22, 7, 1964);

• Collections of objects with different clacalled heterogeneous collections. For exaEmployee [] staff = new Employee[1024];staff[0] = new Manager();staff[1] = new Employee();staff[2] = new Engineer();

Page 178: Java must read for everyone

Java™ Module 6, slide 19 of 43Copyrig

Bec ing is valid:

publpu

}}

// MTaxSManTaxR

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Polymorphic Arguments

ause a Manager is an Employee, the follow

ic class TaxService {blic TaxRate findTaxRate(Employee e) {// calculate the employee’s tax rate

eanwhile, elsewhere in the application classervice taxSvc = new TaxService();ager m = new Manager();ate t = taxSvc.findTaxRate(m);

Page 179: Java must read for everyone

Java™ Module 6, slide 20 of 43Copyrig

r

publpublpubl----

publif

}

}

}}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The instanceofOperato

ic class Employee extends Objectic class Manager extends Employeeic class Engineer extends Employee------------------------------------

ic void doSomething(Employee e) { ( e instanceof Manager ) {// Process a Managerelse if ( e instanceof Engineer ) {// Process an Engineerelse {// Process any other type of Employee

Page 180: Java must read for everyone

Java™ Module 6, slide 21 of 43Copyrig

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Casting Objects

public void doSomething(Employee e) {if ( e instanceof Manager ) {Manager m = (Manager) e;System.out.println(“This is the manager of

+ m.getDepartment());}// rest of operation

}

Page 181: Java must read for everyone

Java™ Module 6, slide 22 of 43Copyrig

bject.y casting.wing

ne implicitly.s and checked

when runtime

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Casting Objects

• Use instanceof to test the type of an o• Restore full functionality of an object b• Check for proper casting using the follo

guidelines:• Casts upward in the hierarchy are do• Downward casts must be to a subclas

by the compiler.• The object type is checked at runtime

errors can occur.

Page 182: Java must read for everyone

Java™ Module 6, slide 23 of 43Copyrig

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Overloading Methods

• Use overloading as follows:public void println(int i)public void println(float f)public void println(String s)

• Argument lists must differ.• Return types can be different.

Page 183: Java must read for everyone

Java™ Module 6, slide 24 of 43Copyrig

ents

it multiple

array. For

););

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Methods Using Variable Argum

• Methods using variable arguments permnumber of arguments in methods.For example:public class Statistics {public float average(int... nums) {int sum = 0;for ( int x : nums ) {sum += x;

}return ((float) sum) / nums.length;

}}

• The vararg parameter is treated as an example:float gradePointAverage = stats.average(4, 3, 4float averageAge = stats.average(24, 32, 27, 18

Page 184: Java must read for everyone

Java™ Module 6, slide 25 of 43Copyrig

verloaded.

e DoB)

irst line of a

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Overloading Constructors

• As with methods, constructors can be oAn example is:public Employee(String name, double salary, Datpublic Employee(String name, double salary)public Employee(String name, Date DoB)

• Argument lists must differ.• You can use the this reference at the f

constructor to call another constructor.

Page 185: Java must read for everyone

Java™ Module 6, slide 26 of 43Copyrig

12 0;34567 DoB) {8910111213141516171819

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Overloading Constructors

public class Employee { private static final double BASE_SALARY = 15000.0 private String name; private double salary; private Date birthDate;

public Employee(String name, double salary, Date this.name = name; this.salary = salary; this.birthDate = DoB; }public Employee(String name, double salary) {

this(name, salary, null); } public Employee(String name, Date DoB) { this(name, BASE_SALARY, DoB); }// more Employee code...

}

Page 186: Java must read for everyone

Java™ Module 6, slide 27 of 43Copyrig

ed

iables from the

ctor from the

ors.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Constructors Are Not Inherit

• A subclass inherits all methods and varsuperclass (parent class).

• A subclass does not inherit the construsuperclass.

• Two ways to include a constructor are:• Use the default constructor.• Write one or more explicit construct

Page 187: Java must read for everyone

Java™ Module 6, slide 28 of 43Copyrig

ctors

st place a call tor.or by theper.structor, thenper() that callshich could be

s, but does noten a compiler

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Invoking Parent Class Constru

• To invoke a parent constructor, you musuper in the first line of the constructo

• You can call a specific parent constructarguments that you use in the call to su

• If no this or super call is used in a conthe compiler adds an implicit call to suthe parent no argument constructor (wthe default constructor).If the parent class defines constructorprovide a no-argument constructor, therror message is issued.

Page 188: Java must read for everyone

Java™ Module 6, slide 29 of 43Copyrig

ctors

1234 dept) {56789101112 s: no super()13141516

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Invoking Parent Class Constru

public class Manager extends Employee {private String department;

public Manager(String name, double salary, Stringsuper(name, salary);department = dept;

}public Manager(String name, String dept) {super(name);department = dept;

}public Manager(String dept) { // This code faildepartment = dept;

}//more Manager code...

}

Page 189: Java must read for everyone

Java™ Module 6, slide 30 of 43Copyrig

ects: A

Me occurs.

Ins s recursively:

then skip to

t super call,

initializers.ructor.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Constructing and Initializing ObjSlight Reprise

mory is allocated and default initialization

tance variable initialization uses these step

1. Bind constructor parameters.2. If explicit this(), call recursively, and

Step 5.3. Call recursively the implicit or explici

except for Object.4. Execute the explicit instance variable5. Execute the body of the current const

Page 190: Java must read for everyone

Sun Educational Services

Constructor and InitializationExamples

1 public class Object {2 public Object() {}3 }

1 public class Employee extends Object {2 private String name;3 private double salary = 15000.00;4 private Date birthDate;56 public Employee(String n, Date DoB) {7 // implicit super();8 name = n;9 birthDate = DoB;10 }11 public Employee(String n) {12 this(n, null);13 }14 }

1 public class Manager extends Employee {2 private String department;34 public Manager(String n, String d) {5 super(n);6 department = d;7 }8 }

Java™ Programming Language Module 6, slide 31 of 43Copyright Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Page 191: Java must read for everyone

Java™ Module 6, slide 32 of 43Copyrig

mples

0 Ba 0.0. values (0 or null)

1 Ca 1. les" 1. 1. ", DoB=null or Object

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Constructor and Initialization Exa

sic initialization1 Allocate memory for the complete Manager object2 Initialize all instance variables to their defaultll constructor: Manager("Joe Smith", "Sales")1 Bind constructor parameters: n="Joe Smith", d="Sa2 No explicit this() call3 Call super(n) for Employee(String)1.3.1 Bind constructor parameters: n="Joe Smith"1.3.2 Call this(n, null) for Employee(String, Date) 1.3.2.1 Bind constructor parameters: n="Joe Smith 1.3.2.2 No explicit this() call 1.3.2.3 Call super() for Object() 1.3.2.3.1 No binding necessary 1.3.2.3.2 No this() call 1.3.2.3.3 No super() call (Object is the root) 1.3.2.3.4 No explicit variable initialization f 1.3.2.3.5 No method body to call

Page 192: Java must read for everyone

Java™ Module 6, slide 33 of 43Copyrig

mples

alary=15000.00; ; 1. 1.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Constructor and Initialization Exa

1.3.2.4 Initialize explicit Employee variables: s 1.3.2.5 Execute body: name="Joe Smith"; date=null1.3.3 - 1.3.4 Steps skipped1.3.5 Execute body: No body in Employee(String)4 No explicit initializers for Manager5 Execute body: department="Sales"

Page 193: Java must read for everyone

Java™ Module 6, slide 34 of 43Copyrig

s in Java.ause implies

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The ObjectClass

• The Object class is the root of all classe• A class declaration with no extends cl

extends Object. For example:public class Employee { ...}

is equivalent to:public class Employee extends Object { ...}

• Two important methods are:• equals

• toString

Page 194: Java must read for everyone

Java™ Module 6, slide 35 of 43Copyrig

rences arehe same object).ts are equal but

als method

ethod touality.emethod if you

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The equalsMethod

• The == operator determines if two refeidentical to each other (that is, refer to t

• The equalsmethod determines if objecnot necessarily identical.

• The Object implementation of the equuses the == operator.

• User classes can override the equals mimplement a domain-specific test for eq

• Note: You should override thehashCodoverride the equals method.

Page 195: Java must read for everyone

Java™ Module 6, slide 36 of 43Copyrig

12345678910

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

An equalsExample

public class MyDate { private int day; private int month; private int year;

public MyDate(int day, int month, int year) { this.day = day; this.month = month; this.year = year; }

Page 196: Java must read for everyone

Java™ Module 6, slide 37 of 43Copyrig

1112131415161718192021222324252627

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

An equalsExample

public boolean equals(Object o) {boolean result = false;if ( (o != null) && (o instanceof MyDate) ) {MyDate d = (MyDate) o;if ( (day == d.day) && (month == d.month)

&& (year == d.year) ) {result = true;

}}return result;

}

public int hashCode() {return (day ^ month ^ year);

}}

Page 197: Java must read for everyone

Java™ Module 6, slide 38 of 43Copyrig

1234567 e2");89 date2");10111213 ;1415 e2");16

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

An equalsExample

class TestEquals {public static void main(String[] args) {

MyDate date1 = new MyDate(14, 3, 1976); MyDate date2 = new MyDate(14, 3, 1976);

if ( date1 == date2 ) { System.out.println("date1 is identical to dat } else { System.out.println("date1 is not identical to }

if ( date1.equals(date2) ) { System.out.println("date1 is equal to date2") } else { System.out.println("date1 is not equal to dat }

Page 198: Java must read for everyone

Java™ Module 6, slide 39 of 43Copyrig

171819202122 e2");2324 date2");252627

Th

datedateset date

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

An equalsExample

System.out.println("set date2 = date1;"); date2 = date1;

if ( date1 == date2 ) { System.out.println("date1 is identical to dat } else { System.out.println("date1 is not identical to } }}

is example generates the following output:

1 is not identical to date21 is equal to date2date2 = date1;1 is identical to date2

Page 199: Java must read for everyone

Java™ Module 6, slide 40 of 43Copyrig

Th acteristics:

ing.ation.ation about a

c method to

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The toStringMethod

e toString method has the following char

• This method converts an object to a Str• Use this method during string concaten• Override this method to provide inform

user-defined object in readable format.• Use the wrapper class’s toString stati

convert primitive types to a String.

Page 200: Java must read for everyone

Java™ Module 6, slide 41 of 43Copyrig

Lo

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Wrapper Classes

ok at primitive data elements as objects.

Primitive Data Type Wrapper Class

boolean Boolean

byte Byte

char Character

short Short

int Integer

long Long

float Float

double Double

Page 201: Java must read for everyone

Java™ Module 6, slide 42 of 43Copyrig

An

int Inte oxingint

Oth

int int

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Wrapper Classes

example of a wrapper class is:

pInt = 420;ger wInt = new Integer(pInt); // this is called bp2 = wInt.intValue(); // this is called unboxing

er methods are:

x = Integer.valueOf(str).intValue();x = Integer.parseInt(str);

Page 202: Java must read for everyone

Java™ Module 6, slide 43 of 43Copyrig

es

Au

ject equivalent

xingg

n dealing with

metic

ng

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Autoboxing of Primitive Typ

toboxing has the following description:

• Conversion of primitive types to the ob• Wrapper classes not always needed• Example:

int pInt = 420;Integer wInt = pInt; // this is called autoboint p2 = wInt; // this is called autounboxin

• Language feature used most often whecollections

• Wrapped primitives also usable in arithexpressions

• Performance loss when using autoboxi

Page 203: Java must read for everyone

Sun

Java™ Programmi

res

Educational Services

ng Language

Module 7

Advanced Class Featu

Page 204: Java must read for everyone

Java™ Module 7, slide 2 of 44Copyrig

itializersbles

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Create static variables, methods, and in• Create final classes, methods, and varia• Create and use enumerated types• Use the static import statement• Create abstract classes and methods• Create and use an interface

Page 205: Java must read for everyone

Java™ Module 7, slide 3 of 44Copyrig

by all instances

om being

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Relevance

• How can you create a constant?• How can you declare data that is shared

of a given class?• How can you keep a class or method fr

subclassed or overridden?

Page 206: Java must read for everyone

Java™ Module 7, slide 4 of 44Copyrig

ier on variables,

bute or methodather than any

ass members,

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The staticKeyword

• Thestatickeyword is used as a modifmethods, and nested classes.

• The static keyword declares the attriis associated with the class as a whole rparticular instance of that class.

• Thus static members are often called clsuch as class attributes or class methods.

Page 207: Java must read for everyone

Java™ Module 7, slide 5 of 44Copyrig

Cla s of a class:

282930313233343536

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Class Attributes

ss attributes are shared among all instance

public class Count {private int serialNumber;public static int counter = 0;

public Count() {counter++;serialNumber = counter;

}}

c1 : Count

Count

serialNumber=1

-serialNumber : int

+counter : int = 0

c2 : Count

serialNumber=2

«instanceOf»«instanceOf»

Page 208: Java must read for everyone

Java™ Module 7, slide 6 of 44Copyrig

If t

12345678

it c out an instance:

12345

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Class Attributes

he static member is public:

public class Count1 {private int serialNumber;public static int counter = 0;

public Count1() { counter++; serialNumber = counter; }}

an be accessed from outside the class with

public class OtherClass { public void incrementNumber() {

Count1.counter++; }}

Page 209: Java must read for everyone

Java™ Module 7, slide 7 of 44Copyrig

You

12345678910111213

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Class Methods

can create static methods:

public class Count2 { private int serialNumber; private static int counter = 0;

public static int getTotalCount() { return counter; }

public Count2() {counter++;

serialNumber = counter; }}

Page 210: Java must read for everyone

Java™ Module 7, slide 8 of 44Copyrig

You instance of thecla

123456789

Th

NumbNumb

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Class Methods

can invoke static methods without anyss to which it belongs:

public class TestCounter { public static void main(String[] args) { System.out.println("Number of counter is " + Count2.getTotalCount()); Count2 counter = new Count2(); System.out.println("Number of counter is " + Count2.getTotalCount()); }}

e output of the TestCounter program is:

er of counter is 0er of counter is 1

Page 211: Java must read for everyone

Java™ Module 7, slide 9 of 44Copyrig

Sta es:

12345678

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Class Methods

tic methods cannot access instance variabl

public class Count3 { private int serialNumber; private static int counter = 0;

public static int getSerialNumber() { return serialNumber; // COMPILER ERROR! }}

Page 212: Java must read for everyone

Java™ Module 7, slide 10 of 44Copyrig

that does not

hen the class is

ze static (class)

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Static Initializers

• A class can contain code in a static blockexist within a method body.

• Static block code executes once only, wloaded.

• Usually, a static block is used to initialiattributes.

Page 213: Java must read for everyone

Java™ Module 7, slide 11 of 44Copyrig

1234 ter").intValue();56

123 );45

Th is:

javacoun

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Static Initializers

public class Count4 { public static int counter;static {

counter = Integer.getInteger("myApp.Count4.coun}

}

public class TestStaticInit { public static void main(String[] args) { System.out.println("counter = "+ Count4.counter }}

e output of the TestStaticInit program

-DmyApp.Count4.counter=47 TestStaticInitter = 47

Page 214: Java must read for everyone

Java™ Module 7, slide 12 of 44Copyrig

, but thatthe declaration;

t be set in every

be set in the

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The finalKeyword

• You cannot subclass a final class.• You cannot override a final method.• A final variable is a constant.• You can set a final variable once only

assignment can occur independently ofthis is called a blank final variable.• A blank final instance attribute mus

constructor.• A blank final method variable must

method body before being used.

Page 215: Java must read for everyone

Java™ Module 7, slide 13 of 44Copyrig

Co

publpr 3.2;..

}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Final Variables

nstants are static final variables.

ic class Bank {ivate static final double DEFAULT_INTEREST_RATE = . // more declarations

Page 216: Java must read for everyone

Java™ Module 7, slide 14 of 44Copyrig

12345678910111213141516171819

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Blank Final Variables

public class Customer {

private final long customerID;

public Customer() {customerID = createID();

}

public long getID() {return customerID;

}

private long createID() {return ... // generate new ID

}

// more declarations

}

Page 217: Java must read for everyone

Java™ Module 7, slide 15 of 44Copyrig

iom

En gramming.1234567891011121314151617

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Old-Style Enumerated Type Id

umerated types are a common idiom in pro0

package cards.domain;

public class PlayingCard {

// pseudo enumerated type public static final int SUIT_SPADES = 0; public static final int SUIT_HEARTS = 1; public static final int SUIT_CLUBS = 2; public static final int SUIT_DIAMONDS = 3;

private int suit; private int rank;

public PlayingCard(int suit, int rank) { this.suit = suit; this.rank = rank; }

Page 218: Java must read for everyone

Java™ Module 7, slide 16 of 44Copyrig

m

2223242526272829303132333435363738394041

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Old-Style Enumerated Type Idio

public String getSuitName() { String name = ““; switch ( suit ) { case SUIT_SPADES: name = “Spades”; break; case SUIT_HEARTS: name = “Hearts”; break; case SUIT_CLUBS: name = “Clubs”; break; case SUIT_DIAMONDS: name = “Diamonds”; break; default: System.err.println(“Invalid suit.”); } return name; }

Page 219: Java must read for everyone

Java™ Module 7, slide 17 of 44Copyrig

m

Old

12345678910 ()11 ;1213 .1415 ()16 ;1718

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Old-Style Enumerated Type Idio

-style idiom is not type-safe:

package cards.tests;

import cards.domain.PlayingCard;

public class TestPlayingCard { public static void main(String[] args) {

PlayingCard card1 = new PlayingCard(PlayingCard.SUIT_SPADES, 2); System.out.println(“card1 is the “ + card1.getRank + “ of “ + card1.getSuitName())

// You can create a playing card with a bogus suit PlayingCard card2 = new PlayingCard(47, 2); System.out.println(“card2 is the “ + card2.getRank + “ of “ + card2.getSuitName()) }}

Page 220: Java must read for everyone

Java™ Module 7, slide 18 of 44Copyrig

iom

Th lems:

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Old-Style Enumerated Type Id

is enumerated type idiom has several prob

• Not type-safe• No namespace• Brittle character• Uninformative printed values

Page 221: Java must read for everyone

Java™ Module 7, slide 19 of 44Copyrig

e

No es:

123456789

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The New Enumerated Typ

w you can create type-safe enumerated typ

package cards.domain;

public enum Suit { SPADES, HEARTS, CLUBS, DIAMONDS}

Page 222: Java must read for everyone

Java™ Module 7, slide 20 of 44Copyrig

e

Us

123456789101112131415

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The New Enumerated Typ

ing enumerated types is easy:

package cards.domain;

public class PlayingCard {

private Suit suit; private int rank;

public PlayingCard(Suit suit, int rank) { this.suit = suit; this.rank = rank; }

public Suit getSuit() { return suit; }

Page 223: Java must read for everyone

Java™ Module 7, slide 21 of 44Copyrig

161718192021222324252627282930313233343536

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The New Enumerated Type

public String getSuitName() { String name = ““; switch ( suit ) { case SPADES: name = “Spades”; break; case HEARTS: name = “Hearts”; break; case CLUBS: name = “Clubs”; break; case DIAMONDS: name = “Diamonds”; break; default: // No need for error checking as the Suit // enum is finite. } return name; }

Page 224: Java must read for everyone

Java™ Module 7, slide 22 of 44Copyrig

e

En

1234567891011 ank()12 ());1314151617

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The New Enumerated Typ

umerated types are type-safe:

package cards.tests;

import cards.domain.PlayingCard;import cards.domain.Suit;

public class TestPlayingCard { public static void main(String[] args) {

PlayingCard card1 = new PlayingCard(Suit.SPADES, 2); System.out.println(“card1 is the “ + card1.getR + “ of “ + card1.getSuitName

// PlayingCard card2 = new PlayingCard(47, 2); // This will not compile. }}

Page 225: Java must read for everyone

Java™ Module 7, slide 23 of 44Copyrig

es

En thods:123456789101112131415161718

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Advanced Enumerated Typ

umerated types can have attributes and mepackage cards.domain;

public enum Suit { SPADES (“Spades”), HEARTS (“Hearts”), CLUBS (“Clubs”), DIAMONDS (“Diamonds”);

private final String name;

private Suit(String name) { this.name = name; }

public String getName() { return name; }}

Page 226: Java must read for everyone

Java™ Module 7, slide 24 of 44Copyrig

es

Pu ssible:

1234567891011 ank()12 etName());1314 , 2);151617

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Advanced Enumerated Typ

blic methods on enumerated types are acce

package cards.tests;

import cards.domain.PlayingCard;import cards.domain.Suit;

public class TestPlayingCard { public static void main(String[] args) {

PlayingCard card1 = new PlayingCard(Suit.SPADES, 2); System.out.println(“card1 is the “ + card1.getR + “ of “ + card1.getSuit().g

// NewPlayingCard card2 = new NewPlayingCard(47 // This will not compile. }}

Page 227: Java must read for everyone

Java™ Module 7, slide 25 of 44Copyrig

ers from a class:er_name>;

idually or

nstants:;

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Static Imports

• A static import imports the static membimport static <pkg_list>.<class_name>.<membORimport static <pkg_list>.<class_name>.*;

• A static import imports members indivcollectively:import static cards.domain.Suit.SPADES;ORimport static cards.domain.Suit.*;

• There is no need to qualify the static coPlayingCard card1 = new PlayingCard(SPADES, 2)

• Use this feature sparingly.

Page 228: Java must read for everyone

Java™ Module 7, slide 26 of 44Copyrig

An

12345678910 ank()11 etName());1213 , 2);141516

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Static Imports

example of a static import is:

package cards.tests;

import cards.domain.PlayingCard;import static cards.domain.Suit.*;

public class TestPlayingCard { public static void main(String[] args) {

PlayingCard card1 = new PlayingCard(SPADES, 2); System.out.println(“card1 is the “ + card1.getR + “ of “ + card1.getSuit().g

// NewPlayingCard card2 = new NewPlayingCard(47 // This will not compile. }}

Page 229: Java must read for everyone

Java™ Module 7, slide 27 of 44Copyrig

Th this:

hicle

RiverBarge

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Abstract Classes

e design of the Shipping system looks like

Ve

Truck

Companyfleet

0..*

shipping

domainShippingMain «Uses»

FuelNeedsReport «Uses»

reports

Page 230: Java must read for everyone

Java™ Module 7, slide 28 of 44Copyrig

Fle

12345 s6789101112 ;131415

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Abstract Classes

et initialization code is shown here:

public class ShippingMain {public static void main(String[] args) {Company c = new Company();

// populate the company with a fleet of vehiclec.addVehicle( new Truck(10000.0) );c.addVehicle( new Truck(15000.0) );c.addVehicle( new RiverBarge(500000.0) );c.addVehicle( new Truck(9500.0) );c.addVehicle( new RiverBarge(750000.0) );

FuelNeedsReport report = new FuelNeedsReport(c)report.generateText(System.out);

}}

Page 231: Java must read for everyone

Java™ Module 7, slide 29 of 44Copyrig

12345678910111213 + ) {1415

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Abstract Classes

public class FuelNeedsReport {private Company company;

public FuelNeedsReport(Company company) {this.company = company;

}

public void generateText(PrintStream output) {Vehicle1 v;double fuel;double total_fuel = 0.0;

for ( int i = 0; i < company.getFleetSize(); i+v = company.getVehicle(i);

Page 232: Java must read for everyone

Java™ Module 7, slide 30 of 44Copyrig

1617 fficency();1819 eeds "20212223 uel + " liters.");2425

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Abstract Classes

// Calculate the fuel needed for this tripfuel = v.calcTripDistance() / v.calcFuelE

output.println("Vehicle " + v.getName() + " n+ fuel + " liters of fuel.");

total_fuel += fuel;}output.println("Total fuel needs is " + total_f

}}

Page 233: Java must read for everyone

Java™ Module 7, slide 31 of 44Copyrig

An hich the fullim by the concretesub

e

() : double

: double

: double)

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Solution

abstract class models a class of objects in wplementation is not known but is suppliedclasses.

RiverBarg

Vehicle

+calcFuelEfficiency() : double

+calcTripDistance() : double

Truck

+calcFuelEfficiency() : double

+calcTripDistance() : double

+Truck(maxLoad : double)

{abstract}

«constructors»

«methods»

+calcFuelEfficiency

+calcTripDistance()

+RiverBarge(maxLoad

«constructors»

«methods»

Page 234: Java must read for everyone

Java™ Module 7, slide 32 of 44Copyrig

Th

1234

Th n:

1234 a given load */567 ay */89

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Solution

e declaration of the Vehicle class is:

public abstract class Vehicle {public abstract double calcFuelEfficiency();public abstract double calcTripDistance();

}

e Truck class must create an implementatio

public class Truck extends Vehicle {public Truck(double maxLoad) {...}

public double calcFuelEfficiency() { /* calculate the fuel consumption of a truck at } public double calcTripDistance() { /* calculate the distance of this trip on highw }}

Page 235: Java must read for everyone

Java™ Module 7, slide 33 of 44Copyrig

Lik nim

1234 ge */567 e river-ways */89

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Solution

ewise, the RiverBarge class must create aplementation:

public class RiverBarge extends Vehicle {public RiverBarge(double maxLoad) {...}

public double calcFuelEfficiency() { /* calculate the fuel efficiency of a river bar } public double calcTripDistance() { /* calculate the distance of this trip along th }}

Page 236: Java must read for everyone

Java™ Module 7, slide 34 of 44Copyrig

lient code and.such a contractentation.

the same

interfaces.

s>]face>]* ] {

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Interfaces

• A public interface is a contract between cthe class that implements that interface

• A Java interface is a formal declaration ofin which all methods contain no implem

• Many unrelated classes can implementinterface.

• A class can implement many unrelated• Syntax of a Java class is as follows:

<modifier> class <name> [extends <superclas[implements <interface> [,<inter

<member_declaration>*}

Page 237: Java must read for everyone

Java™ Module 7, slide 35 of 44Copyrig

publpupupu

}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Flyer Example

ic interface Flyer {blic void takeOff();blic void land();blic void fly();

+takeOff()

+land()

+fly()

«interface»

Flyer

+takeOff()

+land()

+fly()

Airplane

Page 238: Java must read for everyone

Java™ Module 7, slide 36 of 44Copyrig

publpu

}pu

}pu

}}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Flyer Example

ic class Airplane implements Flyer {blic void takeOff() {// accelerate until lift-off// raise landing gear

blic void land() {// lower landing gear// decelerate and lower flaps until touch-down// apply brakes

blic void fly() {// keep those engines running

Page 239: Java must read for everyone

Java™ Module 7, slide 37 of 44Copyrig

)

an

ding()

et()

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Flyer Example

+takeOff()

+land()

+fly()

«interface»

Flyer

+takeOff()

+land()

+fly()

Airplane

+takeOff()

+land()

+fly()

Bird

+takeOff(

+land()

+fly()

Superm

+buildNest()

+layEggs()

+leapBuil

+stopBull

Page 240: Java must read for everyone

Java™ Module 7, slide 38 of 44Copyrig

Kryptonian

eOff()

d()

()

perman

pBuilding()

pBullet()

()

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Flyer Example

Vehicle

Animal

+eat()

+takeOff()

+land()

+fly()

«interface»

Flyer

+takeOff()

+land()

+fly()

Airplane

+takeOff()

+land()

+fly()

Bird

+tak

+lan

+fly

Su

+buildNest()

+layEggs()

+lea

+sto

+eat() +eat

Page 241: Java must read for everyone

Java™ Module 7, slide 39 of 44Copyrig

publpu */ }pu */ }pu */ }pu */ }pu */ }pu */ }

}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Flyer Example

ic class Bird extends Animal implements Flyer {blic void takeOff() { /* take-off implementationblic void land() { /* landing implementationblic void fly() { /* fly implementationblic void buildNest() { /* nest building behaviorblic void layEggs() { /* egg laying behaviorblic void eat() { /* override eating behavior

Page 242: Java must read for everyone

Java™ Module 7, slide 40 of 44Copyrig

Kryptonian

takeOff()

land()

fly()

Superman

leapBuilding()

stopBullet()

eat()

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Flyer Example

Vehicle

Animal

+eat()

+takeOff()

+land()

+fly()

«interface»

Flyer

+takeOff()

+land()

+fly()

Airplane

+takeOff()

+land()

+fly()

Bird

+

+

+

+buildNest()

+layEggs()

+

+

+eat() +

HelicopterSeaPlane

Page 243: Java must read for everyone

Java™ Module 7, slide 41 of 44Copyrig

publpu

}

pr

}}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Flyer Example

ic class Airport {blic static void main(String[] args) {Airport metropolisAirport = new Airport();Helicopter copter = new Helicopter();SeaPlane sPlane = new SeaPlane();

metropolisAirport.givePermissionToLand(copter);metropolisAirport.givePermissionToLand(sPlane);

ivate void givePermissionToLand(Flyer f) {f.land();

Page 244: Java must read for everyone

Java™ Module 7, slide 42 of 44Copyrig

keOff()

nd()

y()

interface»

Flyer

ff()

)

lane

Helicopter

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Multiple Interface Example

+ta

+la

+fl

«

+takeO

+land(

+fly()

Airp

+dock()

+cruise()

«interface»

Sailer

SeaPlane

+dock()

+cruise()

Vehicle

RiverBarge

+dock()

+cruise()

Page 245: Java must read for everyone

Java™ Module 7, slide 43 of 44Copyrig

publpu

}

pr

}}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Multiple Interface Example

ic class Harbor {blic static void main(String[] args) {Harbor bostonHarbor = new Harbor();RiverBarge barge = new RiverBarge();SeaPlane sPlane = new SeaPlane();

bostonHarbor.givePermissionToDock(barge);bostonHarbor.givePermissionToDock(sPlane);

ivate void givePermissionToDock(Sailer s) {s.dock();

Page 246: Java must read for everyone

Java™ Module 7, slide 44 of 44Copyrig

Int

sses are

interfacee classed classes

laring a class

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Uses of Interfaces

erface uses include the following:

• Declaring methods that one or more claexpected to implement

• Determining an object’s programming without revealing the actual body of th

• Capturing similarities between unrelatwithout forcing a class relationship

• Simulating multiple inheritance by decthat implements several interfaces

Page 247: Java must read for everyone

Sun

Java™ Programmi

ons

Educational Services

ng Language

Module 8

Exceptions and Asserti

Page 248: Java must read for everyone

Java™ Module 8, slide 2 of 25Copyrig

ts

exceptions

iate uses of

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Define exceptions• Use try, catch, and finally statemen• Describe exception categories• Identify common exceptions• Develop programs to handle your own• Use assertions• Distinguish appropriate and inappropr

assertions• Enable assertions at runtime

Page 249: Java must read for everyone

Java™ Module 8, slide 3 of 25Copyrig

do you resolve

y your codeng, what might

pend CPU programs?

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Relevance

• In most programming languages, how runtime errors?

• If you make assumptions about the waworks, and those assumptions are wrohappen?

• Is it always necessary or desirable to expower testing assertions in production

Page 250: Java must read for everyone

Java™ Module 8, slide 4 of 25Copyrig

ns – Illegaloundming here from code atn at all.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Exceptions and Assertions

• Exceptions handle unexpected situatioargument, network failure, or file not f

• Assertions document and test programassumptions – This can never be negative

• Assertion tests can be removed entirelyruntime, so the code is not slowed dow

Page 251: Java must read for everyone

Java™ Module 8, slide 5 of 25Copyrig

orrect program

on class.ted as fatal or bugs are

Error class.

exceptions that

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Exceptions

• Conditions that can readily occur in a care checked exceptions.These are represented by the Excepti

• Severe problems that normally are treasituations that probably reflect programunchecked exceptions.Fatal situations are represented by theProbable bugs are represented by theRuntimeException class.

• The API documentation shows checkedcan be thrown from a method.

Page 252: Java must read for everyone

Java™ Module 8, slide 6 of 25Copyrig

123456789

javaSum

javaExce r input string: "two"

matException.java:48)

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Exception Example

public class AddArguments { public static void main(String args[]) { int sum = 0; for ( String arg : args ) { sum += Integer.parseInt(arg); } System.out.println("Sum = " + sum); }}

AddArguments 1 2 3 4= 10

AddArguments 1 two 3.0 4ption in thread "main" java.lang.NumberFormatException: Foat java.lang.NumberFormatException.forInputString(NumberForat java.lang.Integer.parseInt(Integer.java:447)at java.lang.Integer.parseInt(Integer.java:497)at AddArguments.main(AddArguments.java:5)

Page 253: Java must read for everyone

Java™ Module 8, slide 7 of 25Copyrig

t

1234567891011 eger.");121314

javaOne

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The try-catchStatemen

public class AddArguments2 { public static void main(String args[]) {

try { int sum = 0;

for ( String arg : args ) {sum += Integer.parseInt(arg);

} System.out.println("Sum = " + sum);

} catch (NumberFormatException nfe) { System.err.println("One of the command-line "

+ "arguments is not an int}

}}

AddArguments2 1 two 3.0 4of the command-line arguments is not an integer.

Page 254: Java must read for everyone

Java™ Module 8, slide 8 of 25Copyrig

nt

12345678 integer"9 uded in the sum.");1011121314

java[two sum.[3.0 sum.Sum

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The try-catchStateme

public class AddArguments3 { public static void main(String args[]) { int sum = 0;

for ( String arg : args ) {try {sum += Integer.parseInt(arg);

} catch (NumberFormatException nfe) {System.err.println("[" + arg + "] is not an

+ " and will not be incl}

} System.out.println("Sum = " + sum); }}

AddArguments3 1 two 3.0 4] is not an integer and will not be included in the] is not an integer and will not be included in the= 5

Page 255: Java must read for everyone

Java™ Module 8, slide 9 of 25Copyrig

nt

A t h clauses:

try //

} ca// wn

} ca// thrown

} ca//

}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The try-catchStateme

ry-catch statement can use multiple catc

{ code that might throw one or more exceptions

tch (MyException e1) { code to execute if a MyException exception is thro

tch (MyOtherException e2) { code to execute if a MyOtherException exception is

tch (Exception e3) { code to execute if any other exception is thrown

Page 256: Java must read for everyone

Java™ Module 8, slide 10 of 25Copyrig

rent try-catchethod.thod and is not

ed abnormally.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Call Stack Mechanism

• If an exception is not handled in the curblock, it is thrown to the caller of that m

• If the exception gets back to the main mehandled there, the program is terminat

Page 257: Java must read for everyone

Java™ Module 8, slide 11 of 25Copyrig

Th at alwaysexe

12345678

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The finallyClause

e finally clause defines a block of code thcutes.

try { startFaucet(); waterLawn();} catch (BrokenPipeException e) {

logProblem(e); } finally { stopFaucet();}

Page 258: Java must read for everyone

Java™ Module 8, slide 12 of 25Copyrig

icException

terException

rgumentException

ception

rflowError

oryError

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Exception Categories

Throwable

Error

Exception

RuntimeException

IOException

Arithmet

NullPoin

IllegalA

FileNotFoundEx

VirtualMachineError

AssertionError

StackOve

OutOfMem

EOFException

SQLException

Page 259: Java must read for everyone

Java™ Module 8, slide 13 of 25Copyrig

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Common Exceptions

• NullPointerException

• FileNotFoundException

• NumberFormatException

• ArithmeticException

• SecurityException

Page 260: Java must read for everyone

Java™ Module 8, slide 14 of 25Copyrig

e

Us

on by using the

on { ... }

Oth

eptions or

ptions.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Handle or Declare Rul

e the handle or declare rule as follows:

• Handle the exception by using thetry-catch-finally block.

• Declare that the code causes an exceptithrows clause.void trouble() throws IOException { ... }void trouble() throws IOException, MyExcepti

er Principles

• You do not need to declare runtime excerrors.

• You can choose to handle runtime exce

Page 261: Java must read for everyone

Java™ Module 8, slide 15 of 25Copyrig

tions

Th

by the

s thrown by the

Th

e overridden

by the

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Method Overriding and Excep

e overriding method can throw:

• No exceptions• One or more of the exceptions thrown

overridden method• One or more subclasses of the exception

overridden method

e overriding method cannot throw:

• Additional exceptions not thrown by thmethod

• Superclasses of the exceptions thrown overridden method

Page 262: Java must read for everyone

Java™ Module 8, slide 16 of 25Copyrig

tions

12345

12345

12 G345

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Method Overriding and Excep

public class TestA { public void methodA() throws IOException { // do some file manipulation }}

public class TestB1 extends TestA { public void methodA() throws EOFException {

// do some file manipulation}

}

public class TestB2 extends TestA { public void methodA() throws Exception { // WRON

// do some file manipulation}

}

Page 263: Java must read for everyone

Java™ Module 8, slide 17 of 25Copyrig

ns

1 ception {234 t port) {56789101112

Us the Exceptioncla n was made.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Creating Your Own Exceptio

public class ServerTimedOutException extends Ex private int port;

public ServerTimedOutException(String message, insuper(message);

this.port = port; }

public int getPort() { return port; }}

e the getMessage method, inherited from ss, to get the reason for which the exceptio

Page 264: Java must read for everyone

Java™ Module 8, slide 18 of 25Copyrig

ption

A m exception:

123456789 t connect",10 nect);1112

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Handling a User-Defined Exce

ethod can throw a user-defined, checked

public void connectMe(String serverName)throws ServerTimedOutException {

boolean successful; int portToConnect = 80;

successful = open(serverName, portToConnect);

if ( ! successful ) {throw new ServerTimedOutException("Could no portToCon

}}

Page 265: Java must read for everyone

Java™ Module 8, slide 19 of 25Copyrig

eption

An o captureuse

12345 alternative");6789 e() +10 e1.getPort());111213

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Handling a User-Defined Exc

other method can use a try-catch block tr-defined exceptions:

public void findServer() { try { connectMe(defaultServer); } catch (ServerTimedOutException e) { System.out.println("Server timed out, trying try { connectMe(alternativeServer); } catch (ServerTimedOutException e1) { System.out.println("Error: " + e1.getMessag " connecting to port " + } } }

Page 266: Java must read for everyone

Java™ Module 8, slide 20 of 25Copyrig

ssion> ;

alse, then an

string and usedror message.

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Assertions

• Syntax of an assertion is:assert <boolean_expression> ;assert <boolean_expression> : <detail_expre

• If <boolean_expression> evaluates fAssertionError is thrown.

• The second argument is converted to aas descriptive text in the AssertionEr

Page 267: Java must read for everyone

Java™ Module 8, slide 21 of 25Copyrig

tions

Us umptions andint

Ina

meters of a

eck that can

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Recommended Uses of Asser

e assertions to document and verify the assernal logic of a single method:

• Internal invariants• Control flow invariants• Postconditions and class invariants

ppropriate Uses of Assertions

• Do not use assertions to check the parapublic method.

• Do not use methods in the assertion chcause side-effects.

Page 268: Java must read for everyone

Java™ Module 8, slide 22 of 25Copyrig

Th

12345

Th

123456

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Internal Invariants

e problem is:

if (x > 0) {// do this

} else {// do that

}

e solution is:

if (x > 0) {// do this

} else {assert ( x == 0 );// do that, unless x is negative

}

Page 269: Java must read for everyone

Java™ Module 8, slide 23 of 25Copyrig

For

12345678910 d suit";1112

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Control Flow Invariants

example:

switch (suit) { case Suit.CLUBS: // ... break; case Suit.DIAMONDS: // ... break; case Suit.HEARTS: // ... break; case Suit.SPADES: // ... break; default: assert false : "Unknown playing car break;}

Page 270: Java must read for everyone

Java™ Module 8, slide 24 of 25Copyrig

iants

For

1234 empty stack");567 ement */ ;8910111213

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Postconditions and Class Invar

example:

public Object pop() { int size = this.getElementCount(); if (size == 0) { throw new RuntimeException("Attempt to pop from }

Object result = /* code to retrieve the popped el

// test the postconditionassert (this.getElementCount() == size - 1);

return result;}

Page 271: Java must read for everyone

Java™ Module 8, slide 25 of 25Copyrig

n of

e runs as fast as

lt. Enables:

class, package,

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Controlling Runtime EvaluatioAssertions

• If assertion checking is disabled, the codif the check was never there.

• Assertion checks are disabled by defauassertions with the following commandjava -enableassertions MyProgram

or:java -ea MyProgram

• Assertion checking can be controlled onand package hierarchy bases, see:docs/guide/language/assert.html

Page 272: Java must read for everyone

Sun

Java™ Programmi

Col amework

Educational Services

ng Language

Module 9

lections and Generics Fr

Page 273: Java must read for everyone

Java™ Module 9, slide 2 of 40Copyrig

tions of therk

plementinges

n

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Describe the Collections• Describe the general purpose implementa

core interfaces in the Collections framewo• Examine the Map interface• Examine the legacy collection classes• Create natural and custom ordering by im

the Comparable and Comparator interfac• Use generic collections• Use type parameters in generic classes• Refactor existing non-generic code• Write a program to iterate over a collectio• Examine the enhanced for loop

Page 274: Java must read for everyone

Java™ Module 9, slide 3 of 40Copyrig

a group of

that group

lled elements;there is specific permitted.uplicates are

ates are

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Collections API

• A collection is a single object managing objects known as its elements.

• The Collections API contains interfacesobjects as one of the following:• Collection – A group of objects ca

implementations determine whetherordering and whether duplicates are

• Set – An unordered collection; no dpermitted.

• List – An ordered collection; duplicpermitted.

Page 275: Java must read for everyone

Java™ Module 9, slide 4 of 40Copyrig

dList

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Collections API

Collection<<interface>>

Set<<interface>>

List<<interface>>

HashSet

ArrayList Linke

+add

+size+remove

+isEmpty+contains+iterator

+add

+get+remove

+set+indexOf+listIterator

TreeSet

<<interface >>

SortedSet

Page 276: Java must read for everyone

Java™ Module 9, slide 5 of 40Copyrig

s

Th ations of thecor

Set

List

Dequ

Map

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Collection Implementation

ere are several general purpose implemente interfaces (Set, List, Deque and Map)

HashTable

ResizableArray

BalancedTree Linked List Hash Table +

Linked List

HashSet TreeSet LinkedHashSet

ArrayList LinkedList

e ArrayDeque LinkedList

HashMap TreeMap LinkedHashMap

Page 277: Java must read for everyone

Java™ Module 9, slide 6 of 40Copyrig

12345678910 dded11 dded121314

Th

[one

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

A SetExample

import java.util.*;public class SetExample { public static void main(String[] args) { Set set = new HashSet(); set.add("one"); set.add("second"); set.add("3rd"); set.add(new Integer(4)); set.add(new Float(5.0F)); set.add("second"); // duplicate, not a set.add(new Integer(4)); // duplicate, not a System.out.println(set); }}

e output generated from this program is:

, second, 5.0, 3rd, 4]

Page 278: Java must read for everyone

Java™ Module 9, slide 7 of 40Copyrig

12345678910 dded11 dded121314

Th

[one

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

A ListExample

import java.util.*public class ListExample { public static void main(String[] args) { List list = new ArrayList(); list.add("one"); list.add("second"); list.add("3rd"); list.add(new Integer(4)); list.add(new Float(5.0F)); list.add("second"); // duplicate, is a list.add(new Integer(4)); // duplicate, is a System.out.println(list); }}

e output generated from this program is:

, second, 3rd, 4, 5.0, second, 4]

Page 279: Java must read for everyone

Java™ Module 9, slide 8 of 40Copyrig

arrayskeys to values:

o values is not

viewed and

key-value pairs.ys in the map.ll values in the

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Map Interface

• Maps are sometimes called associative • A Map object describes mappings from

• Duplicate keys are not allowed• One-to-many mappings from keys t

permitted• The contents of the Map interface can be

manipulated as collections• entrySet – Returns a Set of all the• keySet – Returns a Set of all the ke• values – Returns a Collection of a

map.

Page 280: Java must read for everyone

Java™ Module 9, slide 9 of 40Copyrig

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Map Interface API

Page 281: Java must read for everyone

Java™ Module 9, slide 10 of 40Copyrig

12345678910111213141516 \n" + set2);1718

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

A MapExample

import java.util.*;public class MapExample {public static void main(String args[]) {Map map = new HashMap();map.put("one","1st");map.put("second", new Integer(2));map.put("third","3rd");// Overwrites the previous assignmentmap.put("third","III");// Returns set view of keysSet set1 = map.keySet();// Returns Collection view of valuesCollection collection = map.values();// Returns set view of key value mappingsSet set2 = map.entrySet();System.out.println(set1 + "\n" + collection + "

}}

Page 282: Java must read for everyone

Java™ Module 9, slide 11 of 40Copyrig

Ou ram:

[sec[2, [sec

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

A MapExample

tput generated from the MapExample prog

ond, one, third]1st, III]ond=2, one=1st, third=III]

Page 283: Java must read for everyone

Java™ Module 9, slide 12 of 40Copyrig

Co

e List

he Vector classethods.

ts the Map

f Hashtablelues.tsmethod thatumerationator interface.

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Legacy Collection Classes

llections in the JDK include:

• The Vector class, which implements thinterface.

• The Stack class, which is a subclass of tand supports the push, pop, and peek m

• The Hashtable class, which implemeninterface.

• The Properties class is an extension othat only uses Strings for keys and va

• Each of these collections has an elemenreturns an Enumeration object. The Eninterface is incompatible with, the Iter

Page 284: Java must read for everyone

Java™ Module 9, slide 13 of 40Copyrig

Th re useful forord

ral ordering to

er relation. Itering.

llections.

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Ordering Collections

e Comparable and Comparator interfaces aering collections:

• The Comparable interface imparts natuclasses that implement it.

• The Comparator interface specifies ordcan also be used to override natural ord

• Both interfaces are useful for sorting co

Page 285: Java must read for everyone

Java™ Module 9, slide 14 of 40Copyrig

Im ment it:

lemented to

implement the

ing objects that

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Comparable Interface

parts natural ordering to classes that imple

• Used for sorting• The compareTo method should be imp

make any class comparable:• int compareTo(Object o) method

• The String, Date, and Integer classesComparable interface

• You can sort the List elements containimplement the Comparable interface

Page 286: Java must read for everyone

Java™ Module 9, slide 15 of 40Copyrig

the natural

errr

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Comparable Interface

• While sorting, the List elements followordering of the element types• String elements – Alphabetical ord• Date elements – Chronological orde• Integer elements – Numerical orde

Page 287: Java must read for everyone

Java™ Module 9, slide 16 of 40Copyrig

erface

123456 int studentID,78 udentID == 09 ion();}101112131415161718

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Example of the Comparable Int

import java.util.*;class Student implements Comparable {String firstName, lastName;int studentID=0;double GPA=0.0;public Student(String firstName, String lastName,double GPA) {if (firstName == null || lastName == null || st|| GPA == 0.0) {throw new IllegalArgumentExceptthis.firstName = firstName;this.lastName = lastName;this.studentID = studentID;this.GPA = GPA;

}public String firstName() { return firstName; }public String lastName() { return lastName; }public int studentID() { return studentID; }public double GPA() { return GPA; }

Page 288: Java must read for everyone

Java™ Module 9, slide 17 of 40Copyrig

erface

19202122232425 than or before2627 than or after2829

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Example of the Comparable Int

// Implement compareTo method.public int compareTo(Object o) {double f = GPA-((Student)o).GPA;if (f == 0.0)return 0; // 0 signifies equalselse if (f<0.0)

return -1; // negative value signifies lesselse

return 1; // positive value signifies more}

}

Page 289: Java must read for everyone

Java™ Module 9, slide 18 of 40Copyrig

erface

12345 01,4.0));6 8 ));7 ));8 2.3));910111213 %.1f\n",14 s.GPA());151617

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Example of the Comparable Int

import java.util.*;public class ComparableTest {public static void main(String[] args) {TreeSet studentSet = new TreeSet(); studentSet.add(new Student("Mike", "Hauffmann",1studentSet.add(new Student("John", "Lynn",102,2. studentSet.add(new Student("Jim", "Max",103, 3.6 studentSet.add(new Student("Kelly", "Grant",104,Object[] studentArray = studentSet.toArray();Student s;for(Object obj : studentArray){s = (Student) obj;System.out.printf("Name = %s %s ID = %d GPA =s.firstName(), s.lastName(), s.studentID(),

}}

}

Page 290: Java must read for everyone

Java™ Module 9, slide 19 of 40Copyrig

erface

Ge

NameNameNameName

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Example of the Comparable Int

nerated Output:

= Kelly Grant ID = 104 GPA = 2.3 = John Lynn ID = 102 GPA = 2.8 = Jim Max ID = 103 GPA = 3.6 = Mike Hauffmann ID = 101 GPA = 4.0

Page 291: Java must read for everyone

Java™ Module 9, slide 20 of 40Copyrig

m the natural

heComparable

You he Comparatorint

2) method

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Comparator Interface

• Represents an order relation• Used for sorting• Enables sorting in an order different fro

order• Used for objects that do not implement t

interface• Can be passed to a sort method

need the comparemethod to implement terface:

• int compare(Object o1, Object o

Page 292: Java must read for everyone

Java™ Module 9, slide 21 of 40Copyrig

erface

1234567 udentID == 0 ||89101112131415161718

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Example of the Comparator Int

class Student {String firstName, lastName;int studentID=0;double GPA=0.0;public Student(String firstName, String lastName,int studentID, double GPA) {if (firstName == null || lastName == null || stGPA == 0.0) throw new NullPointerException();this.firstName = firstName;this.lastName = lastName;this.studentID = studentID;this.GPA = GPA;

}public String firstName() { return firstName; }public String lastName() { return lastName; }public int studentID() { return studentID; }public double GPA() { return GPA; }

}

Page 293: Java must read for everyone

Java™ Module 9, slide 22 of 40Copyrig

erface

12345 o2).firstName));67

1234567891011

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Example of the Comparator Int

import java.util.*;public class NameComp implements Comparator {public int compare(Object o1, Object o2) {return(((Student)o1).firstName.compareTo(((Student)

}}

import java.util.*;public class GradeComp implements Comparator {public int compare(Object o1, Object o2) {if (((Student)o1).GPA == ((Student)o2).GPA)return 0;else if (((Student)o1).GPA < ((Student)o2).GPA)return -1;elsereturn 1;

}}

Page 294: Java must read for everyone

Java™ Module 9, slide 23 of 40Copyrig

erface

123456 101,4.0));7 .8 ));8 6));9 ,2.3));1011121314 = %.1f\n",15 s.GPA());161718

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Example of the Comparator Int

import java.util.*;public class ComparatorTest {public static void main(String[] args) {Comparator c = new NameComp();TreeSet studentSet = new TreeSet(c);studentSet.add(new Student("Mike", "Hauffmann",studentSet.add(new Student("John", "Lynn",102,2studentSet.add(new Student("Jim", "Max",103, 3.studentSet.add(new Student("Kelly", "Grant",104Object[] studentArray = studentSet.toArray();Student s;for(Object obj : studentArray) {s = (Student) obj;System.out.println("Name = %s %s ID = %d GPA s.firstName(), s.lastName(), s.studentID(),

}}

}

Page 295: Java must read for everyone

Java™ Module 9, slide 24 of 40Copyrig

erface

NameNameNameName

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Example of the Comparator Int

= Jim Max ID = 0 GPA = 3.6 = John Lynn ID = 0 GPA = 2.8 = Kelly Grant ID = 0 GPA = 2.3 = Mike Hauffmann ID = 0 GPA = 4.0

Page 296: Java must read for everyone

Java™ Module 9, slide 25 of 40Copyrig

Ge

hecked

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Generics

nerics are described as follows:

• Provide compile-time type safety• Eliminate the need for casts• Provide the ability to create compiler-c

homogeneous collections

Page 297: Java must read for everyone

Java™ Module 9, slide 26 of 40Copyrig

Us

Arralistint

Us

Arralistint

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Generics

ing non-generic collections:

yList list = new ArrayList();.add(0, new Integer(42));total = ((Integer)list.get(0)).intValue();

ing generic collections:

yList<Integer> list = new ArrayList<Integer>();.add(0, new Integer(42));total = list.get(0).intValue();

Page 298: Java must read for everyone

Java™ Module 9, slide 27 of 40Copyrig

1234567891011121314

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Generic SetExample

import java.util.*;public class GenSetExample {public static void main(String[] args) {

Set<String> set = new HashSet<String>(); set.add("one"); set.add("second"); set.add("3rd");// This line generates compile error set.add(new Integer(4)); set.add("second");// Duplicate, not added System.out.println(set); }}

Page 299: Java must read for everyone

Java™ Module 9, slide 28 of 40Copyrig

1234567891011121314151617

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Generic Map Example

import java.util.*;

public class MapPlayerRepository { HashMap<String, String> players;

public MapPlayerRepository() { players = new HashMap<String, String> (); }

public String get(String position) { String player = players.get(position); return player; }

public void put(String position, String name) { players.put(position, name); }

Page 300: Java must read for everyone

Java™ Module 9, slide 29 of 40Copyrig

meters

Sho

Cate

Clasdecl

> extendsts List <E>

Condecl

Metdecl

Varideclexam

;

Instadeclexam

ing> (10);

e> (10);

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Generics: Examining Type Para

ws how to use type parameters

gory Non Generic Class Generic Class

saration

public class ArrayList extendsAbstractList implements List

public class ArrayList<EAbstractList<E> implemen

structoraration

public ArrayList(int capacity);

public ArrayList<E>(int capacity);

hodaration

public void add((Object o)

public Object get(int index)

public void add(E o)

public E get(int index)

ablearation

ples

ArrayList list1;

ArrayList list2;

ArrayList <String> list1

ArrayList <Date> list2;

ncearation

ples

list1 = new ArrayList(10);

list2 = new ArrayList(10);

list1= new ArrayList<Str

list2= new ArrayList<Dat

Page 301: Java must read for everyone

Java™ Module 9, slide 30 of 40Copyrig

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Generic Collections API

Page 302: Java must read for everyone

Java™ Module 9, slide 31 of 40Copyrig

s

nt

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Wild Card Type Parameter

Account

CheckingAccouSavingsAccount

Page 303: Java must read for everyone

Java™ Module 9, slide 32 of 40Copyrig

e

1234 ngAccount>();567 error!8910 o cast required1112

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Type-Safety Guarante

public class TestTypeSafety {

public static void main(String[] args) { List<CheckingAccount> lc = new ArrayList<Checki

lc.add(new CheckingAccount("Fred")); // OK lc.add(new SavingsAccount("Fred")); // Compile

// therefore... CheckingAccount ca = lc.get(0); // Safe, n }}

Page 304: Java must read for everyone

Java™ Module 9, slide 33 of 40Copyrig

78 ngAccount>();9 Account>();1011121314151617181920

In ckingAccountis a unt> is not anArr

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Invariance Challenge

List<Account> la; List<CheckingAccount> lc = new ArrayList<Checki List<SavingsAccount> ls = new ArrayList<Savings

//if the following were possible... la = lc; la.add(new CheckingAccount("Fred"));

//then the following must also be possible... la = ls; la.add(new CheckingAccount("Fred"));

//so... SavingsAccount sa = ls.get(0); //aarrgghh!!

fact, la=lc; is illegal, so even though a Chen Account, an ArrayList<CheckingAccoayList<Account>.

Page 305: Java must read for everyone

Java™ Module 9, slide 34 of 40Copyrig

6 nt> lea) {78910111213 ngAccount>();14 Account>();15161718192021 error!2223

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Covariance Response

public static void printNames(List <? extends Accou for (int i=0; i < lea.size(); i++) { System.out.println(lea.get(i).getName());

} }

public static void main(String[] args) { List<CheckingAccount> lc = new ArrayList<Checki List<SavingsAccount> ls = new ArrayList<Savings

printNames(lc); printNames(ls);

//but... List<? extends Object> leo = lc; //OK leo.add(new CheckingAccount("Fred"));//Compile }}

Page 306: Java must read for everyone

Java™ Module 9, slide 35 of 40Copyrig

on-

12345678

javaNote ions.Note

javaGene l to add(int,E)as a 1 wa

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Generics: Refactoring Existing NGeneric Code

import java.util.*;public class GenericsWarning {public static void main(String[] args) {List list = new ArrayList();list.add(0, new Integer(42));int total = ((Integer)list.get(0).intValue();

}}

c GenericsWarning.java: GenericsWarning.java uses unchecked or unsafe operat: Recompile with -Xlint:unchecked for details.

c -Xlint:unchecked GenericsWarning.javaricsWarning.java:7: warning: [unchecked] unchecked cal member of the raw type java.util.ArrayListlist.add(0, new Integer(42)); ^rning

Page 307: Java must read for everyone

Java™ Module 9, slide 36 of 40Copyrig

ry element in a

u to scan

tor, whichnd insert or

123456

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Iterators

• Iteration is the process of retrieving evecollection.

• The basic Iterator interface allows yoforward through any collection.

• A List object supports the ListIteraallows you to scan the list backwards amodify elements.

List<Student> list = new ArrayList<Student>();// add some elementsIterator<Student> elements = list.iterator();while (elements.hasNext()) {System.out.println(elements.next());

}

Page 308: Java must read for everyone

Java™ Module 9, slide 37 of 40Copyrig

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Generic Iterator Interfaces

Iterator<E>«interface»

ListIterator<E>«interface»

+hasNext() : boolean+next() : E+remove()

+hasPrevious() : boolean+previous() : E+add(element : E)+set(element : E)

Page 309: Java must read for everyone

Java™ Module 9, slide 38 of 40Copyrig

Th racteristics:

Ite

loop. to go wrong.

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Enhanced forLoop

e enhanced for loop has the following cha

• Simplified iteration over collections• Much shorter, clearer, and safer• Effective for arrays• Simpler when using nested loops• Iterator disadvantages removed

rators are error prone:

• Iterator variables occur three times per• This provides the opportunity for code

Page 310: Java must read for everyone

Java™ Module 9, slide 39 of 40Copyrig

An ing:

r loop:

.hasNext() ; ){

collections:

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Enhanced forLoop

enhanced for loop can look like the follow

• Using the iterator with a traditional fopublic void deleteAll(Collection<NameList> c){for ( Iterator<NameList> i = c.iterator() ; iNameList nl = i.next();nl.deleteItem();

}}

• Iterating using an enhanced for loop inpublic void deleteAll(Collection<NameList> c){for ( NameList nl : c ){nl.deleteItem();

}}

Page 311: Java must read for everyone

Java™ Module 9, slide 40 of 40Copyrig

12345678

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Enhanced forLoop

• Nested enhanced for loops:List<Subject> subjects=...;List<Teacher> teachers=...;List<Course> courseList = ArrayList<Course)();for (Subject subj: subjects) {for (Teacher tchr: teachers) {courseList.add(new Course(subj, tchr));

}}

Page 312: Java must read for everyone

Sun

Java™ Programmi

Educational Services

ng Language

Module 10

I/O Fundamentals

Page 313: Java must read for everyone

Java™ Module 10, slide 2 of 35Copyrig

ne arguments

, and use them

treams, and

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Write a program that uses command-liand system properties

• Examine the Properties class• Construct node and processing streams

appropriately• Serialize and deserialize objects• Distinguish readers and writers from s

select appropriately between them

Page 314: Java must read for everyone

Java™ Module 10, slide 3 of 35Copyrig

s

se

he command the class name:

in the argsethod:

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Command-Line Argument

• Any Java technology application can ucommand-line arguments.

• These string arguments are placed on tline to launch the Java interpreter afterjava TestArgs arg1 arg2 "another arg"

• Each command-line argument is placedarray that is passed to the static main mpublic static void main(String[] args)

Page 315: Java must read for everyone

Java™ Module 10, slide 4 of 35Copyrig

s

1234 rgs[i] + "’");567

Ex

javaargsargsargs

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Command-Line Argument

public class TestArgs { public static void main(String[] args) { for ( int i = 0; i < args.length; i++ ) { System.out.println("args[" + i + "] is ’" + a } }}

ample execution:

TestArgs arg0 arg1 "another arg"[0] is ’arg0’[1] is ’arg1’[2] is ’another arg’

Page 316: Java must read for everyone

Java™ Module 10, slide 5 of 35Copyrig

laces the are

eturns a

ringoperty. to include a

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

System Properties

• System properties are a feature that repconcept of environment variables (whichplatform-specific).

• The System.getProperties method rProperties object.

• The getProperty method returns a Strepresenting the value of the named pr

• Use the -D option on the command linenew property.

Page 317: Java must read for everyone

Java™ Module 10, slide 6 of 35Copyrig

pping of names

Enumeration

ringoperty.s collection into

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The PropertiesClass

• ThePropertiesclass implements a mato values (a String-to-String map).

• The propertyNames method returns anof all property names.

• The getProperty method returns a Strepresenting the value of the named pr

• You can also read and write a propertiea file using load and store.

Page 318: Java must read for everyone

Java™ Module 10, slide 7 of 35Copyrig

123456789

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The PropertiesClass

import java.util.Properties;import java.util.Enumeration;

public class TestProperties { public static void main(String[] args) { Properties props = System.getProperties();

props.list(System.out);}

}

Page 319: Java must read for everyone

Java™ Module 10, slide 8 of 35Copyrig

Th rogram:

java

Th

javasun.javajavajavafileusermyPr

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The PropertiesClass

e following is an example test run of this p

-DmyProp=theValue TestProperties

e following is the (partial) output:

.runtime.name=Java(TM) SE Runtime Environmentboot.library.path=C:\jse\jdk1.6.0\jre\bin.vm.version=1.6.0-b105.vm.vendor=Sun Microsystems Inc..vm.name=Java HotSpot(TM) Client VM.encoding.pkg=sun.io.country=USop=theValue

Page 320: Java must read for everyone

Java™ Module 10, slide 9 of 35Copyrig

or to a sink.a, also called an

a, also called an

.y, and pipes

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

I/O Stream Fundamentals

• A stream is a flow of data from a source• A source stream initiates the flow of dat

input stream.• A sink stream terminates the flow of dat

output stream.• Sources and sinks are both node streams• Types of node streams are files, memor

between threads or processes.

Page 321: Java must read for everyone

Java™ Module 10, slide 10 of 35Copyrig

es

Str racter Streams

Sou der

Sin ter

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Fundamental Stream Class

eam Byte Streams Cha

rce streams InputStream Rea

k streams OutputStream Wri

Page 322: Java must read for everyone

Java™ Module 10, slide 11 of 35Copyrig

streams:

andled by

d by input

byte stream.haracter

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Data Within Streams

• Java technology supports two types of character and byte.

• Input and output of character data is hreaders and writers.

• Input and output of byte data is handlestreams and output streams:• Normally, the term stream refers to a• The terms reader and writer refer to c

streams.

Page 323: Java must read for everyone

Java™ Module 10, slide 12 of 35Copyrig

s

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The InputStreamMethod

• The three basic read methods are:int read()int read(byte[] buffer)int read(byte[] buffer, int offset, int length)

• Other methods include:void close()int available()long skip(long n)boolean markSupported()void mark(int readlimit)void reset()

Page 324: Java must read for everyone

Java™ Module 10, slide 13 of 35Copyrig

s

h)

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The OutputStreamMethod

• The three basic write methods are:void write(int c)void write(byte[] buffer)void write(byte[] buffer, int offset, int lengt

• Other methods include:void close()void flush()

Page 325: Java must read for everyone

Java™ Module 10, slide 14 of 35Copyrig

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The ReaderMethods

• The three basic read methods are:int read()int read(char[] cbuf)int read(char[] cbuf, int offset, int length)

• Other methods include:void close()boolean ready()long skip(long n)boolean markSupported()void mark(int readAheadLimit)void reset()

Page 326: Java must read for everyone

Java™ Module 10, slide 15 of 35Copyrig

h)

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The WriterMethods

• The basic write methods are:void write(int c)void write(char[] cbuf)void write(char[] cbuf, int offset, int length)void write(String string)void write(String string, int offset, int lengt

• Other methods include:void close()void flush()

Page 327: Java must read for everyone

Java™ Module 10, slide 16 of 35Copyrig

Ty ms

Fil StreamtStream

Mearr

InputStreamOutputStream

Mestr

Pip tStreamutStream

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Node Streams

pe Character Streams Byte Strea

e FileReaderFileWriter

FileInputFileOutpu

mory:ay

CharArrayReaderCharArrayWriter

ByteArrayByteArray

mory:ing

StringReaderStringWriter

N/A

e PipedReaderPipedWriter

PipedInpuPipedOutp

Page 328: Java must read for everyone

Java™ Module 10, slide 17 of 35Copyrig

Th ng a manualbu

java

123456789101112131415

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

A Simple Example

is program performs a copy file operation usiffer:

TestNodeStreams file1 file2

import java.io.*;public class TestNodeStreams { public static void main(String[] args) { try {

FileReader input = new FileReader(args[0]);try {FileWriter output = new FileWriter(args[1]);try {char[] buffer = new char[128];int charsRead;

// read the first buffercharsRead = input.read(buffer);while ( charsRead != -1 ) {// write buffer to the output file

Page 329: Java must read for everyone

Java™ Module 10, slide 18 of 35Copyrig

161718192021222324252627282930

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

A Simple Example

output.write(buffer, 0, charsRead);

// read the next buffercharsRead = input.read(buffer);

}

} finally {output.close();}

} finally {input.close();}

} catch (IOException e) {e.printStackTrace();

}}

}

Page 330: Java must read for everyone

Java™ Module 10, slide 19 of 35Copyrig

Th ng a built-inbu

java

123456 ut);789 utput);101112131415

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Buffered Streams

is program performs a copy file operation usiffer:

TestBufferedStreams file1 file2

import java.io.*;public class TestBufferedStreams {public static void main(String[] args) {try {FileReader input = new FileReader(args[0]);BufferedReader bufInput = new BufferedReader(inptry {FileWriter output = new FileWriter(args[1]);BufferedWriter bufOutput= new BufferedWriter(otry {String line;// read the first lineline = bufInput.readLine();while ( line != null ) {// write the line out to the output file

Page 331: Java must read for everyone

Java™ Module 10, slide 20 of 35Copyrig

16 );1718192021222324252627282930313233

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Buffered Streams

bufOutput.write(line, 0, line.length()bufOutput.newLine();// read the next lineline = bufInput.readLine();

}} finally {bufOutput.close();

}} finally {bufInput.close();

}} catch (IOException e) {e.printStackTrace();

}}

}

Page 332: Java must read for everyone

Java™ Module 10, slide 21 of 35Copyrig

Program

Data Sink

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

I/O Stream Chaining

Data Source

FileInputStreamBufferedInputStream

DataInputStream

Program

FileOutputStreamBufferedOutputStream

DataOutputStream

Input Stream Chain

Output Stream Chain

Page 333: Java must read for everyone

Java™ Module 10, slide 22 of 35Copyrig

Ty ams

Bu InputStreamOutputStream

Filt putStreamtputStream

Cobetand

Perobjser

putStreamtputStream

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Processing Streams

pe Character Streams Byte Stre

ffering BufferedReaderBufferedWriter

BufferedBuffered

ering FilterReaderFilterWriter

FilterInFilterOu

nvertingween bytes character

InputStreamReaderOutputStreamWriter

formingectialization

ObjectInObjectOu

Page 334: Java must read for everyone

Java™ Module 10, slide 23 of 35Copyrig

Ty ams

Percon

tStreamutStream

Co erInputStream

Pee InputStream

Pri eam

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Processing Streams

pe Character Streams Byte Stre

forming dataversion

DataInpuDataOutp

unting LineNumberReader LineNumb

king ahead PushbackReader Pushback

nting PrintWriter PrintStr

Page 335: Java must read for everyone

Java™ Module 10, slide 24 of 35Copyrig

rchy

InataInputStream

shbackInputStream

fferedInputStream

ineNumberInputStream

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The InputStreamClass Hiera

putStream

FileInputStream

ObjectInputStream

PipedInputStream

StringBufferInputStream

FilterInputStream

ByteArrayInputStream

D

Pu

Bu

L

SequenceInputStream

Page 336: Java must read for everyone

Java™ Module 10, slide 25 of 35Copyrig

archy

Ou

ataOutputStream

rintStreamrintStream

ufferedOutputStream

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The OutputStreamClass Hier

tputStream

FileOutputStream

ObjectOutputStream

FilterOutputStream

ByteArrayOutputStream

D

PP

B

PipedOutputStream

Page 337: Java must read for everyone

Java™ Module 10, slide 26 of 35Copyrig

Thees

m (called object process of

eam writes the data memberstream, followed.tream reads the class to matchvalues from the

nce of that class.ished if files (ors.

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The ObjectInputStreamandObjectOutputStreamClass

• The Java API provides a standard mechanisserialization) that completely automates thewriting and reading objects from streams.

• When writing an object, the object input strclass name, followed by a description of theof the class, in the order they appear in the sby the values for all the fields on that object

• When reading an object, the object output sname of the class and the description of theagainst the class in memory, and it reads thestream to populate a newly allocation insta

• Persistent storage of objects can be accomplother persistent storage) are used as stream

Page 338: Java must read for everyone

Java™ Module 10, slide 27 of 35Copyrig

Review

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Input Chaining Combinations: A

Page 339: Java must read for everyone

Java™ Module 10, slide 28 of 35Copyrig

O Review

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

utput Chaining Combinations: A

Page 340: Java must read for everyone

Java™ Module 10, slide 29 of 35Copyrig

the objects as a later when

lds of the object

elds of the

because theirtem-specific

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Serialization

• Serialization is a mechanism for savingsequence of bytes and rebuilding themneeded.

• When an object is serialized, only the fieare preserved

• When a field references an object, the fireferenced object are also serialized

• Some object classes are not serializablefields represent transient operating sysinformation.

Page 341: Java must read for everyone

Java™ Module 10, slide 30 of 35Copyrig

s

12345678910111213141516171819

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The SerializeDateClas

import java.io.*;import java.util.Date;

public class SerializeDate {

SerializeDate() { Date d = new Date ();

try { FileOutputStream f = new FileOutputStream ("date.ser"); ObjectOutputStream s = new ObjectOutputStream (f); s.writeObject (d); s.close (); } catch (IOException e) { e.printStackTrace (); } }

Page 342: Java must read for everyone

Java™ Module 10, slide 31 of 35Copyrig

s

2021222324

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The SerializeDateClas

public static void main (String args[]) { new SerializeDate(); }}

Page 343: Java must read for everyone

Java™ Module 10, slide 32 of 35Copyrig

ss

123456789101112131415161718

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The DeSerializeDateCla

import java.io.*;import java.util.Date;

public class DeSerializeDate {

DeSerializeDate () { Date d = null;

try { FileInputStream f = new FileInputStream ("date.ser"); ObjectInputStream s = new ObjectInputStream (f); d = (Date) s.readObject (); s.close (); } catch (Exception e) { e.printStackTrace (); }

Page 344: Java must read for everyone

Java™ Module 10, slide 33 of 35Copyrig

ss

19202122232425262728

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The DeSerializeDateCla

System.out.println( "Deserialized Date object from date.ser"); System.out.println("Date: "+d); }

public static void main (String args[]) { new DeSerializeDate();}

}

Page 345: Java must read for everyone

Java™ Module 10, slide 34 of 35Copyrig

y

R

FileReader

neNumberReader

backReader

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The ReaderClass Hierarch

eader

BufferedReader

CharArrayReader

PipedReader

FilterReader

StringReader

InputStreamReader

Li

Push

Page 346: Java must read for everyone

Java™ Module 10, slide 35 of 35Copyrig

y

W FileWriter

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The WriterClass Hierarch

riter

BufferedWriter

CharArrayWriter

PrintWriter

PipedWriter

FilterWriter

StringWriter

OutputStreamWriter

Page 347: Java must read for everyone

Sun

Java™ Programmi

/O

Educational Services

ng Language

Module 11

Console I/O and File I

Page 348: Java must read for everyone

Java™ Module 11, slide 2 of 17Copyrig

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Read data from the console• Write data to the console• Describe files and file I/O

Page 349: Java must read for everyone

Java™ Module 11, slide 3 of 17Copyrig

o write to

Stream. read from

tream.o write to

Stream.

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Console I/O

• The variable System.out enables you tstandard output.System.out is an object of type Print

• The variable System.in enables you tostandard input.System.in is an object of type InputS

• The variable System.err enables you tstandard error.System.err is an object of type Print

Page 350: Java must read for everyone

Java™ Module 11, slide 4 of 17Copyrig

t

ent and a

t without a

verloaded fornt, long,ject, and

ect) methodsent.

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Writing to Standard Outpu

• The println methods print the argumnewline character (\n).

• The print methods print the argumennewline character.

• The print and println methods are omost primitive types (boolean, char, ifloat, and double) and for char[], ObString.

• The print(Object) and println(Objcall the toString method on the argum

Page 351: Java must read for everyone

Java™ Module 11, slide 5 of 17Copyrig

ut

123456789101112 +13 xit");

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Reading From Standard Inp

import java.io.*;

public class KeyboardInput {public static void main (String args[]) {String s;// Create a buffered reader to read// each line from the keyboard.InputStreamReader ir= new InputStreamReader(System.in);

BufferedReader in = new BufferedReader(ir);

System.out.println("Unix: Type ctrl-d to exit.""\nWindows: Type ctrl-z to e

Page 352: Java must read for everyone

Java™ Module 11, slide 6 of 17Copyrig

ut

1415 reen.161718192021222324 tions.25262728

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Reading From Standard Inp

try {// Read each input line and echo it to the scs = in.readLine();while ( s != null ) {System.out.println("Read: " + s);s = in.readLine();

}

// Close the buffered reader.in.close();

} catch (IOException e) { // Catch any IO excepe.printStackTrace();

}}

}

Page 353: Java must read for everyone

Java™ Module 11, slide 7 of 17Copyrig

y as follows:

l);

this table.

Co

%s ling the

%d cimal value.

%f es scientific

%n .

%%

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Simple Formatted Output

• You can use the formatting functionalitout.printf(“name count\n”);String s = String.format(“%s %5d%n”, user, tota

• Common formatting codes are listed in

de Description

Formats the argument as a string, usually by caltoString method on the object.

%o %x Formats an integer, as a decimal, octal, or hexade

%g Formats a floating point number. The %g code usnotation.

Inserts a newline character to the string or stream

Inserts the % character to the string or stream.

Page 354: Java must read for everyone

Java™ Module 11, slide 8 of 17Copyrig

input function.ole inputms.

m);

ue);

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Simple Formatted Input

• The Scanner class provides a formatted• A Scanner class can be used with cons

streams as well as file or network strea• You can read console input as follows:

1 import java.io.*;2 import java.util.Scanner;3 public class ScanTest {4 public static void main(String [] args) {5 Scanner s = new Scanner(System.in);6 String param = s.next();7 System.out.println("the param 1" + para8 int value = s.nextInt();9 System.out.println("second param" + val10 s.close();11 }12 }

Page 355: Java must read for everyone

Java™ Module 11, slide 9 of 17Copyrig

Th ollowing:

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Files and File I/O

e java.io package enables you to do the f

• Create File objects• Manipulate File objects• Read and write to file streams

Page 356: Java must read for everyone

Java™ Module 11, slide 10 of 17Copyrig

t

Th

;

file.txt");

Dir gramminglan presents adir , for example:

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Creating a New FileObjec

e File class provides several utilities:

• File myFile;

• myFile = new File("myfile.txt")

• myFile = new File("MyDocs", "my

ectories are treated like files in the Java proguage. You can create a File object that reectory and then use it to identify other files

File myDir = new File("MyDocs");myFile = new File(myDir, "myfile.txt");

Page 357: Java must read for everyone

Java™ Module 11, slide 11 of 17Copyrig

s

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The FileTests and Utilitie

• File information:String getName()String getPath()String getAbsolutePath()String getParent()long lastModified()long length()

• File modification:boolean renameTo(File newName)boolean delete()

• Directory utilities:boolean mkdir()String[] list()

Page 358: Java must read for everyone

Java™ Module 11, slide 12 of 17Copyrig

s

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The FileTests and Utilitie

• File tests:boolean exists()boolean canWrite()boolean canRead()boolean isFile()boolean isDirectory()boolean isAbsolute();boolean is Hidden();

Page 359: Java must read for everyone

Java™ Module 11, slide 13 of 17Copyrig

aracters.e the readLine

haracters.e print and

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

File Stream I/O

• For file input:• Use the FileReader class to read ch• Use the BufferedReader class to us

method.• For file output:

• Use the FileWriter class to write c• Use the PrintWriter class to use th

println methods.

Page 360: Java must read for everyone

Java™ Module 11, slide 14 of 17Copyrig

A fi

12345678910111213

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

File Input Example

le input example is:

import java.io.*;public class ReadFile { public static void main (String[] args) { // Create file File file = new File(args[0]);

try { // Create a buffered reader

// to read each line from a file. BufferedReader in

= new BufferedReader(new FileReader(file)); String s;

Page 361: Java must read for everyone

Java™ Module 11, slide 15 of 17Copyrig

14 o the screen.1516171819202122232425 ;26272829303132

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Printing a File

// Read each line from the file and echo it ts = in.readLine();

while ( s != null ) {System.out.println("Read: " + s);s = in.readLine();

}// Close the buffered readerin.close();

} catch (FileNotFoundException e1) {// If this file does not exist

System.err.println("File not found: " + file)

} catch (IOException e2) {// Catch any other IO exceptions.

e2.printStackTrace();}

}}

Page 362: Java must read for everyone

Java™ Module 11, slide 16 of 17Copyrig

123456789 from standard in.1011121314151617

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

File Output Example

import java.io.*;

public class WriteFile {public static void main (String[] args) {// Create fileFile file = new File(args[0]);

try {// Create a buffered reader to read each lineInputStreamReader isr= new InputStreamReader(System.in);

BufferedReader in = new BufferedReader(isr); // Create a print writer on this file. PrintWriter out = new PrintWriter(new FileWriter(file)); String s;

Page 363: Java must read for everyone

Java™ Module 11, slide 17 of 17Copyrig

1819202122 reen.2324252627 nt writer.282930313233343536

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

File Output Example

System.out.print("Enter file text. "); System.out.println("[Type ctrl-d to stop.]");

// Read each input line and echo it to the sc while ((s = in.readLine()) != null) { out.println(s); }

// Close the buffered reader and the file pri in.close(); out.close();

} catch (IOException e) { // Catch any IO exceptions. e.printStackTrace(); } }}

Page 364: Java must read for everyone

Sun

Java™ Programmi

Build Swing API

Educational Services

ng Language

Module 12

ing Java GUIs Using the

Page 365: Java must read for everyone

Java™ Module 12, slide 2 of 35Copyrig

ainers,

d special-

del

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Describe the JFC Swing technology• Define Swing• Identify the Swing packages• Describe the GUI building blocks: cont

components, and layout managers• Examine top-level, general-purpose, an

purpose properties of container• Examine components• Examine layout managers• Describe the Swing single-threaded mo• Build a GUI using Swing components

Page 366: Java must read for everyone

Java™ Module 12, slide 3 of 35Copyrig

lasses

Jav l User Interface(GU

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

What Are the Java Foundation C(JFC)?

a Foundation Classes are a set of GraphicaI) support packages, including:

• Abstract Window Toolkit (AWT)• The Swing component set• 2D graphics• Pluggable look-and-feel• Accessibility• Drag-and-drop• Internationalization

Page 367: Java must read for everyone

Java™ Module 12, slide 4 of 35Copyrig

those in the

le look-and feel

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

What Is Swing?

• An enhanced GUI component set• Provides replacement components for

original AWT• Has special features, such as a pluggab

Page 368: Java must read for everyone

Java™ Module 12, slide 5 of 35Copyrig

V

C

mponent

UIject

UIManager

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Swing Architecture

• Has its roots in theModel-View-Controller(MVC) architecture

• The Swing componentsfollow Separable ModelArchitecture

M

Co

ObM

Page 369: Java must read for everyone

Java™ Module 12, slide 6 of 35Copyrig

Pa

jav orchooser

jav echooser

jav le

jav e

jav t

jav t.html

jav t.html.parser

jav t.rtf

jav o

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Swing Packages

ckage Name Package Name

ax.swing javax.swing.col

ax.swing.border javax.swing.fil

ax.swing.event javax.swing.tab

ax.swing.undo javax.swing.tre

ax.swing.plaf javax.swing.tex

ax.swing.plaf.basic javax.swing.tex

ax.swing.plaf.metal javax.swing.tex

ax.swing.plaf.multi javax.swing.tex

ax.swing.plaf.synth javax.swing.und

Page 370: Java must read for everyone

Java™ Module 12, slide 7 of 35Copyrig

Java

A S ollowingele

tainment

onents that are

laying out

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Examining the Composition of aTechnology GUI

wing API-based GUI is composed of the fments:

• Containers – Are on top of the GUI conhierarchy.

• Components – Contain all the GUI compderived from the JComponent class.

• Layout Managers – Are responsible forcomponents in a container.

Page 371: Java must read for everyone

Java™ Module 12, slide 8 of 35Copyrig

Java

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Examining the Composition of aTechnology GUI

ContainerComponents

Layout Managers

Page 372: Java must read for everyone

Java™ Module 12, slide 9 of 35Copyrig

Sw ain categories:

plitPane, and

e

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Swing Containers

ing containers can be classified into three m

• Top-level containers:• JFrame, JWindow, and JDialog

• General-purpose containers:• JPanel, JScrollPane,JToolBar,JS

JTabbedPane

• Special-purpose containers:• JInternalFrame and JLayeredPan

Page 373: Java must read for everyone

Java™ Module 12, slide 10 of 35Copyrig

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Top-Level Containers

Page 374: Java must read for everyone

Java™ Module 12, slide 11 of 35Copyrig

Sw s:

nents

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Swing Components

ing components can be broadly classified a

• Buttons• Text components• Uneditable information display compo• Menus• Formatted display components• Other basic controls

Page 375: Java must read for everyone

Java™ Module 12, slide 12 of 35Copyrig

y

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Swing Component Hierarch

Page 376: Java must read for everyone

Java™ Module 12, slide 13 of 35Copyrig

Sw d into threecat

Field (for user

ext in plain text,

Pane (displays

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Text Components

ing text components can be broadly divideegories.

• Text controls –JTextField,JPasswordinput)

• Plain text areas –JTextArea (displays talso for multi-line user input

• Styled text areas – JEditorPane, JTextformatted text)

Page 377: Java must read for everyone

Java™ Module 12, slide 14 of 35Copyrig

es

Co

commonponent.

Co

properties.

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Swing Component Properti

mmon component properties:

• All the Swing components share some properties because they all extend JCom

mponent-specific properties:

• Each component defines more specific

Page 378: Java must read for everyone

Java™ Module 12, slide 15 of 35Copyrig

ties

Pro

Bor

Bacandcol

Fon

Op

Mami

Ali

Pre )

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Common Component Proper

perty Methods

der Border getBorder()void setBorder(Border b)

kgroundforeground

or

void setBackground(Color bg)void setForeground(Color bg)

t void setFont(Font f)

aque void setOpaque(boolean isOpaque)

ximum andnimum size

void setMaximumSize(Dimension d)void setMinimumSize(Dimension d)

gnment void setAlignmentX(float ax)void setAlignmentY(float ay)

ferred size void setPreferredSize(Dimension ps

Page 379: Java must read for everyone

Java™ Module 12, slide 16 of 35Copyrig

ties

Th omboBox.

Pro

Ma count)

Mo cbm)

Sel

Sel

Item

Ren nderer ar)

Ed ag)

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Component-Specific Proper

e following shows properties specific to JC

perties Methods

ximum row count void setMaximumRowCount(int

del void setModal(ComboBoxModel

ected index int getSelectedIndex()

ected Item Object getSelectedItem()

count int getItemCount()

derer void setRenderer(ListCellRe

itable void setEditable(boolean fl

Page 380: Java must read for everyone

Java™ Module 12, slide 17 of 35Copyrig

tsents

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Layout Managers

• Handle problems caused by:• GUI resizing by user• Operating system differences in fon• Locale-specific text layout requirem

• Layout manager classes:• BorderLayout

• FlowLayout

• BoxLayout

• CardLayout

• GridLayout

• GridBagLayout

Page 381: Java must read for everyone

Java™ Module 12, slide 18 of 35Copyrig

er

Th nts in top,bot

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The BorderLayout Manag

e BorderLayout manager places componetom, left, right and center locations.

Page 382: Java must read for everyone

Java™ Module 12, slide 19 of 35Copyrig

12345678910111213141516

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

BorderLayoutExample

import java.awt.*;import javax.swing.*;

public class BorderExample { private JFrame f; private JButton bn, bs, bw, be, bc;

public BorderExample() { f = new JFrame("Border Layout"); bn = new JButton("Button 1"); bc = new JButton("Button 2"); bw = new JButton("Button 3"); bs = new JButton("Button 4"); be = new JButton("Button 5"); }

Page 383: Java must read for everyone

Java™ Module 12, slide 20 of 35Copyrig

17181920212223242526272829303132

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

BorderLayoutExample

public void launchFrame() { f.add(bn, BorderLayout.NORTH); f.add(bs, BorderLayout.SOUTH); f.add(bw, BorderLayout.WEST); f.add(be, BorderLayout.EAST); f.add(bc, BorderLayout.CENTER); f.setSize(400,200); f.setVisible(true); }

public static void main(String args[]) { BorderExample guiWindow2 = new BorderExample(); guiWindow2.launchFrame(); }}

Page 384: Java must read for everyone

Java™ Module 12, slide 21 of 35Copyrig

r

Th in a row, and ifthe xt row.

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The FlowLayout Manage

e FlowLayoutmanager places components row fills, components are placed in the ne

Page 385: Java must read for everyone

Java™ Module 12, slide 22 of 35Copyrig

12345678910111213141516171819

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

FlowLayoutExample

import javax.swing.*;import java.awt.*;

public class LayoutExample {private JFrame f;private JButton b1;private JButton b2;private JButton b3;private JButton b4;private JButton b5;

public LayoutExample() {f = new JFrame("GUI example");b1 = new JButton("Button 1");b2 = new JButton("Button 2");b3 = new JButton("Button 3");b4 = new JButton("Button 4");b5 = new JButton("Button 5");

}

Page 386: Java must read for everyone

Java™ Module 12, slide 23 of 35Copyrig

2021222324252627282930313233 ();34353637

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

FlowLayoutExample

public void launchFrame() {f.setLayout(new FlowLayout());f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);f.pack();f.setVisible(true);

}

public static void main(String args[]) {LayoutExample guiWindow = new LayoutExampleguiWindow.launchFrame();

}

} // end of LayoutExample class

Page 387: Java must read for everyone

Java™ Module 12, slide 24 of 35Copyrig

Th om left to right,and mn.

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The BoxLayoutManager

e BoxLayoutmanager adds components fr from top to bottom in a single row of colu

Page 388: Java must read for everyone

Java™ Module 12, slide 25 of 35Copyrig

r

Th ents in differentcar o box.

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The CardLayoutManage

e CardLayoutmanager places the componds. Cards are usually controlled by a comb

Page 389: Java must read for everyone

Java™ Module 12, slide 26 of 35Copyrig

r

Th in rows andcol

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The GridLayoutManage

e GridLayout manager places componentsumns in the form of a grid.

Page 390: Java must read for everyone

Java™ Module 12, slide 27 of 35Copyrig

12345678910111213141516

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

GridLayoutExample

import java.awt.*;import javax.swing.*;

public class GridExample { private JFrame f; private JButton b1, b2, b3, b4, b5;

public GridExample() { f = new JFrame("Grid Example"); b1 = new JButton("Button 1"); b2 = new JButton("Button 2"); b3 = new JButton("Button 3"); b4 = new JButton("Button 4"); b5 = new JButton("Button 5"); }

Page 391: Java must read for everyone

Java™ Module 12, slide 28 of 35Copyrig

171819202122232425262728293031323334

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

GridLayoutExample

public void launchFrame() { f.setLayout (new GridLayout(3,2));

f.add(b1); f.add(b2); f.add(b3); f.add(b4); f.add(b5);

f.pack(); f.setVisible(true); }

public static void main(String args[]) { GridExample grid = new GridExample(); grid.launchFrame(); }}

Page 392: Java must read for everyone

Java™ Module 12, slide 29 of 35Copyrig

er

Th onents in rowsand vides a widevar thecom

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The GridBagLayoutManag

e GridBagLayout manager arranges comp columns, similar to a grid layout, but proiety of options for resizing and positioningponents.

Page 393: Java must read for everyone

Java™ Module 12, slide 30 of 35Copyrig

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

GUI Construction

• Programmatic• GUI builder tool

Page 394: Java must read for everyone

Java™ Module 12, slide 31 of 35Copyrig

n

1234 );56 IT_ON_CLOSE);78910111213

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Programmatic Constructio

import javax.swing.*;public class HelloWorldSwing { private static void createAndShowGUI() { JFrame frame = new JFrame("HelloWorldSwing"

//Set up the window. frame.setDefaultCloseOperation(JFrame.EX JLabel label = new JLabel("Hello World");

// Add Label frame.add(label); frame.setSize(300,200);

// Display Window frame.setVisible(true);}

Page 395: Java must read for everyone

Java™ Module 12, slide 32 of 35Copyrig

n

1415 new Runnable() {16 read:1718192021

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Programmatic Constructio

public static void main(String[] args) {javax.swing.SwingUtilities.invokeLater(

//Schedule for the event-dispatching th //creating,showing this app's GUI.

public void run() {createAndShowGUI();} });

}}

Page 396: Java must read for everyone

Java™ Module 12, slide 33 of 35Copyrig

n

Th

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Programmatic Constructio

e output generated from the program

Page 397: Java must read for everyone

Java™ Module 12, slide 34 of 35Copyrig

Me g JLabel:

XIT_ON_CLOSE)close button is

e visible.ntent pane not

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Key Methods

thods for setting up the JFrame and addin

• setDefaultCloseOperationJFrame.E–Creates the program to exit when the clicked.

• setVisible(true)– Makes the JFram• add(label)– JLabel is added to the co

to the JFrame directly.

Page 398: Java must read for everyone

Java™ Module 12, slide 35 of 35Copyrig

h as rendering

und) processes

Runnable())

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Key Methods

• Tasks:• Executing GUI application code, suc• Handling GUI events• Handling time consuming (backgro

• The SwingUtilities class:• SwingUtilites.invokeLater(new

Page 399: Java must read for everyone

Sun

Java™ Programmi

H Events

Educational Services

ng Language

Module 13

andling GUI-Generated

Page 400: Java must read for everyone

Java™ Module 13, slide 2 of 24Copyrig

ed an event

UIs ander class

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Define events and event handling• Examine the Java SE event model• Describe GUI behavior• Determine the user action that originat• Develop event listeners• Describe concurrency in Swing-based G

describe the features of the SwingWork

Page 401: Java must read for everyone

Java™ Module 13, slide 3 of 24Copyrig

penedents an event

ser’s interaction

vent e) {

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

What Is an Event?

• Events – Objects that describe what hap• Event sources – The generator of an ev• Event handlers – A method that receive

object, deciphers it, and processes the uJFrame

JPanel

JButton

The user clicks on the button

Some Event HandleractionPerformed(ActionE ...}

ActionEvent

Page 402: Java must read for everyone

Java™ Module 13, slide 4 of 24Copyrig

ndlers.

ts when theyat component.

vent e) {

vent e) {

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Delegation Model

• An event can be sent to many event ha

• Event handlers register with componenare interested in events generated by th

JFrame

JPanel

JButton

The user clicks on the button

Another Event Handler

One Event Handler

actionPerformed(ActionE ...}

actionPerformed(ActionE ...}ActionEvent

Page 403: Java must read for everyone

Java™ Module 13, slide 5 of 24Copyrig

GUI

lers for the type

n one type of

ork among

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Delegation Model

• Client objects (handlers) register with acomponent that they want to observe.

• GUI components trigger only the handof event that has occurred.

• Most components can trigger more thaevent.

• The delegation model distributes the wmultiple classes.

Page 404: Java must read for everyone

Java™ Module 13, slide 6 of 24Copyrig

123456789101112131415161718

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

A Listener Example

import java.awt.*;import javax.swing.*;public class TestButton { private JFrame f; private JButton b;

public TestButton() { f = new JFrame("Test"); b = new JButton("Press Me!"); b.setActionCommand("ButtonPressed"); }

public void launchFrame() {b.addActionListener(new ButtonHandler());

f.add(b,BorderLayout.CENTER); f.pack(); f.setVisible(true); }

Page 405: Java must read for everyone

Java™ Module 13, slide 7 of 24Copyrig

192021222324

Co wing:

123 tener {456789

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

A Listener Example

public static void main(String args[]) { TestButton guiApp = new TestButton(); guiApp.launchFrame(); }}

de for the event listener looks like the follo

import java.awt.event.*;

public class ButtonHandler implements ActionLis public void actionPerformed(ActionEvent e) { System.out.println("Action occurred"); System.out.println("Button’s command is: " + e.getActionCommand()); }}

Page 406: Java must read for everyone

Java™ Module 13, slide 8 of 24Copyrig

java.util.EventObject

KeyEvent

MouseEvent

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Event Categoriesjava.awt.AWTEvent ActionEvent

AdjustmentEvent

ComponentEvent

TextEvent

ContainerEvent

FocusEvent

InputEvent

WindowEvent

java.awt.event

ItemEvent

Page 407: Java must read for everyone

Java™ Module 13, slide 9 of 24Copyrig

ces

Ca

Ac ActionEvent)

Item (ItemEvent)

Mo seEvent)useEvent)seEvent)eEvent)seEvent)

Momo

seEvent)Event)

Ke ent)vent)t)

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Method Categories and Interfa

tegory Interface Name Methods

tion ActionListener actionPerformed(

ItemListener itemStateChanged

use MouseListener mousePressed(MoumouseReleased(MomouseEntered(MoumouseExited(MousmouseClicked(Mou

usetion

MouseMotionListener mouseDragged(MoumouseMoved(Mouse

y KeyListener keyPressed(KeyEvkeyReleased(KeyEkeyTyped(KeyEven

Page 408: Java must read for everyone

Java™ Module 13, slide 10 of 24Copyrig

ces

Ca

Foc sEvent)vent)

Ad hanged)

Co omponentEvent)ComponentEvent)(ComponentEvent)omponentEvent)

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Method Categories and Interfa

tegory Interface Name Methods

us FocusListener focusGained(FocufocusLost(FocusE

justment AdjustmentListener adjustmentValueC(AdjustmentEvent

mponent ComponentListener componentMoved(CcomponentHidden(componentResizedcomponentShown(C

Page 409: Java must read for everyone

Java™ Module 13, slide 11 of 24Copyrig

ces

Ca

Wi dowEvent)owEvent)indowEvent)(WindowEvent)owEvent)indowEvent)(WindowEvent)

Co ntainerEvent)

Wista

d(WindowEvent e)

Wifoc

(WindowEvent e)indowEvent e)

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Method Categories and Interfa

tegory Interface Name Methods

ndow WindowListener windowClosing(WinwindowOpened(WindwindowIconified(WwindowDeiconifiedwindowClosed(WindwindowActivated(WwindowDeactivated

ntainer ContainerListener componentAdded(CocomponentRemoved(ContainerEvent)

ndowte

WindowStateListener windowStateChange

ndowus

WindowFocusListener windowGainedFocuswindowLostFocus(W

Page 410: Java must read for everyone

Java™ Module 13, slide 12 of 24Copyrig

ces

Ca

Mowh )

Inpme

ede)agede)

Hie

Hiebou

archyEvent e)erarchyEvent e)

AW TEvent e)

Tex extEvent)

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Method Categories and Interfa

tegory Interface Name Methods

useeel

MouseWheelListener mouseWheelMoved(MouseWheelEvent e

utthods

InputMethodListener caretPositionChang(InputMethodEvent inputMethodTextChn(InputMethodEvent

rarchy HierarchyListener hierarchyChanged(HierarchyEvent e)

rarchynds

HierarchyBoundsListener

ancestorMoved(HierancestorResized(Hi

T AWTEventListener eventDispatched(AW

t TextListener textValueChanged(T

Page 411: Java must read for everyone

Java™ Module 13, slide 13 of 24Copyrig

12345 tener {6789101112

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Complex Example

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class TwoListener

implements MouseMotionListener, MouseLis private JFrame f; private JTextField tf;

public TwoListener() { f = new JFrame("Two listeners example"); tf = new JTextField(30); }

Page 412: Java must read for everyone

Java™ Module 13, slide 14 of 24Copyrig

131415 ouse");16171819202122232425

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Complex Example

public void launchFrame() { JLabel label = new JLabel("Click and drag the m // Add components to the frame f.add(label, BorderLayout.NORTH); f.add(tf, BorderLayout.SOUTH); // Add this object as a listener f.addMouseMotionListener(this); f.addMouseListener(this); // Size the frame and make it visible f.setSize(300, 200); f.setVisible(true); }

Page 413: Java must read for everyone

Java™ Module 13, slide 15 of 24Copyrig

2627282930313233343536373839404142

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Complex Example

// These are MouseMotionListener events public void mouseDragged(MouseEvent e) { String s = "Mouse dragging: X = " + e.getX() + " Y = " + e.getY(); tf.setText(s); }

public void mouseEntered(MouseEvent e) { String s = "The mouse entered"; tf.setText(s); }

public void mouseExited(MouseEvent e) { String s = "The mouse has left the building"; tf.setText(s); }

Page 414: Java must read for everyone

Java™ Module 13, slide 16 of 24Copyrig

434445 he46474849505152535455565758

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Complex Example

// Unused MouseMotionListener method. // All methods of a listener must be present in t // class even if they are not used. public void mouseMoved(MouseEvent e) { }

// Unused MouseListener methods. public void mousePressed(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseReleased(MouseEvent e) { }

public static void main(String args[]) { TwoListener two = new TwoListener(); two.launchFrame(); }}

Page 415: Java must read for everyone

Java™ Module 13, slide 17 of 24Copyrig

of a program to

re called when

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Multiple Listeners

• Multiple listeners cause unrelated partsreact to the same event.

• The handlers of all registered listeners athe event occurs.

Page 416: Java must read for everyone

Java™ Module 13, slide 18 of 24Copyrig

extend adapterthat you need.

12345 {67891011121314

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Event Adapters

• The listener classes that you define canclasses and override only the methods

• An example is:import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class MouseClickHandler extends MouseAdapter

// We just need the mouseClick handler, so we use // an adapter to avoid having to write all the // event handler methods

public void mouseClicked(MouseEvent e) { // Do stuff with the mouse click... }}

Page 417: Java must read for everyone

Java™ Module 13, slide 19 of 24Copyrig

sses

12345678910111213 apter {1415 )16171819

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Event Handling Using Inner Cla

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class TestInner { private JFrame f; private JTextField tf; // used by inner class

public TestInner() { f = new JFrame("Inner classes example"); tf = new JTextField(30); }

class MyMouseMotionListener extends MouseMotionAd public void mouseDragged(MouseEvent e) { String s = "Mouse dragging: X = "+ e.getX( + " Y = " + e.getY();

tf.setText(s); }}

Page 418: Java must read for everyone

Java™ Module 13, slide 20 of 24Copyrig

sses

202122 ouse");2324252627 ner());2829303132333435363738

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Event Handling Using Inner Cla

public void launchFrame() { JLabel label = new JLabel("Click and drag the m // Add components to the frame f.add(label, BorderLayout.NORTH); f.add(tf, BorderLayout.SOUTH); // Add a listener that uses an Inner class f.addMouseMotionListener(new MyMouseMotionListe f.addMouseListener(new MouseClickHandler()); // Size the frame and make it visible f.setSize(300, 200); f.setVisible(true); }

public static void main(String args[]) { TestInner obj = new TestInner(); obj.launchFrame(); }}

Page 419: Java must read for everyone

Java™ Module 13, slide 21 of 24Copyrig

E Classes

123456789101112131415161718

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

vent Handling Using Anonymous

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class TestAnonymous { private JFrame f; private JTextField tf;

public TestAnonymous() { f = new JFrame("Anonymous classes example"); tf = new JTextField(30); }

public static void main(String args[]) { TestAnonymous obj = new TestAnonymous(); obj.launchFrame(); }

Page 420: Java must read for everyone

Java™ Module 13, slide 22 of 24Copyrig

E Classes

1920 ouse");2122232425 () {2627 )2829303132 Not shown3334353637

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

vent Handling Using Anonymous

public void launchFrame() { JLabel label = new JLabel("Click and drag the m // Add components to the frame f.add(label, BorderLayout.NORTH); f.add(tf, BorderLayout.SOUTH); // Add a listener that uses an anonymous class f.addMouseMotionListener(new MouseMotionAdapter public void mouseDragged(MouseEvent e) { String s = "Mouse dragging: X = "+ e.getX( + " Y = " + e.getY(); tf.setText(s); } }); // <- note the closing parenthesis f.addMouseListener(new MouseClickHandler()); // // Size the frame and make it visible f.setSize(300, 200); f.setVisible(true); }}

Page 421: Java must read for everyone

Java™ Module 13, slide 23 of 24Copyrig

To m needsdif

hreads)UI (event

e time

Eac an instance ofjav

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Concurrency In Swing

handle a GUI efficiently, the Swing prograferent threads to:

• Execute the application code (current t• Handle the events that arise from the G

dispatch threads)• Handle background tasks that might b

consuming (worker threads)

h task in a worker thread is represented byax.swing.SwingWorker.

Page 422: Java must read for everyone

Java™ Module 13, slide 24 of 24Copyrig

Th e the followingreq

nation betweenther threads:

results:

Sun Educational Services

Programming Languageht 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The SwingWorkerClass

e SwingWorker class has methods to servicuirements:

• To provide communication and coordiworker thread tasks and the tasks on o• Properties: state and progress

• To execute simple background tasks:• doInBackground method

• To execute tasks that have intermediate• publish method

• To cancel the background threads:• cancel method

Page 423: Java must read for everyone

Sun

Java™ Programmi

ns

Educational Services

ng Language

Module 14

GUI-Based Applicatio

Page 424: Java must read for everyone

Java™ Module 14, slide 2 of 12Copyrig

menu, and

d font of a

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Describe how to construct a menu bar, menu items in a Java GUI

• Understand how to change the color ancomponent

Page 425: Java must read for everyone

Java™ Module 14, slide 3 of 12Copyrig

I for bothut. However,

ich GUIs can becomponents

UI frame?

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Relevance

• You now know how to set up a Java GUgraphic output and interactive user inponly a few of the components from whbuilt have been described. What other would be useful in a GUI?

• How can you create a menu for your G

Page 426: Java must read for everyone

Java™ Module 14, slide 4 of 12Copyrig

to a menu

add them to

, and add them

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

How to Create a Menu

1. Create a JMenuBar object, and set it incontainer, such as a JFrame.

2. Create one or more JMenu objects, andthe menu bar object.

3. Create one or more JMenuItem objectsto the menu object.

Page 427: Java must read for everyone

Java™ Module 14, slide 5 of 12Copyrig

123

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Creating a JMenuBar

f = new JFrame("MenuBar");mb = new JMenuBar();f.setJMenuBar(mb);

Page 428: Java must read for everyone

Java™ Module 14, slide 6 of 12Copyrig

131415161718192021

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Creating a JMenu

f = new JFrame("Menu");mb = new JMenuBar();m1 = new JMenu("File");m2 = new JMenu("Edit");m3 = new JMenu("Help");mb.add(m1);mb.add(m2);mb.add(m3);f.setJMenuBar(mb);

Page 429: Java must read for everyone

Java™ Module 14, slide 7 of 12Copyrig

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Creating a JMenu

Page 430: Java must read for everyone

Java™ Module 14, slide 8 of 12Copyrig

28293031323334353637383940

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Creating a JMenuItem

mi1 = new JMenuItem("New");mi2 = new JMenuItem("Save");mi3 = new JMenuItem("Load");mi4 = new JMenuItem("Quit");mi1.addActionListener(this);mi2.addActionListener(this);mi3.addActionListener(this);mi4.addActionListener(this);m1.add(mi1);m1.add(mi2);m1.add(mi3);m1.addSeparator();m1.add(mi4);

Page 431: Java must read for everyone

Java™ Module 14, slide 9 of 12Copyrig

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Creating a JMenuItem

Page 432: Java must read for everyone

Java™ Module 14, slide 10 of 12Copyrig

tem

192021222324252627....434445

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Creating a JCheckBoxMenuI

f = new JFrame("CheckboxMenuItem");mb = new JMenuBar();m1 = new JMenu("File");m2 = new JMenu("Edit");m3 = new JMenu("Help");mb.add(m1);mb.add(m2);mb.add(m3);f.setJMenuBar(mb);.......mi5 = new JCheckBoxMenuItem("Persistent");mi5.addItemListener(this);m1.add(mi5);

Page 433: Java must read for everyone

Java™ Module 14, slide 11 of 12Copyrig

tem

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Creating a JCheckBoxMenuI

Page 434: Java must read for everyone

Java™ Module 14, slide 12 of 12Copyrig

Co I include:

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Controlling Visual Aspects

mmands to control visual aspects of the GU

• Colors:setForeground()setBackground()

• Example:Color purple = new Color(255, 0, 255);JButton b = new JButton(“Purple”);b.setBackground(purple);

Page 435: Java must read for everyone

Sun

Java™ Programmi

Educational Services

ng Language

Module 15

Threads

Page 436: Java must read for everyone

Java™ Module 15, slide 2 of 39Copyrig

ology program,sed by that

rite platform-

when multiple

etween threads corruption

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Define a thread• Create separate threads in a Java techn

controlling the code and data that are uthread

• Control the execution of a thread and windependent code with threads

• Describe the difficulties that might arisethreads share data

• Use waitand notify to communicate b• Use synchronized to protect data from

Page 437: Java must read for everyone

Java™ Module 15, slide 3 of 39Copyrig

Ho le taskscon

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Relevance

w do you get programs to perform multipcurrently?

Page 438: Java must read for everyone

Java™ Module 15, slide 4 of 39Copyrig

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Threads

• What are threads?Threads are a virtual CPU.

• The three parts of at thread are:• CPU• Code• Data

CPU

Code Data

A thread orexecution context

Page 439: Java must read for everyone

Java™ Module 15, slide 5 of 39Copyrig

12345678910111213141516171819

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Creating the Thread

public class ThreadTester { public static void main(String args[]) { HelloRunner r = new HelloRunner(); Thread t = new Thread(r); t.start(); }}class HelloRunner implements Runnable { int i; public void run() { i = 0; while (true) { System.out.println("Hello " + i++); if ( i == 50 ) { break; } } }}

Page 440: Java must read for everyone

Java™ Module 15, slide 6 of 39Copyrig

characteristics:ble instance.e.

”nner

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Creating the Thread

• Multithreaded programming has these• Multiple threads are from one Runna• Threads share the same data and cod

• For example:Thread t1 = new Thread(r);Thread t2 = new Thread(r);

CPU

Code DataHelloRunner Instance “r

Thread t}New Thread

Class of HelloRu

Page 441: Java must read for everyone

Java™ Module 15, slide 7 of 39Copyrig

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Starting the Thread

• Use the start method.• Place the thread in a runnable state.

Page 442: Java must read for everyone

Java™ Module 15, slide 8 of 39Copyrig

N Dead

run() Completes

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Thread Scheduling

Runnable

ew

RunningScheduler

Blocked

Unblocked Event Blocked

start()

Page 443: Java must read for everyone

Java™ Module 15, slide 9 of 39Copyrig

le

123456789101112131415

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Thread Scheduling Examp

public class Runner implements Runnable { public void run() { while (true) { // do lots of interesting stuff

// ...// Give other threads a chance

try {Thread.sleep(10);

} catch (InterruptedException e) { // This thread’s sleep was interrupted // by another thread } } }}

Page 444: Java must read for everyone

Java™ Module 15, slide 10 of 39Copyrig

1234567891011121314

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Terminating a Thread

public class Runner implements Runnable { private boolean timeToQuit=false;

public void run() { while ( ! timeToQuit ) { // continue doing work } // clean up before run() ends }

public void stopRunning() { timeToQuit=true; }}

Page 445: Java must read for everyone

Java™ Module 15, slide 11 of 39Copyrig

12345678910111213

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Terminating a Thread

public class ThreadController { private Runner r = new Runner(); private Thread t = new Thread(r);

public void startThread() { t.start(); }

public void stopThread() { // use specific instance of Runner r.stopRunning(); }}

Page 446: Java must read for everyone

Java™ Module 15, slide 12 of 39Copyrig

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Basic Control of Threads

• Test threads:isAlive()

• Access thread priority:getPriority()setPriority()

• Put threads on hold:Thread.sleep() // static methodjoin()Thread.yield() // static method

Page 447: Java must read for everyone

Java™ Module 15, slide 13 of 39Copyrig

12345 a while678910111213141516

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The joinMethod

public static void main(String[] args) { Thread t = new Thread(new Runner()); t.start(); ... // Do stuff in parallel with the other thread for ... // Wait here for the other thread to finish try { t.join(); } catch (InterruptedException e) { // the other thread came back early } ... // Now continue in this thread ...}

Page 448: Java must read for everyone

Java™ Module 15, slide 14 of 39Copyrig

ds

1234567891011121314151617

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Other Ways to Create Threa

public class MyThread extends Thread { public void run() { while ( true ) { // do lots of interesting stuff try { Thread.sleep(100); } catch (InterruptedException e) { // sleep interrupted } } }

public static void main(String args[]) { Thread t = new MyThread(); t.start(); }}

Page 449: Java must read for everyone

Java™ Module 15, slide 15 of 39Copyrig

eads

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Selecting a Way to Create Thr

• Implement Runnable:• Better object-oriented design• Single inheritance• Consistency

• Extend Thread:Simpler code

Page 450: Java must read for everyone

Java™ Module 15, slide 16 of 39Copyrig

ord

123456789101112131415

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Using the synchronizedKeyw

public class MyStack {

int idx = 0; char [] data = new char[6];

public void push(char c) { data[idx] = c; idx++; }

public char pop() { idx--; return data[idx]; }}

Page 451: Java must read for everyone

Java™ Module 15, slide 17 of 39Copyrig

lock flag. with the lock

h(char c) {(this) { c;

onized(this)

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Object Lock Flag

• Every object has a flag that is a type of• The synchronized enables interaction

flag.

Object this

public void pussynchronized data[idx] =idx++;

}}

Thread before synchr

Code orBehavior

Data orState

Page 452: Java must read for everyone

Java™ Module 15, slide 18 of 39Copyrig

h(char c) {(this) { c;

nized(this)

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Object Lock Flag

Object this

public void pussynchronized data[idx] =idx++;

}}

Thread after synchro

Code orBehavior

Data orState

Page 453: Java must read for everyone

Java™ Module 15, slide 19 of 39Copyrig

op() {d (this) {

ta[idx];

ing tozed(this)

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The Object Lock Flag

Object this

public char psynchronizeidx--;return da

}}

Another thread, try

Waiting for

lock flag missing

object lock

Code orBehavior

Data orState

execute synchroni

Page 454: Java must read for everyone

Java™ Module 15, slide 20 of 39Copyrig

Th ts:

d of the

eturn, ored code block

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Releasing the Lock Flag

e lock flag is released in the following even

• Released when the thread passes the ensynchronized code block

• Released automatically when a break, rexception is thrown by the synchroniz

Page 455: Java must read for everyone

Java™ Module 15, slide 21 of 39Copyrig

U ogether

nchronized.ed should be

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

sing synchronized– Putting It T

• All access to delicate data should be sy• Delicate data protected by synchroniz

private.

Page 456: Java must read for everyone

Java™ Module 15, slide 22 of 39Copyrig

U ogether

Th ent:

publ sy }}

publ//

}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

sing synchronized– Putting It T

e following two code segments are equival

ic void push(char c) {nchronized(this) {// The push method code

ic synchronized void push(char c) { The push method code

Page 457: Java must read for everyone

Java™ Module 15, slide 23 of 39Copyrig

h

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Thread State Diagram Wit

Page 458: Java must read for everyone

Java™ Module 15, slide 24 of 39Copyrig

N Dead

run() Completes

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Synchronization

Blocked inObject’s

Lock Pool

Runnable

ew

RunningScheduler

Blocked

Unblocked Event Blocked

Lock Acquired Synchronized

start()

Page 459: Java must read for everyone

Java™ Module 15, slide 25 of 39Copyrig

A d

from the other.

s

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Deadlock

eadlock has the following characteristics:

• It is two threads, each waiting for a lock• It is not detected or avoided.• Deadlock can be avoided by:

• Deciding on the order to obtain lock• Adhering to this order throughout• Releasing locks in reverse order

Page 460: Java must read for everyone

Java™ Module 15, slide 26 of 39Copyrig

otify

two threads.

at your

stination and

pon arrival at

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Thread Interaction – waitand n

• Scenario:Consider yourself and a cab driver as

• The problem:How do you determine when you aredestination?

• The solution:• You notify the cab driver of your de

relax.• The driver drives and notifies you u

your destination.

Page 461: Java must read for everyone

Java™ Module 15, slide 27 of 39Copyrig

Th

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Thread Interaction

read interactions include:

• The wait and notify methods• The pools:

• Wait pool• Lock pool

Page 462: Java must read for everyone

Java™ Module 15, slide 28 of 39Copyrig

h

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Thread State Diagram Wit

Page 463: Java must read for everyone

Java™ Module 15, slide 29 of 39Copyrig

Blocked inObject’s

Wait Pool

New Dead

un() Completes

)

wait()[Must have lock]/Releases lock

st

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

wait and notify

notify() orBlocked inObject’s

Lock Pool

Runnable RunningScheduler

Blocked

Unblocked Event Blocked

r

Lock Acquired Synchronized

interrupt(

art()

Page 464: Java must read for everyone

Java™ Module 15, slide 30 of 39Copyrig

tion

notifications in

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Monitor Model for Synchroniza

• Leave shared data in a consistent state.• Ensure programs cannot deadlock.• Do not put threads expecting different

the same wait pool.

Page 465: Java must read for everyone

Java™ Module 15, slide 31 of 39Copyrig

123456789101112

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The ProducerClass

package mod13;

public class Producer implements Runnable { private SyncStack theStack; private int num; private static int counter = 1;

public Producer (SyncStack s) { theStack = s; num = counter++; }

Page 466: Java must read for everyone

Java™ Module 15, slide 32 of 39Copyrig

13141516171819 c);202122232425262728

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The ProducerClass

public void run() { char c;

for (int i = 0; i < 200; i++) { c = (char)(Math.random() * 26 +’A’); theStack.push(c); System.out.println(“Producer” + num + “: “ + try { Thread.sleep((int)(Math.random() * 300)); } catch (InterruptedException e) { // ignore it } } } // END run method

} // END Producer class

Page 467: Java must read for everyone

Java™ Module 15, slide 33 of 39Copyrig

123456789101112

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The ConsumerClass

package mod13;

public class Consumer implements Runnable { private SyncStack theStack; private int num; private static int counter = 1;

public Consumer (SyncStack s) { theStack = s; num = counter++; }

Page 468: Java must read for everyone

Java™ Module 15, slide 34 of 39Copyrig

1314151617 c);181920212223242526

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The ConsumerClass

public void run() { char c; for (int i = 0; i < 200; i++) { c = theStack.pop(); System.out.println(“Consumer” + num + “: “ +

try { Thread.sleep((int)(Math.random() * 300)); } catch (InterruptedException e) { // ignore it } } } // END run method

Page 469: Java must read for everyone

Java™ Module 15, slide 35 of 39Copyrig

Th

publ

pr ter>(400);

pu

}

pu

}}

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The SyncStackClass

is is a sketch of the SyncStack class:

ic class SyncStack {

ivate List<Character> buffer = new ArrayList<Charac

blic synchronized char pop() {// pop code here

blic synchronized void push(char c) {// push code here

Page 470: Java must read for everyone

Java™ Module 15, slide 36 of 39Copyrig

9101112131415161718192021

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The popMethod

public synchronized char pop() { char c; while (buffer.size() == 0) { try { this.wait(); } catch (InterruptedException e) { // ignore it... } } c = buffer.remove(buffer.size()-1); return c; }

Page 471: Java must read for everyone

Java™ Module 15, slide 37 of 39Copyrig

22232425

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The pushMethod

public synchronized void push(char c) { this.notify(); buffer.add(c); }

Page 472: Java must read for everyone

Java™ Module 15, slide 38 of 39Copyrig

12345678910111213141516171819

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The SyncTestClass

package mod13;public class SyncTest { public static void main(String[] args) { SyncStack stack = new SyncStack(); Producer p1 = new Producer(stack); Thread prodT1 = new Thread (p1); prodT1.start(); Producer p2 = new Producer(stack); Thread prodT2 = new Thread (p2); prodT2.start();

Consumer c1 = new Consumer(stack); Thread consT1 = new Thread (c1); consT1.start(); Consumer c2 = new Consumer(stack); Thread consT2 = new Thread (c2); consT2.start(); }}

Page 473: Java must read for everyone

Java™ Module 15, slide 39 of 39Copyrig

ProdConsProdConsProdProdProdConsConsProdProdConsConsProdConsProdConsCons

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

The SyncTestClass

ucer2: Fumer1: Fucer2: Kumer2: Kucer2: Tucer1: Nucer1: Vumer2: Vumer1: Nucer2: Vucer2: Uumer2: Uumer2: Vucer1: Fumer1: Fucer2: Mumer2: Mumer2: T

Page 474: Java must read for everyone

Sun

Java™ Programmi

Educational Services

ng Language

Module 16

Networking

Page 475: Java must read for everyone

Java™ Module 16, slide 2 of 12Copyrig

nection

forservers

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Objectives

• Develop code to set up the network con• Understand the TCP/IP Protocol• Use ServerSocket and Socket classes

implementation of TCP/IP clients and

Page 476: Java must read for everyone

Java™ Module 16, slide 3 of 12Copyrig

Ho nt machine anda s

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Relevance

w can a communication link between a clieerver on the network be established?

Page 477: Java must read for everyone

Java™ Module 16, slide 4 of 12Copyrig

Th

So

am and an

ams.

Se

Set telephonesys ch must belist

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Networking

is section describes networking concepts.

ckets

• Sockets hold two streams: an input streoutput stream.

• Each end of the socket has a pair of stre

tting Up the Connection

up of a network connection is similar to a tem: One end must dial the other end, whiening.

Page 478: Java must read for everyone

Java™ Module 16, slide 5 of 12Copyrig

o.com

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Networking

client.bar.com

client.baz.com

server.fo

18000

18002

3000

Page 479: Java must read for everyone

Java™ Module 16, slide 6 of 12Copyrig

logy

following:hinese at the server

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Networking With Java Techno

• To address the connection, include the • The address or name of remote mac• A port number to identify the purpo

• Port numbers range from 0–65535.

Page 480: Java must read for everyone

Java™ Module 16, slide 7 of 12Copyrig

#)

)

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Java Networking Model

Server

ServerSocket (port #)

OutputStream

InputStream

Socket.close()

Client

Socket (host, port

OutputStream

InputStream

Socket.close(

Register withthis service

Wait for aconnection

(Attempt to connect)Socket()

ServerSocket.accept()

Page 481: Java must read for everyone

Java™ Module 16, slide 8 of 12Copyrig

12345678910111213

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Minimal TCP/IP Server

import java.net.*;import java.io.*;

public class SimpleServer { public static void main(String args[]) { ServerSocket s = null;

// Register your service on port 5432 try {

s = new ServerSocket(5432); } catch (IOException e) { e.printStackTrace(); }

Page 482: Java must read for everyone

Java™ Module 16, slide 9 of 12Copyrig

1415161718192021 cket22 );2324252627

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Minimal TCP/IP Server

// Run the listen/accept loop forever while (true) { try { // Wait here and listen for a connection

Socket s1 = s.accept();

// Get output stream associated with the so OutputStream s1out = s1.getOutputStream( BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(s1out));

// Send your string! bw.write(“Hello Net World!\n”);

Page 483: Java must read for everyone

Java™ Module 16, slide 10 of 12Copyrig

2829 socket303132333435363738394041

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Minimal TCP/IP Server

// Close the connection, but not the serverbw.close();s1.close();

} catch (IOException e) { e.printStackTrace(); } // END of try-catch

} // END of while(true)

} // END of main method

} // END of SimpleServer program

Page 484: Java must read for everyone

Java™ Module 16, slide 11 of 12Copyrig

123456789 54321011 ;1213141516 ;

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Minimal TCP/IP Client

import java.net.*;import java.io.*;

public class SimpleClient {

public static void main(String args[]) {

try { // Open your connection to a server, at port // localhost used here

Socket s1 = new Socket("127.0.0.1", 5432)

// Get an input stream from the socket InputStream is = s1.getInputStream(); // Decorate it with a "data" input stream DataInputStream dis = new DataInputStream(is)

Page 485: Java must read for everyone

Java™ Module 16, slide 12 of 12Copyrig

1718192021 tion22232425262728293031323334

Sun Educational Services

Programming Languageht Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G.1

Minimal TCP/IP Client

// Read the input and print it to the screen System.out.println(dis.readUTF());

// When done, just close the steam and connec dis.close(); s1.close();

} catch (ConnectException connExc) { System.err.println("Could not connect.");

} catch (IOException e) { // ignore } // END of try-catch

} // END of main method

} // END of SimpleClient program