core java

456
Sun Services Java™ Programming Language Java™ Programming Language SL-275

Upload: sounthar-rajan

Post on 12-Jan-2015

4.233 views

Category:

Education


1 download

DESCRIPTION

core java basics...

TRANSCRIPT

Page 1: core java

Sun

Java™ Programmi

Ja guage

Services

ng Language

va™ Programming Lan

SL-275

Page 2: core java

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 2006 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: core java

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 2006 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: core java

Java™ Programmi iv2006 Sun Microsystem

....................... 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 Languages, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

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 Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 With HTML3 .......................

Page 6: core java

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 Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

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 Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

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 Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

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 Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

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

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

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

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

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

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

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

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

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

................................................ 9-17

................................................ 9-18

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 ................................

Text-Based Applications ....................................................Objectives ...............................................................................................Relevance ................................................................................................Command-Line Arguments ................................................................System Properties ..................................................................................The Properties Class .........................................................................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 ................................................................

Page 11: core java

Java™ xiCopyrig

................................................ 9-20

................................................ 9-23

................................................ 9-25

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

................................................ 9-28................................................. 9-29................................................ 9-30................................................ 9-31................................................. 9-32................................................ 9-33................................................ 9-34................................................ 9-35

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

.............................................. 10-20

.............................................. 10-22

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

File Stream I/O ......................................................................................File Output Example .............................................................................The Collections API ..............................................................................A Set Example ......................................................................................A List Example ....................................................................................Collections in JDK™ Version 1.1 .......................................................Generics ..................................................................................................Generic Collections API .......................................................................Compiler Warnings .............................................................................Iterators ...................................................................................................The Iterator Interface Hierarchy .........................................................Enhanced for Loop ..............................................................................

Building Java GUIs .............................................................Objectives ...............................................................................................Relevance ................................................................................................Abstract Window Toolkit ....................................................................The java.awt Package .........................................................................Containers ..............................................................................................Positioning Components ......................................................................Frames .....................................................................................................The FrameExample Class .....................................................................Example Frame ......................................................................................Panels ......................................................................................................The FrameWithPanel Class .................................................................Layout Managers ..................................................................................Default Layout Managers ....................................................................A Simple FlowLayout Example ..........................................................The FlowLayout Manager ...................................................................The FlowExample Class .......................................................................

Page 12: core java

Java™ xiiCopyrig

.............................................. 10-24

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

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

.............................................. 10-28

.............................................. 10-29

.............................................. 10-30............................................... 10-32............................................... 10-33............................................... 10-36.............................................. 10-37

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

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

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

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

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

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

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

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

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

.............................................. 11-17

.............................................. 11-18............................................... 11-19............................................... 11-21

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

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

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

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

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

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The BorderLayout Manager ...............................................................Organization of the Border Layout Components .............................The BorderExample Class ...................................................................Example of BorderLayout ..................................................................The GridLayout Manager ...................................................................The GridExample Class .......................................................................Example of GridLayout .....................................................................The ComplexLayoutExample Class ..................................................Drawing in AWT ..................................................................................Various Shapes Drawn by the Graphics Object ..............................

GUI Event Handling .............................................................Objectives ...............................................................................................Relevance ................................................................................................What Is an Event? .................................................................................Delegation Model ..................................................................................A Listener Example ...............................................................................Event Categories ...................................................................................Method Categories and Interfaces ......................................................Complex Example .................................................................................Multiple Listeners .................................................................................Event Adapters ......................................................................................Event Handling Using Inner Classes ................................................Event Handling Using Anonymous Classes ....................................

GUI-Based Applications .....................................................Objectives ...............................................................................................Relevance ................................................................................................AWT Components ................................................................................AWT Listeners .......................................................................................

Page 13: core java

Java™ xiiiCopyrig

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

.............................................. 13-14

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

.............................................. 13-16

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

.............................................. 13-20

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

.............................................. 13-23

.............................................. 13-24

.............................................. 13-25

.............................................. 13-26

.............................................. 13-27

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

How to Create a Menu .........................................................................Creating a MenuBar ...............................................................................Creating a Menu .....................................................................................Creating a MenuItem .............................................................................Creating a CheckBoxMenuItem ...........................................................Controlling Visual Aspects ..................................................................J.F.C./Swing Technology .....................................................................

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 ......................................Thread State Diagram With Synchronization ...................................Deadlock .................................................................................................Thread Interaction – wait and notify ..............................................Thread Interaction .................................................................................Thread State Diagram With wait and notify ................................

Page 14: core java

Java™ xivCopyrig

.............................................. 13-28

.............................................. 13-29

.............................................. 13-31

.............................................. 13-33

.............................................. 13-34

.............................................. 13-35

.............................................. 13-36

.............................................. 13-37

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

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

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

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

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

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

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

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

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

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

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

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

.............................................. 14-14............................................... 14-16.............................................. 14-17.............................................. 14-19.............................................. 14-20.............................................. 14-21.............................................. 14-22

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

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

Advanced I/O Streams ........................................................Objectives ...............................................................................................Relevance ................................................................................................I/O 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 ....................................................The OutputStream Class Hierarchy ..................................................The Reader Class Hierarchy ...............................................................The Writer Class Hierarchy ...............................................................

Page 15: core java

Java™ xvCopyrig

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

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

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

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

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

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

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

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

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

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

Page 16: core java

Sun

Java™ Programmi

Services

ng Language

Preface

About This Course

Page 17: core java

Java™ Preface, slide xvii of xxviiCopyrig

Th d skills to:

hat leverage theuage, such asrphismrom the

ressionsructs

sing exception

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Preface, slide xviii of xxviiCopyrig

nterface (GUI)ents: panels,s

nality to read

rotocol/ommunicates

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Preface, slide xix of xxviiCopyrig

Th

nguage to the Java

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Sun Services

Course Map

The Java Programming Language Basics

More Object-Oriented Programming

Building Applications

Developing Graphical User Interfaces

Advanced Java Programming

Getting StartedObject-Oriented

Programming

Identifiers,Keywords, and

Types

Arrays

Class DesignAdvanced

Class Features

Text-Based

Applications

Building Java

GUIs

GUI Event

Handling

GUI-Based

Applications

Advanced

I/O StreamsThreads Networking

Expressions

and Flow Control

Exceptions

and Assertions

Java™ Programming Language Preface, slide xx of xxviiCopyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Page 21: core java

Java™ Preface, slide xxi of xxviiCopyrig

overed inlysis and Design

red in SL-110: Language

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Preface, slide xxii of xxviiCopyrig

Bef completedSL g Language, orhav

or C++t editorser, such as

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Preface, slide xxiii of xxviiCopyrig

in this course

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Preface, slide xxiv of xxviiCopyrig

?

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

How to Use the Icons

Additional resources

Discussion

Note

Caution

Visual Aid

!

Page 25: core java

Java™ Preface, slide xxv of xxviiCopyrig

T ymbols

ands, files,mmingtput.and numbersramming coden.es andplaced with a

epresentby the student

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 that you type, and for each line of progthat is referenced in a textual descriptio

• Courier italics is used for variablcommand-line placeholders that are rereal name or value.

• Courier italics bold is used to rvariables whose values are to be enteredas part of an activity.

Page 26: core java

Java™ Preface, slide xxvi of xxviiCopyrig

T ymbols

w words or

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

ypographical Conventions and S

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

Page 27: core java

Java™ Preface, slide xxvii of xxviiCopyrig

Jav e followingadd

ethods, and

es unless an.rations,e.g System

soft Windows

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Sun

Java™ Programmi

Services

ng Language

Module 1

Getting Started

Page 29: core java

Java™ Module 1, slide 2 of 23Copyrig

ologyechnology

l Machine

a platform that

ne” and “JVM”platform.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 1, slide 3 of 23Copyrig

mplete programs for

g language? improve on

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 1, slide 4 of 23Copyrig

ogy?

d applications.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

What Is the Java™ Technol

• 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: core java

Java™ Module 1, slide 5 of 23Copyrig

nology

uages

and clear coder:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Primary Goals of the Java Tech

• 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: core java

Java™ Module 1, slide 6 of 23Copyrig

ology

ead of activitye time they are

ally duringate sources

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 1, slide 7 of 23Copyrig

ology

Th

1.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 1, slide 8 of 23Copyrig

e

ons

revelopment tool

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The Java Virtual Machin

• 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: core java

Java™ Module 1, slide 9 of 23Copyrig

JVM

[CPU])

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 1, slide 10 of 23Copyrig

hen the code is

y Suncompliant class

environments.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 1, slide 11 of 23Copyrig

ded should be

rogrammer’s

des alocation.aracteristics:ger needed

plementations

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 1, slide 12 of 23Copyrig

ent

Th s follows:

ser

deer

ter

e

are

e

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 1, slide 13 of 23Copyrig

O -Time (JIT)

e

codeenerator

JIT

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

peration of the JRE With a Just-InCompiler

Compile

TestGreeting.java

TestGreeting.class

Classloader

Bytecodeverifier

Interpreter

Runtime

Hardwar

Runtime

javac

java

g

Load fromhard disk,network,or othersource

Page 41: core java

Java™ Module 1, slide 14 of 23Copyrig

Th

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

JVM™ Tasks

e JVM performs three main tasks:

• Loads code• Verifies code• Executes code

Page 42: core java

Java™ Module 1, slide 15 of 23Copyrig

ution of a

in separate

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The Class Loader

• Loads all classes necessary for the execprogram

• Maintains classes of the local file systemnamespaces

• Prevents spoofing

Page 43: core java

Java™ Module 1, slide 16 of 23Copyrig

En

ion.rity.flows or

code are

sion of integers

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 1, slide 17 of 23Copyrig

n

Th

123456789

Th

12345

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

A Simple Java Applicatio

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: core java

Java™ Module 1, slide 18 of 23Copyrig

tion

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The TestGreetingApplica

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

Page 46: core java

Java™ Module 1, slide 19 of 23Copyrig

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The GreetingClass

• Class declaration• The greet method

Page 47: core java

Java™ Module 1, slide 20 of 23Copyrig

C Greeting

atically.ing command:

rrors.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

ompiling and Running the TestProgram

• 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: core java

Java™ Module 1, slide 21 of 23Copyrig

symbolang.String)ream

estGreetingd

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 1, slide 22 of 23Copyrig

in

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Runtime Errors

• Can’t find class TestGreeting

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

Page 50: core java

Java™ Module 1, slide 23 of 23Copyrig

ronment

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Java Technology Runtime Envi

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: core java

Sun

Java™ Programmi

ming

Services

ng Language

Module 2

Object-Oriented Program

Page 52: core java

Java™ Module 2, slide 2 of 26Copyrig

ncapsulation,

ogy application

onstructor, and

public assulation

ogramming

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 2, slide 3 of 26Copyrig

e analysis and

and code reuse?ing language

language?

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 2, slide 4 of 26Copyrig

0s–Up)soft Windows

penLook

JDBC™

Java

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 MicroMacOS

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: core java

Java™ Module 2, slide 5 of 26Copyrig

ase

ds to do:tors and

t:ractionsstemimplify the

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The Analysis and Design Ph

• 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: core java

Java™ Module 2, slide 6 of 26Copyrig

e used in many

tes and

of objects thats can be usedbehavior

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 2, slide 7 of 26Copyrig

jects

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

e key features:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Classes as Blueprints for Ob

• 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: core java

Java™ Module 2, slide 8 of 26Copyrig

lasses

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Declaring Java Technology C

• 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: core java

Java™ Module 2, slide 9 of 26Copyrig

e>];

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 2, slide 10 of 26Copyrig

t>* ) {

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 2, slide 11 of 26Copyrig

rs

r>

ncluding

s public

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Accessing Object Membe

• 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: core java

Java™ Module 2, slide 12 of 26Copyrig

Th

+

+

+

t access to to a MyDate

ound

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 2, slide 13 of 26Copyrig

Th setters andnal data:

false

e if wrap around

+

+

+

+

+

+

-d

-m

-y

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 2, slide 14 of 26Copyrig

lasscess data

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 2, slide 15 of 26Copyrig

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 2, slide 16 of 26Copyrig

r

in every class.ructors, thecally:umentstyinstances with

onstructor.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The Default Constructo

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

Page 67: core java

Java™ Module 2, slide 17 of 26Copyrig

ort.java file

{...}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 2, slide 18 of 26Copyrig

ystems.ackages.

icle

RiverBarge

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 2, slide 19 of 26Copyrig

t

is:

eginning of the

ce file. is placed into

d separated by

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The packageStatemen

• 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: core java

Java™ Module 2, slide 20 of 26Copyrig

:name>;

g:

ses

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 2, slide 21 of 26Copyrig

ges

containing the

packages.

.class

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Directory Layout and Packa

• 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: core java

Java™ Module 2, slide 22 of 26Copyrig

J

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

DevelopmentavaProjects/

ShippingPrj/

src/

docs/

shipping/

domain/gui/reports/

classes/

shipping/

domain/gui/reports/

Page 73: core java

Java™ Module 2, slide 23 of 26Copyrig

tion

va

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Compiling Using the -dOp

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

Page 74: core java

Java™ Module 2, slide 24 of 26Copyrig

run-time object

;iable, and data

bject;roceduresed to initialize

b-packages

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 2, slide 25 of 26Copyrig

API

HTML) files

s hyperlinks tot package.rarchy, avariables, a list

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Using the Java TechnologyDocumentation

• 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: core java

Sun Services

Java Technology APIDocumentation With HTML3

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

Page 77: core java

Sun

Java™ Programmi

Id Types

Services

ng Language

Module 3

entifiers, Keywords, and

Page 78: core java

Java™ Module 3, slide 2 of 37Copyrig

identifiers

xtual typeseference variable

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 3 of 37Copyrig

variableiables of class

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 4 of 37Copyrig

n variableswith object

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Relevance

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

holding primitive values as compared references?

Page 81: core java

Java™ Module 3, slide 5 of 37Copyrig

Th ava technologypro

// c

/* c* o*/

/** * */

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 6 of 37Copyrig

Space

terminated by

nd by opening

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 7 of 37Copyrig

Space

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 8 of 37Copyrig

Space

in a Java

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 9 of 37Copyrig

Ide

methodcore (_), or

m length

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 10 of 37Copyrig

eywords

Re e

abs switch

ass synchronized

boo this

bre d throw

byt throws

cas transient

cat try

cha void

cla volatile

con while

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Java Programming Language K

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: core java

Java™ Module 3, slide 11 of 37Copyrig

Th t primitivetyp

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 12 of 37Copyrig

Th acteristics:

, true and

n type and

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 booleaassigns it a value of true.

Page 89: core java

Java™ Module 3, slide 13 of 37Copyrig

Th characteristics:

quotes (’ ’)

is replaced with

letter phi [Φ].

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 14 of 37Copyrig

Th aracteristics:

s (" ")

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 15 of 37Copyrig

d long

Th aracteristics:

mal, octal, or

long.

e.

al value.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Integral – byte, short, int, an

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

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: core java

Java™ Module 3, slide 16 of 37Copyrig

d long

ranges:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Integral – byte, short, int, an

• 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: core java

Java™ Module 3, slide 17 of 37Copyrig

ouble

Th ngcha

ecimal point or

ouble)

dant D

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Floating Point – floatand d

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: core java

Java™ Module 3, slide 18 of 37Copyrig

ouble

owing sizes:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Floating Point – floatand d

• 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: core java

Sun 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 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Page 96: core java

Java™ Module 3, slide 20 of 37Copyrig

pes all others

n object.

r) { ... }

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 21 of 37Copyrig

bjects

ing actions:

rformed.

the new

o a variable.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Constructing and Initializing O

• 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: core java

Java™ Module 3, slide 22 of 37Copyrig

out

a reference:

for MyDate:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Memory Allocation and Lay

• 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: core java

Java™ Module 3, slide 23 of 37Copyrig

ion

ttribute

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Explicit Attribute Initializat

• 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: core java

Java™ Module 3, slide 24 of 37Copyrig

or

llows:

r, the first

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Executing the Construct

• 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: core java

Java™ Module 3, slide 25 of 37Copyrig

eference

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 26 of 37Copyrig

nt to two

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 27 of 37Copyrig

ogramminglue. argument to areference to the

d in the callede is never

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 28 of 37Copyrig

123456789101112

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 29 of 37Copyrig

1314151617181920212223

Th

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 30 of 37Copyrig

24252627282930

Th

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 31 of 37Copyrig

3132333435363738

Th

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 32 of 37Copyrig

He

variables and

er to another

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 33 of 37Copyrig

123456789101112131415

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 34 of 37Copyrig

1617181920212223242526

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 35 of 37Copyrig

12345678

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 3, slide 36 of 37Copyrig

Coding

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Java Programming LanguageConventions

• Packages:com.example.domain;

• Classes, interfaces, and enum types:SavingsAccount

• Methods:getAccount()

• Variables:currentCustomer

• Constants:HEAD_COUNT

Page 113: core java

Java™ Module 3, slide 37 of 37Copyrig

Coding

on.

ss members.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Java Programming LanguageConventions

• 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: core java

Sun

Java™ Programmi

ontrol

Services

ng Language

Module 4

Expressions and Flow C

Page 115: core java

Java™ Module 4, slide 2 of 31Copyrig

variablesablesence before

are operatorsssignments of

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 4, slide 3 of 31Copyrig

requirements

d required casts

structions andue as flow

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Objectives

• Identify boolean expressions and theirin control constructs

• Recognize assignment compatibility anin fundamental types

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

Page 117: core java

Java™ Module 4, slide 4 of 31Copyrig

ogrammers?th the same

ed in otherguages use to

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 4, slide 5 of 31Copyrig

Lo

od and arek variableshod is executedd

Va :

ation.atically.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 4, slide 6 of 31Copyrig

epub p

p

} p

}}

pubp

}}

Heap Memory

ScopeExample

i 1

ack

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Variable Scope Exampllic 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 St

Page 120: core java

Java™ Module 4, slide 7 of 31Copyrig

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 4, slide 8 of 31Copyrig

ciple

Th ave beenini

javTest en initialized 1 er

345678910 ation11

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Initialization Before Use Prin

e compiler will verify that local variables htialized before used.

ac 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: core java

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 Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 4, slide 10 of 31Copyrig

e:

:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 4, slide 11 of 31Copyrig

s

0 1

1 1

0 1

0 1

1 1

1 1

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Bitwise Logical Operator

• 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: core java

Java™ Module 4, slide 12 of 31Copyrig

>>>

rator:

ft.rator:. shift.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 4, slide 13 of 31Copyrig

s:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Left-Shift Operator <<

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

Page 127: core java

Java™ Module 4, slide 14 of 31Copyrig

s

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 Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Shift Operator Example

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: core java

Java™ Module 4, slide 15 of 31Copyrig

h +

.bjects

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

String Concatenation Wit

• 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: core java

Java™ Module 4, slide 16 of 31Copyrig

nment, theent with a cast. requires an

a cast

a cast

ger literal

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 4, slide 17 of 31Copyrig

essions

o a longer form

e variable type bits) as the

l

egal

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Promotion and Casting of Expr

• 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: core java

Java™ Module 4, slide 18 of 31Copyrig

nts

Th

if <

Ex

if (Sy

or

if (Sy

}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Simple if, elseStateme

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: core java

Java™ Module 4, slide 19 of 31Copyrig

ents

Th

if <

els<

Ex

if (Sy

} elSy

}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Complex if, elseStatem

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: core java

Java™ Module 4, slide 20 of 31Copyrig

ents

Th

if <

els<

Ex

int sif (Sy ;

} elSy

} elSy

}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Complex if, elseStatem

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: core java

Java™ Module 4, slide 21 of 31Copyrig

Th

swic

c

d

}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 4, slide 22 of 31Copyrig

A s

switca

ca

de

}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 4, slide 23 of 31Copyrig

Th vious example:

switca

ca

de

}

Wi falls througheac

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 4, slide 24 of 31Copyrig

Th

for<

Ex

for Sy

or

for Sy

}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 4, slide 25 of 31Copyrig

Th

whi<

Ex

int whilSyi+

}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 4, slide 26 of 31Copyrig

Th

do<

whi

Ex

intdo {Syi+

} wh

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 4, slide 27 of 31Copyrig

ol

dand, where

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Special Loop Flow Contr

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

<statement> should be a loop

Page 141: core java

Java™ Module 4, slide 28 of 31Copyrig

1234567

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The breakStatement

do {statement;if ( condition ) {break;

}statement;

} while ( test_expr );

Page 142: core java

Java™ Module 4, slide 29 of 31Copyrig

t

1234567

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The continueStatemen

do {statement;if ( condition ) {continue;

}statement;

} while ( test_expr );

Page 143: core java

Java™ Module 4, slide 30 of 31Copyrig

Labels

123456789101112

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Using breakStatements with

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

}statement3;

} while ( test_expr );statement4;

} while ( test_expr );

Page 144: core java

Java™ Module 4, slide 31 of 31Copyrig

th Labels

123456789101112

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Using continueStatements wi

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

}statement3;

} while ( test_expr );statement4;

} while ( test_expr );

Page 145: core java

Sun

Java™ Programmi

Services

ng Language

Module 5

Arrays

Page 146: core java

Java™ Module 5, slide 2 of 15Copyrig

class, or array

nitializedf an arrayn array

ne array to

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 5, slide 3 of 15Copyrig

Wh

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Relevance

at is the purpose of an array?

Page 148: core java

Java™ Module 5, slide 4 of 15Copyrig

es:

new.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 5, slide 5 of 15Copyrig

Us .

For

12345678910

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 5, slide 6 of 15Copyrig

C imitives

ory

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

reating an Array of Character Pr

main

createArray s

this

char[]

A

Execution Stack

Heap Mem

B

C

D

Z

Page 151: core java

Java™ Module 5, slide 7 of 15Copyrig

ys

An

12345678910

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Creating Reference Arra

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: core java

Java™ Module 5, slide 8 of 15Copyrig

C imitives

nt

0

1

Point

x

y

1

2

int

2

3

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 5, slide 9 of 15Copyrig

Strnamnamnamnam

{

MyDdatdatdatdat

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

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 5, slide 10 of 15Copyrig

Ar

int[twoDtwoD

int[

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 5, slide 11 of 15Copyrig

h:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 5, slide 12 of 15Copyrig

All

publfo

}}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 5, slide 13 of 15Copyrig

oop

Jav rsion 5.0int over arrays:

publfo

}}

Th in list do.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Using the Enhanced forL

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: core java

Java™ Module 5, slide 14 of 15Copyrig

e to refer to an

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 5, slide 15 of 15Copyrig

Th rays is:

123456789 h);

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Sun

Java™ Programmi

Services

ng Language

Module 6

Class Design

Page 161: core java

Java™ Module 6, slide 2 of 43Copyrig

ding, overriding,

nd the default

d method

on and

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 3 of 43Copyrig

Ho pport objectinh

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Relevance

w does the Java programming language sueritance?

Page 163: core java

Java™ Module 6, slide 4 of 43Copyrig

Th

";

ls() {...}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 5 of 43Copyrig

Th

";

nt;

ls() {...}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 6 of 43Copyrig

C d Manager

";

ls() {...}

ends Employee {nt;

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

lass Diagrams for EmployeeanUsing 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: core java

Java™ Module 6, slide 7 of 43Copyrig

ss, it is called

le inheritance

s>] {

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 8 of 43Copyrig

cretary

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Single Inheritance

Manager

+department : String = ""

Employee

+name : String = ""

+salary : double

+birthDate : Date

Director

+carAllowance : double

Engineer Se

+getDetails() : String

+increaseAllowance()

Page 168: core java

Java™ Module 6, slide 9 of 43Copyrig

Ac s are listed here.

Mo ass Universe

pri

def

pro

pub Yes

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 10 of 43Copyrig

ed from a

fferent but with the

1.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 11 of 43Copyrig

12345678910

123456789

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 12 of 43Copyrig

e Less

123

123

12345678

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Overridden Methods Cannot BAccessible

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: core java

Java™ Module 6, slide 13 of 43Copyrig

ods

A s ethod using thesup

refer to its

the members ofthods.the superclass;

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Invoking Overridden Meth

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: core java

Java™ Module 6, slide 14 of 43Copyrig

ods

123456789

123456789

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Invoking Overridden Meth

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: core java

Java™ Module 6, slide 15 of 43Copyrig

y differentas access to

of different

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 16 of 43Copyrig

Empl

// e.de// t// e

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 17 of 43Copyrig

n

d as follows:

vocations have

of the declared has a method

based on theManager classtails method.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Virtual Method Invocatio

• 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: core java

Java™ Module 6, slide 18 of 43Copyrig

ns

ss type areple:

ss types aremple:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Heterogeneous Collectio

• 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: core java

Java™ Module 6, slide 19 of 43Copyrig

Bec ing is valid:

publpu

}}

// MTaxSManTaxR

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 20 of 43Copyrig

or

publpublpubl----

publif

}

}

}}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The instanceofOperat

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: core java

Java™ Module 6, slide 21 of 43Copyrig

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 22 of 43Copyrig

bject.y casting.wing

ne implicitly.s and checked

when runtime

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 23 of 43Copyrig

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 24 of 43Copyrig

ments

it multiple

array. For

););

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Methods Using Variable Argu

• 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 anexample:float gradePointAverage = stats.average(4, 3, 4float averageAge = stats.average(24, 32, 27, 18

Page 184: core java

Java™ Module 6, slide 25 of 43Copyrig

rs

verloaded.

e DoB)

irst line of a

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Overloading Constructo

• 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: core java

Java™ Module 6, slide 26 of 43Copyrig

rs

12 0;34567 DoB) {8910111213141516171819

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Overloading Constructo

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: core java

Java™ Module 6, slide 27 of 43Copyrig

ited

iables from the

ctor from the

ors.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Constructors Are Not Inher

• 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: core java

Java™ Module 6, slide 28 of 43Copyrig

uctors

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

s, but does noten a compiler

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Invoking Parent Class Constr

• 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: core java

Java™ Module 6, slide 29 of 43Copyrig

uctors

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

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Invoking Parent Class Constr

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: core java

Java™ Module 6, slide 30 of 43Copyrig

C ts: A Slight

Me occurs.

Ins s recursively:

then skip to

t super call,

initializers.ructor.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

onstructing and Initializing ObjecReprise

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: core java

Sun 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 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Page 191: core java

Java™ Module 6, slide 32 of 43Copyrig

xamples

0 Ba 0. 0.1 C 1. 1. 1. ull

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Constructor and Initialization E

sic initialization1 Allocate memory for the completeManager object2 Initialize all instance variables to their default values (0 ornull)

all constructor:Manager("Joe Smith", "Sales")1 Bind constructor parameters:n="Joe Smith", d="Sales"2 No explicitthis() call3 Callsuper(n) forEmployee(String)1.3.1 Bind constructor parameters:n="Joe Smith"1.3.2 Callthis(n, null) forEmployee(String, Date) 1.3.2.1 Bind constructor parameters:n="Joe Smith", DoB=n 1.3.2.2 No explicitthis() call 1.3.2.3 Callsuper() forObject() 1.3.2.3.1 No binding necessary 1.3.2.3.2 Nothis() call 1.3.2.3.3 Nosuper() call(Object is the root) 1.3.2.3.4 No explicit variable initialization forObject 1.3.2.3.5 No method body to call

Page 192: core java

Java™ Module 6, slide 33 of 43Copyrig

xamples

0; 1. 1.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Constructor and Initialization E

1.3.2.4 Initialize explicit Employee variables:salary=15000.0 1.3.2.5 Execute body:name="Joe Smith"; date=null;1.3.3 - 1.3.4 Steps skipped1.3.5 Execute body: No body inEmployee(String)4 No explicit initializers forManager5 Execute body:department="Sales"

Page 193: core java

Java™ Module 6, slide 34 of 43Copyrig

s in Java.ause implies

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 35 of 43Copyrig

rences arehe same object).ts are equal but

als method

ethod touality.emethod if you

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 36 of 43Copyrig

12345678910

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 37 of 43Copyrig

1112131415161718192021222324252627

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 38 of 43Copyrig

1234567 e2");89 date2");10111213 ;1415 e2");16

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 39 of 43Copyrig

171819202122 e2");2324 date2");252627

Th

datedateset date

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 40 of 43Copyrig

Th acteristics:

ing.ation.ation about a

c method to

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 41 of 43Copyrig

Lo

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 42 of 43Copyrig

An

int Inte oxingint

Oth

int int

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 6, slide 43 of 43Copyrig

pes

Au

ject equivalent

xingg

n dealing with

metic

ng

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Autoboxing of Primitive Ty

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: core java

Sun

Java™ Programmi

res

Services

ng Language

Module 7

Advanced Class Featu

Page 204: core java

Java™ Module 7, slide 2 of 44Copyrig

itializersbles

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 3 of 44Copyrig

by all instances

om being

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 4 of 44Copyrig

ier on variables,

bute or methodather than any

ass members,

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 5 of 44Copyrig

Cla s of a class:

123456789

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 6 of 44Copyrig

If t

12345678

it c out an instance:

12345

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 7 of 44Copyrig

You

12345678910111213

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 8 of 44Copyrig

You instance of thecla

123456789

Th

NumbNumb

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 9 of 44Copyrig

Sta es:

12345678

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 10 of 44Copyrig

that does not

hen the class is

ze static (class)

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 11 of 44Copyrig

1234 ter").intValue();56

123 );45

Th is:

javacoun

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 12 of 44Copyrig

, but thatthe declaration;

t be set in every

be set in the

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 13 of 44Copyrig

Co

publpr 3.2;..

}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Final Variables

nstants are static final variables.

ic class Bank {ivate static final double DEFAULT_INTEREST_RATE = . // more declarations

Page 216: core java

Java™ Module 7, slide 14 of 44Copyrig

12345678910111213141516171819

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 15 of 44Copyrig

Idiom

En gramming.1234567891011121314151617

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Old-Style Enumerated Type

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: core java

Java™ Module 7, slide 16 of 44Copyrig

Idiom2223242526272829303132333435363738394041

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Old-Style Enumerated Type} 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: core java

Java™ Module 7, slide 17 of 44Copyrig

Idiom

Old123456789 ;10 ank()11 ());1213 uit.1415 ank()16 ());1718

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Old-Style Enumerated Type

-style idiom is not type-safe:0

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.getR + “ of “ + card1.getSuitName

// You can create a playing card with a bogus s PlayingCard card2 = new PlayingCard(47, 2); System.out.println(“card2 is the “ + card2.getR + “ of “ + card2.getSuitName }}

Page 220: core java

Java™ Module 7, slide 18 of 44Copyrig

Idiom

Th lems:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Old-Style Enumerated Type

is enumerated type idiom has several prob

• Not type-safe• No namespace• Brittle character• Uninformative printed values

Page 221: core java

Java™ Module 7, slide 19 of 44Copyrig

pe

No es:12345678

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The New Enumerated Ty

w you can create type-safe enumerated typ0

package cards.domain;

public enum Suit { SPADES, HEARTS, CLUBS, DIAMONDS}

Page 222: core java

Java™ Module 7, slide 20 of 44Copyrig

pe

Us123456789101112131415

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The New Enumerated Ty

ing enumerated types is easy:0

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: core java

Java™ Module 7, slide 21 of 44Copyrig

e161718192021222324252627282930313233343536

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The New Enumerated Typ 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: core java

Java™ Module 7, slide 22 of 44Copyrig

pe

En1234567891011 ank()12 ());1314151617

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The New Enumerated Ty

umerated types are type-safe:0

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: core java

Java™ Module 7, slide 23 of 44Copyrig

pes

En thods:123456789101112131415161718

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Advanced Enumerated Ty

umerated types can have attributes and me0

package 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: core java

Java™ Module 7, slide 24 of 44Copyrig

pes

Pu ssible:1234567891011 ank()12 etName());1314 , 2);151617

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Advanced Enumerated Ty

blic methods on enumerated types are acce0

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: core java

Java™ Module 7, slide 25 of 44Copyrig

ers from a class:er_name>;

idually or

nstants:;

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 26 of 44Copyrig

An12345678910 ank()11 etName());1213 , 2);141516

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Static Imports

example of a static import is:0

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: core java

Java™ Module 7, slide 27 of 44Copyrig

Th this:

hicle

RiverBarge

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Abstract Classes

e design of the Shipping system looks like

Ve

Truck

Companyfleet

0..*

shipping

domainShippingMain «Uses»

FuelNeedsReport «Uses»

reports

Page 230: core java

Java™ Module 7, slide 28 of 44Copyrig

Fle

12345 s6789101112 ;131415

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 29 of 44Copyrig

12345678910111213 + ) {1415

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 30 of 44Copyrig

1617 fficency();1819 eeds "20212223 uel + " liters.");2425

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 31 of 44Copyrig

An hich the fullim by the concretesub

e

() : double

: double

: double)

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 32 of 44Copyrig

Th

1234

Th n:

1234 a given load */567 ay */89

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 33 of 44Copyrig

Lik nim

1234 ge */567 e river-ways */89

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 34 of 44Copyrig

lient code and.such a contractentation.

the same

interfaces.

s>]face>]* ] {

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 35 of 44Copyrig

publpupupu

}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 36 of 44Copyrig

publpu

}pu

}pu

}}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 37 of 44Copyrig

)

an

ding()

et()

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 38 of 44Copyrig

Kryptonian

eOff()

d()

()

perman

pBuilding()

pBullet()

()

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 39 of 44Copyrig

publpu */ }pu */ }pu */ }pu */ }pu */ }pu */ }

}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 40 of 44Copyrig

Kryptonian

takeOff()

land()

fly()

Superman

leapBuilding()

stopBullet()

eat()

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 41 of 44Copyrig

publpu

}

pr

}}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 7, slide 42 of 44Copyrig

le

keOff()

nd()

y()

interface»

Flyer

ff()

)

lane

Helicopter

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Multiple Interface Examp

+ta

+la

+fl

«

+takeO

+land(

+fly()

Airp

+dock()

+cruise()

«interface»

Sailer

SeaPlane

+dock()

+cruise()

Vehicle

RiverBarge

+dock()

+cruise()

Page 245: core java

Java™ Module 7, slide 43 of 44Copyrig

le

publpu

}

pr

}}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Multiple Interface Examp

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: core java

Java™ Module 7, slide 44 of 44Copyrig

Int

sses are

interfacee classed classes

laring a class

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Sun

Java™ Programmi

ons

Services

ng Language

Module 8

Exceptions and Asserti

Page 248: core java

Java™ Module 8, slide 2 of 25Copyrig

ts

exceptions

iate uses of

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 8, slide 3 of 25Copyrig

do you resolve

y your codeng, what might

pend CPU programs?

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 8, slide 4 of 25Copyrig

ns

ns – Illegaloundming here from code atn at all.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Exceptions and Assertio

• 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: core java

Java™ Module 8, slide 5 of 25Copyrig

orrect program

on class.ted as fatal or bugs are

Error class.

exceptions that

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 8, slide 6 of 25Copyrig

123456789

javSum

javExce r input string: "two"

matException.java:48)

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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); }}

a AddArguments 1 2 3 4= 10

a 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: core java

Java™ Module 8, slide 7 of 25Copyrig

nt

1234567891011 eger.");121314

javOne

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The try-catchStateme

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}

}}

a AddArguments2 1 two 3.0 4of the command-line arguments is not an integer.

Page 254: core java

Java™ Module 8, slide 8 of 25Copyrig

nt

12345678 integer"9 uded in the sum.");1011121314

jav[two sum.[3.0 sum.Sum

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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); }}

a 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: core java

Java™ Module 8, slide 9 of 25Copyrig

nt

A t h clauses:

try //

} ca// wn

} ca// thrown

} ca//

}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 8, slide 10 of 25Copyrig

rent try-catchethod.thod and is not

ed abnormally.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 8, slide 11 of 25Copyrig

Th at alwaysexe

12345678

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The finallyClause

e finally clause defines a block of code thcutes.

try { startFaucet(); waterLawn();} catch (BrokenPipeException e) {

logProblem(e); } finally { stopFaucet();}

Page 258: core java

Java™ Module 8, slide 12 of 25Copyrig

icException

terException

rgumentException

ception

rflowError

oryError

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Exception Categories

Throwable

Error

Exception

RuntimeException

IOException

Arithmet

NullPoin

IllegalA

FileNotFoundEx

VirtualMachineError

AssertionError

StackOve

OutOfMem

EOFException

SQLException

Page 259: core java

Java™ Module 8, slide 13 of 25Copyrig

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Common Exceptions

• NullPointerException

• FileNotFoundException

• NumberFormatException

• ArithmeticException

• SecurityException

Page 260: core java

Java™ Module 8, slide 14 of 25Copyrig

le

Us

on by using the

on { ... }

Oth

eptions or

ptions.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The Handle or Declare Ru

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: core java

Java™ Module 8, slide 15 of 25Copyrig

ptions

Th

by the

s thrown by the

Th

e overridden

by the

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Method Overriding and Exce

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: core java

Java™ Module 8, slide 16 of 25Copyrig

tions

12345

12345

12 G345

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 8, slide 17 of 25Copyrig

ions

1 ception {234 t port) {56789101112

Us the Exceptioncla n was made.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Creating Your Own Except

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: core java

Java™ Module 8, slide 18 of 25Copyrig

eption

A m exception:

123456789 t connect",10 nect);1112

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Handling a User-Defined Exc

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: core java

Java™ Module 8, slide 19 of 25Copyrig

eption

An o captureuse

12345 alternative");6789 e() +10 e1.getPort());111213

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 8, slide 20 of 25Copyrig

ssion> ;

false, then an

string and usedror message.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Assertions

• Syntax of an assertion is:assert <boolean_expression> ;assert <boolean_expression> : <detail_expre

• If <boolean_expression> evaluatesAssertionError is thrown.

• The second argument is converted to aas descriptive text in the AssertionEr

Page 267: core java

Java™ Module 8, slide 21 of 25Copyrig

rtions

Us umptions andint

Ina

meters of a

eck that can

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Recommended Uses of Asse

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: core java

Java™ Module 8, slide 22 of 25Copyrig

Th

12345

Th

123456

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 8, slide 23 of 25Copyrig

For

12345678910 d suit";1112

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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: core java

Java™ Module 8, slide 24 of 25Copyrig

riants

For

1234 empty stack");567 ement */ ;8910111213

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Postconditions and Class Inva

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: core java

Java™ Module 8, slide 25 of 25Copyrig

C Assertions

e runs as fast as

lt. Enables:

class, package,

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

ontrolling Runtime Evaluation of

• 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: core java

Sun

Java™ Programmi

ns

Services

ng Language

Module 9

Text-Based Applicatio

Page 273: core java

Java™ Module 9, slide 2 of 37Copyrig

ne arguments

rd inputd outputnd write filesns in the Java 2)

tionctions

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Objectives

• Write a program that uses command-liand system properties

• Write a program that reads from standa• Describe the C-type formatted input an• Write a program that can create, read, a• Describe the basic hierarchy of collectio

Software Development Kit (Java 2 SDK• Write a program that uses sets and lists• Write a program to iterate over a collec• Write a program that uses generic colle

Page 274: core java

Java™ Module 9, slide 3 of 37Copyrig

of a programnames or the

be coded to

collections (thatava technologyollections?ents of any

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Relevance

• It is often the case that certain elementsshould not be hard-coded, such as file name of a database. How can a programsupply these elements at runtime?

• Simple arrays are far too static for mostis, a fixed number of elements). What Jfeatures exist to support more flexible c

• Besides computation, what are key elemtext-based application?

Page 275: core java

Java™ Module 9, slide 4 of 37Copyrig

ts

se

he commandthe class name:

in the argsethod:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Command-Line Argumen

• 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 276: core java

Java™ Module 9, slide 5 of 37Copyrig

s

1234 rgs[i] + "’");567

Ex

javargsargsargs

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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:

a TestArgs arg1 arg2 "another arg"[0] is ’arg1’[1] is ’arg2’[2] is ’another arg’

Page 277: core java

Java™ Module 9, slide 6 of 37Copyrig

laces the are

eturns a

ringoperty.perty.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 to include a new pro

Page 278: core java

Java™ Module 9, slide 7 of 37Copyrig

pping of names

Enumeration

ringoperty.s collection into

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 279: core java

Java™ Module 9, slide 8 of 37Copyrig

12345678910 ent();11 ;1213 ");141516

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The PropertiesClass

import java.util.Properties;import java.util.Enumeration;

public class TestProperties { public static void main(String[] args) { Properties props = System.getProperties(); Enumeration propNames = props.propertyNames();

while ( propNames.hasMoreElements() ) { String propName = (String) propNames.nextElem String property = props.getProperty(propName) System.out.println("property ’" + propName

+ "’ is ’" + property + "’ } }}

Page 280: core java

Java™ Module 9, slide 9 of 37Copyrig

He

jav

He

propproppropproppropprop ms Inc.’proppropprop

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The PropertiesClass

re is an example test run of this program:

a -DmyProp=theValue TestProperties

re is the (partial) output:

erty ’java.version’ is ’1.5.0-rc’erty ’java.compiler’ is ’NONE’erty ’path.separator’ is ’:’erty ’file.separator’ is ’/’erty ’user.home’ is ’/home/basham’erty ’java.specification.vendor’ is ’Sun Microsysteerty ’user.language’ is ’en’erty ’user.name’ is ’basham’erty ’myProp’ is ’theValue’

Page 281: core java

Java™ Module 9, slide 10 of 37Copyrig

o write to

read from

o write to

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Console I/O

• The variable System.out enables you tstandard output.It is an object of type PrintStream.

• The variable System.in enables you tostandard input.It is an object of type InputStream.

• The variable System.err enables you tstandard error.It is an object of type PrintStream.

Page 282: core java

Java™ Module 9, slide 11 of 37Copyrig

ut

ent and a

t without a

verloaded fornt, long,ject, and

ect) methodsent.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Writing to Standard Outp

• 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 283: core java

Java™ Module 9, slide 12 of 37Copyrig

put

123456789101112 +13 xit");

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Reading From Standard In

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 284: core java

Java™ Module 9, slide 13 of 37Copyrig

ut

1415 reen.161718192021222324 tions.25262728

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 285: core java

Java™ Module 9, slide 14 of 37Copyrig

t

y as follows

l);

this table.

Co

%s ling the

%d cimal value.

%f es scientific

%n .

%%

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Simple Formatted Outpu

• 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 286: core java

Java™ Module 9, slide 15 of 37Copyrig

t

input function.ut streams as

m);

ue);

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Simple Formatted Inpu

• The Scanner API provides a formatted • A Scanner can be used with console inp

well as file or network streams.• 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 287: core java

Java™ Module 9, slide 16 of 37Copyrig

Th ollowing:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 288: core java

Java™ Module 9, slide 17 of 37Copyrig

ect

Th

;

file.txt");

Dir e File classsup les in thedir

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Creating a New FileObj

e File class provides several utilities:

• File myFile;

• myFile = new File("myfile.txt")

• myFile = new File("MyDocs", "my

ectories are treated just like files in Java; thports methods for retrieving an array of fi

ectory, as follows:

File myDir = new File("MyDocs");myFile = new File(myDir, "myfile.txt");

Page 289: core java

Java™ Module 9, slide 18 of 37Copyrig

es

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The FileTests and Utiliti

• 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 290: core java

Java™ Module 9, slide 19 of 37Copyrig

s

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The FileTests and Utilitie

• File tests:boolean exists()boolean canWrite()boolean canRead()boolean isFile()boolean isDirectory()boolean isAbsolute();

Page 291: core java

Java™ Module 9, slide 20 of 37Copyrig

aracters.e the readLine

haracters.e print and

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 292: core java

Java™ Module 9, slide 21 of 37Copyrig

A fi

12345678910111213

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

File Stream I/O

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 293: core java

Java™ Module 9, slide 22 of 37Copyrig

14 o the screen.1516171819202122232425 ;26272829303132

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

File Stream I/O

// 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 294: core java

Java™ Module 9, slide 23 of 37Copyrig

123456789 from standard in.1011121314151617

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 295: core java

Java™ Module 9, slide 24 of 37Copyrig

1819202122 reen.2324252627 nt writer.282930313233343536

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 296: core java

Java™ Module 9, slide 25 of 37Copyrig

g a group of

that group

lled elements; allowance ofmentationuplicates are

ates are

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The Collections API

• A collection is a single object representinobjects known as its elements.

• The Collections API contains interfacesobjects as one of the following:• Collection – A group of objects ca

any specific ordering (or lack of) andduplicates is specified by each imple

• Set – An unordered collection; no dpermitted

• List – An ordered collection; duplicpermitted

Page 297: core java

Java™ Module 9, slide 26 of 37Copyrig

st

Object)t

ject) intor

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The Collections API

Collection«interface»

Set«interface»

List«interface»

HashSet

ArrayList LinkedLi

+add(element : Object) : boolean

+size() : int+remove(element : Object) : boolean

+isEmpty() : boolean+contains(element : Object) : boolean+iterator() : Iterator

+add(index : int, element :

+get(index : int) : Object+remove(index : int) : Objec

+set(index : int, element Ob+indexOf(element : Object) :+listIterator() : ListIterat

Page 298: core java

Java™ Module 9, slide 27 of 37Copyrig

1234567891011 dded12 dded131415

Th

[one

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 299: core java

Java™ Module 9, slide 28 of 37Copyrig

1234567891011 dded12 dded131415

Th

[one

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 300: core java

Java™ Module 9, slide 29 of 37Copyrig

n 1.1

Co ™) include:

interface. and supports

ap interface.n on the

ementsble.

heavy weight.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Collections in JDK™ Versio

llections in the Java Development Kit (JDK

• The class Vector implements the List• The class Stack is a subclass of Vector

the push, pop, and peek methods.• The class Hashtable implements the M• The Enumeration interface is a variatio

Iterator interface.An enumeration is returned by the elmethod in Vector, Stack, and Hashta

• Classes are thread-safe, and therefore,• These classes also support generics.

Page 301: core java

Java™ Module 9, slide 30 of 37Copyrig

Ge

Be

Arralistint

Aft

Arralistint

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Generics

nerics are described as follows:

• Provides compile-time type safety• Eliminates the need for casts

fore Generics

yList list = new ArrayList();.add(0, new Integer(42));total = ((Integer)list.get(0)).intValue();

er Generics

yList<Integer> list = new ArrayList<Integer>();.add(0, new Integer(42));total = list.get(0).intValue();

Page 302: core java

Java™ Module 9, slide 31 of 37Copyrig

I

t<E>

E)

or<E>

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Generic Collections APCollection<E>

«interface»

Set<E>«interface»

List<E>«interface»

HashSet<E>

ArrayList<E> LinkedLis

+add(element : E) : boolean

+size() : int+remove(element : E) : boolean

+isEmpty() : boolean+contains(element : E) : boolean+iterator() : Iterator<E>

+add(index : int, element :

+get(index : int) : E+remove(index : int) : E

+set(index : int, element E)+indexOf(element : E) : int+listIterator() : ListIterat

Page 303: core java

Java™ Module 9, slide 32 of 37Copyrig

javaNote rations.Note

javaGene call to add(int,E)as a 1 wa

12345678

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Compiler Warnings

c GenericsWarning.java: GenericsWarning.java uses unchecked or unsafe ope: Recompile with -Xlint:unchecked for details.

c -Xlint:unchecked GenericsWarning.javaricsWarning.java:7: warning: [unchecked] unchecked member of the raw type java.util.ArrayListlist.add(0, new Integer(42)); ^rning

0

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(); }}

Page 304: core java

Java™ Module 9, slide 33 of 37Copyrig

ry element in a

ned forwards (using the

List// aIterwhilSy

}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Iterators

• Iteration is the process of retrieving evecollection.

• An Iterator of a Set is unordered.• A ListIterator of a List can be scan

(using the next method) or backwardsprevious method).

list = new ArrayList();dd some elementsator elements = list.iterator();e ( elements.hasNext() ) {stem.out.println(elements.next());

Page 305: core java

Java™ Module 9, slide 34 of 37Copyrig

rchy

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The Iterator Interface Hiera

Iterator<E>«interface»

ListIterator<E>«interface»

+hasNext() : boolean+next() : E+remove()

+hasPrevious() : boolean+previous() : E+add(element : E)+set(element : E)

Page 306: core java

Java™ Module 9, slide 35 of 37Copyrig

Th racteristics:

Ite

loop. to go wrong.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

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 307: core java

Java™ Module 9, slide 36 of 37Copyrig

An

.hasNext() ; ){

:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Enhanced forLoop

enhanced for loop can look like this:

• Using iterators:public void deleteAll(Collection<NameList> c){for ( Iterator<NameList> i = c.iterator() ; iNameList nl = i.next();nl.deleteItem();

}}

• Using enhanced for loop in collectionspublic void deleteAll(Collection<NameList> c){for ( NameList nl : c ){nl.deleteItem();

}}

Page 308: core java

Java™ Module 9, slide 37 of 37Copyrig

ps:

();

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Enhanced forLoop

• Using enhanced for loop in arrays:public int sum(int[] array){int result = 0;for ( int element : array ) {result += element;

}return result;

}

• Using enhanced for loop in nested looList<Subject> subjects=...;List<Teacher> teachers=...;List<Course> courseList = new ArrayList<Course>for ( Subject subj : subjects ) {for ( Teacher tchr : teachers ) {courseList.add(new Course(subj, tchr));

}}

Page 309: core java

Sun

Java™ Programmi

Services

ng Language

Module 10

Building Java GUIs

Page 310: core java

Java™ Module 10, slide 2 of 37Copyrig

AWT)package

, and layouttogether to

nd GridLayout layout

propriatelysted containers

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Objectives

• Describe the Abstract Window Toolkit (and its components

• Define the terms containers, componentsmanagers, and describe how they work build a GUI

• Use layout managers• Use the FlowLayout, BorderLayout, a

managers to achieve a desired dynamic• Add components to a container• Use the Frame and Panel containers ap• Describe how complex layouts with ne

work

Page 311: core java

Java™ Module 10, slide 3 of 37Copyrig

As guage, how isJav ser interface(GU

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Relevance

a platform-independent programming lana technology used to make the graphical uI) platform-independent?

Page 312: core java

Java™ Module 10, slide 4 of 37Copyrig

t

Th

d in all Java

or extended;

is displayed onlass Component

bclass ofs:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Abstract Window Toolki

e AWT performs the following:

• Provides GUI components that are useapplets and applications

• Contains classes that can be composed classes can also be abstract

• Ensures that every GUI component thatthe screen is a subclass of the abstract cor MenuComponent

• Has Container, which is an abstract suComponent and includes two subclasse• Panel

• Window

Page 313: core java

Sun Services

The java.awtPackage

java.lang.Object

ButtonCanvasCheckboxChoiceContainerLabelListScrollbarTextComponent

BorderLayoutCardLayoutCheckboxGroupColorEventFontFlowLayoutFontMetricsGraphicsGridBagLayoutGridLayoutImageInsetsPointPolygonRectangleToolkitMenuComponentComponent

MenuBarMenuItem Menu -- PopupMenu

CheckboxMenuItem

TextAreaTextField

PanelWindowScrollPane

DialogFrame

Applet (java.applet package)

FileDialog

Exceptions – AWTException Errors – AWTError

java.awt.geom.Dimension2D

java.lang.Object

Dimension

Java™ Programming Language Module 10, slide 5 of 37Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Page 314: core java

Java™ Module 10, slide 6 of 37Copyrig

od.indow and

the display.nts that must

iner, such as a

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Containers

• Add components with the add() meth• The two main types of containers are W

Panel.• A Window is a free floating window on • A Panel is a container of GUI compone

exist in the context of some other contawindow or applet.

Page 315: core java

Java™ Module 10, slide 7 of 37Copyrig

s

n a container is

omponents by

etSize(), orthem in the

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Positioning Component

• The position and size of a component idetermined by a layout manager.

• You can control the size or position of cdisabling the layout manager.You must then use setLocation(), ssetBounds() on components to locatecontainer.

Page 316: core java

Java™ Module 10, slide 8 of 37Copyrig

Fra

(true) to

out managerhe default

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Frames

mes have the following characteristics:

• Are a subclass of Window• Have title and resizing corners• Are invisible initially; use setVisible

expose the frame• Have BorderLayout as the default lay• Use the setLayout method to change t

layout manager

Page 317: core java

Java™ Module 10, slide 9 of 37Copyrig

s

12345678910111213141516171819

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The FrameExampleClas

import java.awt.*;

public class FrameExample { private Frame f; public FrameExample() { f = new Frame("Hello Out There!"); }

public void launchFrame() { f.setSize(170,170); f.setBackground(Color.blue); f.setVisible(true); }

public static void main(String args[]) { FrameExample guiWindow = new FrameExample(); guiWindow.launchFrame(); }}

Page 318: core java

Java™ Module 10, slide 10 of 37Copyrig

dows

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Example Frame

Solaris OS Microsoft Win

Page 319: core java

Java™ Module 10, slide 11 of 37Copyrig

.n layout

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Panels

• Panels provide a space for components• This enables subpanels to have their ow

manager.

Page 320: core java

Java™ Module 10, slide 12 of 37Copyrig

ss

12345678910

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The FrameWithPanelCla

import java.awt.*;

public class FrameWithPanel { private Frame f;private Panel pan;

public FrameWithPanel(String title) { f = new Frame(title);

pan = new Panel();}

Page 321: core java

Java™ Module 10, slide 13 of 37Copyrig

s

111213141516171819202122232425262728

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The FrameWithPanelClas

public void launchFrame() { f.setSize(200,200); f.setBackground(Color.blue); f.setLayout(null); // Use default layout

pan.setSize(100,100); pan.setBackground(Color.yellow); f.add(pan); f.setVisible(true); }

public static void main(String args[]) { FrameWithPanel guiWindow = new FrameWithPanel("Frame with Panel"); guiWindow.launchFrame(); }}

Page 322: core java

Java™ Module 10, slide 14 of 37Copyrig

indows

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Example Panel

Solaris OSMicrosoft W

Page 323: core java

Java™ Module 10, slide 15 of 37Copyrig

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Layout Managers

• FlowLayout

• BorderLayout

• GridLayout

• CardLayout

• GridBagLayout

Page 324: core java

Java™ Module 10, slide 16 of 37Copyrig

s

ut

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Default Layout Manager

Component

Container

Window

Frame Dialog

BorderLayout

Panel

Applet

FlowLayo

Page 325: core java

Java™ Module 10, slide 17 of 37Copyrig

ple

123456789101112

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

A Simple FlowLayoutExam

import java.awt.*;

public class LayoutExample { private Frame f; private Button b1; private Button b2;

public LayoutExample() { f = new Frame("GUI example"); b1 = new Button("Press Me"); b2 = new Button("Don’t press Me"); }

Page 326: core java

Java™ Module 10, slide 18 of 37Copyrig

ple

131415161718192021222324252627

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

A Simple FlowLayoutExam

public void launchFrame() { f.setLayout(new FlowLayout()); f.add(b1); f.add(b2); f.pack(); f.setVisible(true); }

public static void main(String args[]) { LayoutExample guiWindow = new LayoutExample(); guiWindow.launchFrame(); }

} // end of LayoutExample class

Page 327: core java

Java™ Module 10, slide 19 of 37Copyrig

dows

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Example of FlowLayout

Solaris OS Microsoft Win

Page 328: core java

Java™ Module 10, slide 20 of 37Copyrig

er

Th haracteristics:

class

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The FlowLayoutManag

e FlowLayout manager has the following c

• Forms the default layout for the Panel• Adds components from left to right• Alignment default is centered• Uses components’ preferred sizes• Uses the constructor to tune behavior

Page 329: core java

Java™ Module 10, slide 21 of 37Copyrig

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The FlowLayoutResizing

Solaris OS

After user orprogram resizes

Page 330: core java

Java™ Module 10, slide 22 of 37Copyrig

s

1234567891011121314

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The FlowExampleClas

import java.awt.*;

public class FlowExample { private Frame f; private Button button1; private Button button2; private Button button3;

public FlowExample() { f = new Frame("Flow Layout"); button1 = new Button("Ok"); button2 = new Button("Open"); button3 = new Button("Close"); }

Page 331: core java

Java™ Module 10, slide 23 of 37Copyrig

151617181920212223242526272829

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The FlowExampleClass

public void launchFrame() { f.setLayout(new FlowLayout()); f.add(button1); f.add(button2); f.add(button3); f.setSize(100,100); f.setVisible(true); }

public static void main(String args[]) { FlowExample guiWindow = new FlowExample(); guiWindow.launchFrame(); }}

Page 332: core java

Java™ Module 10, slide 24 of 37Copyrig

ger

ult layout for

ns.

just

t vertically

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The BorderLayoutMana

• The BorderLayout manager is the defathe Frame class.

• Components are added to specific regio• The resizing behavior is as follows:

• North, South, and Center regions adhorizontally

• East, West, and Center regions adjus

Page 333: core java

Java™ Module 10, slide 25 of 37Copyrig

ayout

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Organization of the Border LComponents

North

South

Eas

t

Wes

t

Center

Page 334: core java

Java™ Module 10, slide 26 of 37Copyrig

ss

1234567891011121314

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The BorderExampleCla

import java.awt.*;

public class BorderExample { private Frame f; private Button bn, bs, bw, be, bc;

public BorderExample() { f = new Frame("Border Layout"); bn = new Button("B1"); bs = new Button("B2"); bw = new Button("B3"); be = new Button("B4"); bc = new Button("B5"); }

Page 335: core java

Java™ Module 10, slide 27 of 37Copyrig

s

15161718192021222324252627282930

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The BorderExampleClas

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(200,200); f.setVisible(true); }

public static void main(String args[]) { BorderExample guiWindow2 = new BorderExample(); guiWindow2.launchFrame(); }}

Page 336: core java

Java™ Module 10, slide 28 of 37Copyrig

t

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Example of BorderLayou

Solaris OS

After user orprogram resizes

Page 337: core java

Java™ Module 10, slide 29 of 37Copyrig

er

t, and from top

columns.

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The GridLayoutManag

• Components are added from left to righto bottom.

• All regions are sized equally.• The constructor specifies the rows and

Page 338: core java

Java™ Module 10, slide 30 of 37Copyrig

s

123456789101112131415

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The GridExampleClas

import java.awt.*;

public class GridExample { private Frame f; private Button b1, b2, b3, b4, b5, b6;

public GridExample() { f = new Frame("Grid Example"); b1 = new Button("1"); b2 = new Button("2"); b3 = new Button("3"); b4 = new Button("4"); b5 = new Button("5"); b6 = new Button("6"); }

Page 339: core java

Java™ Module 10, slide 31 of 37Copyrig

161718192021222324252627282930313233

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The GridExampleClass

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.add(b6);

f.pack(); f.setVisible(true); }

public static void main(String args[]) { GridExample grid = new GridExample(); grid.launchFrame(); }}

Page 340: core java

Java™ Module 10, slide 32 of 37Copyrig

ows

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Example of GridLayout

Solaris OS

Microsoft Wind

After user orprogram resizes

After user orprogram resizes

Page 341: core java

Java™ Module 10, slide 33 of 37Copyrig

Class

123456789101112131415

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The ComplexLayoutExample

import java.awt.*;

public class ComplexLayoutExample { private Frame f; private Panel p; private Button bw, bc; private Button bfile, bhelp;

public ComplexLayoutExample() { f = new Frame("GUI example 3"); bw = new Button("West"); bc = new Button("Work space region"); bfile = new Button("File"); bhelp = new Button("Help"); }

Page 342: core java

Java™ Module 10, slide 34 of 37Copyrig

lass

1617181920 rder2122232425262728293031 mple();323334

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The ComplexLayoutExampleC

public void launchFrame() { // Add bw and bc buttons in the frame border f.add(bw, BorderLayout.WEST); f.add(bc, BorderLayout.CENTER); // Create panel for the buttons in the north bo p = new Panel(); p.add(bfile); p.add(bhelp); f.add(p, BorderLayout.NORTH); // Pack the frame and make it visible f.pack(); f.setVisible(true); }

public static void main(String args[]) { ComplexLayoutExample gui = new ComplexLayoutExa gui.launchFrame(); }}

Page 343: core java

Java™ Module 10, slide 35 of 37Copyrig

rs

aris OS

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Combining Layout Manage

Sol

After user orprogram resizes

Page 344: core java

Java™ Module 10, slide 36 of 37Copyrig

ugh AWT just for this

sorPaneland

the componentow overlapped.

ct.drawing

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Drawing in AWT

• You can draw in any Component (althoprovides the Canvas and Panel classespurpose).

• Typically, you create a subclass ofCanvaoverride the paint method.

• The paintmethod is called every timeis shown (for example, if another windthe component and was then removed)

• Every component has a Graphics obje• The Graphics class implements many

methods.

Page 345: core java

Java™ Module 10, slide 37 of 37Copyrig

raphics

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Various Shapes Drawn by the GObject

Page 346: core java

Sun

Java™ Programmi

Services

ng Language

Module 11

GUI Event Handling

Page 347: core java

Java™ Module 11, slide 2 of 22Copyrig

in a GUI, including how

ed the event

ce for a variety

ethods for a

anonymous

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Objectives

• Define events and event handling• Write code to handle events that occur • Describe the concept of adapter classes

and when to use them• Determine the user action that originat

from the event object details• Identify the appropriate listener interfa

of event types• Create the appropriate event handler m

variety of event types• Understand the use of inner classes and

classes in event handling

Page 348: core java

Java™ Module 11, slide 3 of 22Copyrig

ke it useful?mouse click or

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Relevance

• What parts of a GUI are required to ma• How does a graphical program handle a

any other type of user interaction?

Page 349: core java

Java™ Module 11, slide 4 of 22Copyrig

penedents an event

ser’s interaction

vent e) {

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 uFrame

Panel

Button

The user clicks on the button

Some Event HandleractionPerformed(ActionE ...}

ActionEvent

Page 350: core java

Java™ Module 11, slide 5 of 22Copyrig

ndlers.

ts when theyat component.

vent e) {

vent e) {

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Delegation Model

• An event can be sent to many event ha

• Event handlers register with componenare interested in events generated by th

Frame

Panel

Button

The user clicks on the button

Another Event Handler

One Event Handler

actionPerformed(ActionE ...}

actionPerformed(ActionE ...}ActionEvent

Page 351: core java

Java™ Module 11, slide 6 of 22Copyrig

GUI

lers for the type

n one type of

ork among

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Delegation Model

• Client objects (handlers) register with acomponent that they want to observe.

• GUI components only trigger the handof event that has occurred.

• Most components can trigger more thaevent.

• The delegation model distributes the wmultiple classes.

Page 352: core java

Java™ Module 11, slide 7 of 22Copyrig

123456789101112131415161718

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

A Listener Example

import java.awt.*;

public class TestButton { private Frame f; private Button b;

public TestButton() { f = new Frame("Test"); b = new Button("Press Me!"); b.setActionCommand("ButtonPressed"); }

public void launchFrame() {b.addActionListener(new ButtonHandler());

f.add(b,BorderLayout.CENTER); f.pack(); f.setVisible(true); }

Page 353: core java

Java™ Module 11, slide 8 of 22Copyrig

192021222324

Co

123 tener {456789

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

A Listener Example

public static void main(String args[]) { TestButton guiApp = new TestButton(); guiApp.launchFrame(); }}

de for the event listener looks like this:

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 354: core java

Java™ Module 11, slide 9 of 22Copyrig

java.util.EventObject

KeyEvent

MouseEvent

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Event Categoriesjava.awt.AWTEvent ActionEvent

AdjustmentEvent

ComponentEvent

TextEvent

ContainerEvent

FocusEvent

InputEvent

WindowEvent

java.awt.event

ItemEvent

Page 355: core java

Java™ Module 11, slide 10 of 22Copyrig

faces

Ca

Ac ActionEvent)

Item (ItemEvent)

Mo seEvent)useEvent)seEvent)eEvent)seEvent)

Momo

seEvent)Event)

Ke ent)vent)t)

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Method Categories and Inter

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 356: core java

Java™ Module 11, slide 11 of 22Copyrig

ces

Ca

Foc sEvent)vent)

Ad hanged)

Co omponentEvent)ComponentEvent)(ComponentEvent)omponentEvent)

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 357: core java

Java™ Module 11, slide 12 of 22Copyrig

ces

Ca

Wi ndowEvent)dowEvent)WindowEvent)d(WindowEvent)dowEvent)WindowEvent)d(WindowEvent)

Co ontainerEvent)(ContainerEvent)

Tex (TextEvent)

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Method Categories and Interfa

tegory Interface Name Methods

ndow WindowListener windowClosing(WiwindowOpened(WinwindowIconified(windowDeiconifiewindowClosed(WinwindowActivated(windowDeactivate

ntainer ContainerListener componentAdded(CcomponentRemoved

t TextListener textValueChanged

Page 358: core java

Java™ Module 11, slide 13 of 22Copyrig

12345 tener {6789101112

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Complex Example

import java.awt.*;import java.awt.event.*;

public class TwoListenerimplements MouseMotionListener, MouseLis

private Frame f; private TextField tf;

public TwoListener() { f = new Frame("Two listeners example"); tf = new TextField(30); }

Page 359: core java

Java™ Module 11, slide 14 of 22Copyrig

131415 se");16171819202122232425

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Complex Example

public void launchFrame() { Label label = new Label("Click and drag the mou // 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 360: core java

Java™ Module 11, slide 15 of 22Copyrig

2627282930313233343536373839404142

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 361: core java

Java™ Module 11, slide 16 of 22Copyrig

434445 he46474849505152535455565758

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 362: core java

Java™ Module 11, slide 17 of 22Copyrig

of a program to

re called when

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Multiple Listeners

• Multiple listeners cause unrelated partsreact to the same event.

• The handlers of all registered listeners athe event occurs.

Page 363: core java

Java™ Module 11, slide 18 of 22Copyrig

extend adapterthat you need.

1234 {5678910111213

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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.*;

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 364: core java

Java™ Module 11, slide 19 of 22Copyrig

lasses

123456789101112 apter {1314 )15161718

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Event Handling Using Inner C

import java.awt.*;import java.awt.event.*;public class TestInner { private Frame f; private TextField tf; // used by inner class

public TestInner() { f = new Frame("Inner classes example"); tf = new TextField(30); }

class MyMouseMotionListener extends MouseMotionAd public void mouseDragged(MouseEvent e) { String s = "Mouse dragging: X = "+ e.getX( + " Y = " + e.getY();

tf.setText(s); } }

Page 365: core java

Java™ Module 11, slide 20 of 22Copyrig

sses

192021 se");2223242526 ner());2728293031323334353637

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Event Handling Using Inner Cla

public void launchFrame() { Label label = new Label("Click and drag the mou // 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 366: core java

Java™ Module 11, slide 21 of 22Copyrig

E s Classes

1234567891011121314151617

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

vent Handling Using Anonymou

import java.awt.*;import java.awt.event.*;

public class TestAnonymous { private Frame f; private TextField tf;

public TestAnonymous() { f = new Frame("Anonymous classes example"); tf = new TextField(30); }

public static void main(String args[]) { TestAnonymous obj = new TestAnonymous(); obj.launchFrame(); }

Page 367: core java

Java™ Module 11, slide 22 of 22Copyrig

E Classes

1819 se");2021222324 () {2526 )2728293031 Not shown3233343536

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

vent Handling Using Anonymous

public void launchFrame() { Label label = new Label("Click and drag the mou // 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 368: core java

Sun

Java™ Programmi

ns

Services

ng Language

Module 12

GUI-Based Applicatio

Page 369: core java

Java™ Module 12, slide 2 of 18Copyrig

the events that

menu, and

d font of a

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Objectives

• Identify the key AWT components andthey trigger

• Describe how to construct a menu bar, menu items in a Java GUI

• Understand how to change the color ancomponent

Page 370: core java

Java™ Module 12, slide 3 of 18Copyrig

I for bothut. However,

ich GUIs can becomponents

UI frame?

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 371: core java

Java™ Module 12, slide 4 of 18Copyrig

Co

But for receiving mouse

Can

Che to select an item

Che

Cho

Com nts, except menu

Con s

Dia and a border;al

Fra ws with window

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

AWT Components

mponent Type Description

ton A named rectangular box used clicks

vas A panel used for drawing

ckbox A component enabling the user

ckboxMenuItem A checkbox within a menu

ice A pull-down static list of items

ponent The parent of all AWT componecomponents

tainer The parent of all AWT container

log A top-level window with a titledialogs can be modeless or mod

me The base class of all GUI windomanager controls

Page 372: core java

Java™ Module 12, slide 5 of 18Copyrig

Co

Lab

Lis namic set of items

Men , which contains a

Men

Pan st often to create

Scr r to select from a

Scr ts automatic for a single child

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

AWT Components

mponent Type Description

el A text string component

t A component that contains a dy

u An element under the menu barset of menu items

uItem An item within a menu

el A basic container class used mocomplex layouts

ollbar A component that enables a userange of values

ollPane A container class that implemenhorizontal and vertical scrollingcomponent

Page 373: core java

Java™ Module 12, slide 6 of 18Copyrig

Co

Tex ser to enter a block

Tex ser to enter a single

Win s, without window

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

AWT Components

mponent Type Description

tArea A component that enables the uof text

tField A component that enables the uline of text

dow The base class of all GUI windowmanager controls

Page 374: core java

Java™ Module 12, slide 7 of 18Copyrig

CoTy

u MM Text Win

But ✓

Can ✓

Che ✓

CheMen

Cho ✓

Com ✓

Con ✓

Dia ✓

Fra ✓

Lab ✓

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

AWT Listeners

mponentpe

Act Adj Cmp Cnt Foc Itm Key Mo

ton ✓ ✓ ✓ ✓ ✓

vas ✓ ✓ ✓ ✓

ckbox ✓ ✓ ✓ ✓ ✓

ckbox-uItem

ice ✓ ✓ ✓ ✓ ✓

ponent ✓ ✓ ✓ ✓

tainer ✓ ✓ ✓ ✓ ✓

log ✓ ✓ ✓ ✓ ✓

me ✓ ✓ ✓ ✓ ✓

el ✓ ✓ ✓ ✓

Page 375: core java

Java™ Module 12, slide 8 of 18Copyrig

CoTy

u MM Text Win

Lis ✓

Men

Pan ✓

Scr ✓

Scr ✓

Tex ✓ ✓

Tex ✓ ✓

Win ✓ ✓ ✓

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

AWT Listeners

mponentpe

Act Adj Cmp Cnt Foc Itm Key Mo

t ✓ ✓ ✓ ✓ ✓ ✓

uItem ✓

el ✓ ✓ ✓ ✓ ✓

ollbar ✓ ✓ ✓ ✓ ✓

ollPane ✓ ✓ ✓ ✓ ✓

tArea ✓ ✓ ✓ ✓

tField ✓ ✓ ✓ ✓ ✓

dow ✓ ✓ ✓ ✓ ✓

Page 376: core java

Java™ Module 12, slide 9 of 18Copyrig

a menu

dd them to the

and add them

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

How to Create a Menu

1. Create a MenuBar object, and set it intocontainer, such as a Frame.

2. Create one or more Menu objects, and amenu bar object.

3. Create one or more MenuItem objects,to the menu object.

Page 377: core java

Java™ Module 12, slide 10 of 18Copyrig

123

ndows

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Creating a MenuBar

Frame f = new Frame("MenuBar");MenuBar mb = new MenuBar();f.setMenuBar(mb);

Solaris OS Microsoft Wi

Page 378: core java

Java™ Module 12, slide 11 of 18Copyrig

123456789

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Creating a Menu

Frame f = new Frame("Menu");MenuBar mb = new MenuBar();Menu m1 = new Menu("File");Menu m2 = new Menu("Edit");Menu m3 = new Menu("Help");mb.add(m1);mb.add(m2);mb.setHelpMenu(m3);f.setMenuBar(mb);

Page 379: core java

Java™ Module 12, slide 12 of 18Copyrig

ndows

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Creating a Menu

Solaris OSMicrosoft Wi

Page 380: core java

Java™ Module 12, slide 13 of 18Copyrig

12345678910111213

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Creating a MenuItem

MenuItem mi1 = new MenuItem("New");MenuItem mi2 = new MenuItem("Save");MenuItem mi3 = new MenuItem("Load");MenuItem mi4 = new MenuItem("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 381: core java

Java™ Module 12, slide 14 of 18Copyrig

ndows

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Creating a MenuItem

Solaris OSMicrosoft Wi

Page 382: core java

Java™ Module 12, slide 15 of 18Copyrig

tem

1234567891011121314 tent");1516

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Creating a CheckBoxMenuI

MenuBar mb = new MenuBar();Menu m1 = new Menu("File");Menu m2 = new Menu("Edit");Menu m3 = new Menu("Help");mb.add(m1);mb.add(m2);mb.setHelpMenu(m3);f.setMenuBar(mb);.....MenuItem mi2 = new MenuItem("Save");mi2.addActionListener(this);m1.add(mi2);......CheckboxMenuItem mi5 = new CheckboxMenuItem("Persismi5.addItemListener(this);m1.add(mi5);

Page 383: core java

Java™ Module 12, slide 16 of 18Copyrig

tem

ndows

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Creating a CheckBoxMenuI

Solaris OSMicrosoft Wi

Page 384: core java

Java™ Module 12, slide 17 of 18Copyrig

ts

Co I include:

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Controlling Visual Aspec

mmands to control visual aspects of the GU

• Colors:setForeground()setBackground()

• Example:Color purple = new Color(255, 0, 255);Button b = new Button(“Purple”);b.setBackground(purple);

Page 385: core java

Java™ Module 12, slide 18 of 18Copyrig

y

wing) toolkit.he components

much moree, JTree, and

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

J.F.C./Swing Technolog

• Java Foundation Class/Swing (J.F.C./Stechnology is a second-generation GUI

• It builds on top of AWT, but supplants twith lightweight versions.

• There are many more components, andcomplex components, including JTablJComboBox.

Page 386: core java

Sun

Java™ Programmi

Services

ng Language

Module 13

Threads

Page 387: core java

Java™ Module 13, slide 2 of 37Copyrig

ology program,sed by that

rite platform-

when multiple

etween threads corruption

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 388: core java

Java™ Module 13, slide 3 of 37Copyrig

Ho le taskscon

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Relevance

w do you get programs to perform multipcurrently?

Page 389: core java

Java™ Module 13, slide 4 of 37Copyrig

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 390: core java

Java™ Module 13, slide 5 of 37Copyrig

12345678910111213141516171819

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 391: core java

Java™ Module 13, slide 6 of 37Copyrig

characteristics:ble instance.e.

”nner

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 392: core java

Java™ Module 13, slide 7 of 37Copyrig

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Starting the Thread

• Use the start method.• Place the thread in a runnable state.

Page 393: core java

Java™ Module 13, slide 8 of 37Copyrig

N Dead

run() Completes

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Thread Scheduling

Runnable

ew

RunningScheduler

Blocked

Unblocked Event Blocked

start()

Page 394: core java

Java™ Module 13, slide 9 of 37Copyrig

ple

123456789101112131415

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Thread Scheduling Exam

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 395: core java

Java™ Module 13, slide 10 of 37Copyrig

1234567891011121314

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 396: core java

Java™ Module 13, slide 11 of 37Copyrig

12345678910111213

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 397: core java

Java™ Module 13, slide 12 of 37Copyrig

s

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Basic Control of Thread

• Test threads:isAlive()

• Access thread priority:getPriority()setPriority()

• Put threads on hold:Thread.sleep() // static methodjoin()Thread.yield() // static method

Page 398: core java

Java™ Module 13, slide 13 of 37Copyrig

12345 a while678910111213141516

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 399: core java

Java™ Module 13, slide 14 of 37Copyrig

ads

1234567891011121314151617

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Other Ways to Create Thre

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 400: core java

Java™ Module 13, slide 15 of 37Copyrig

reads

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Selecting a Way to Create Th

• Implement Runnable:• Better object-oriented design• Single inheritance• Consistency

• Extend Thread:Simpler code

Page 401: core java

Java™ Module 13, slide 16 of 37Copyrig

yword

123456789101112131415

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Using the synchronizedKe

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 402: core java

Java™ Module 13, slide 17 of 37Copyrig

lock flag. with the lock

h(char c) {(this) { c;

onized(this)

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 403: core java

Java™ Module 13, slide 18 of 37Copyrig

h(char c) {(this) { c;

nized(this)

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The Object Lock Flag

Object this

public void pussynchronized data[idx] =idx++;

}}

Thread after synchro

Code orBehavior

Data orState

Page 404: core java

Java™ Module 13, slide 19 of 37Copyrig

op() {d (this) {

ta[idx];

ing tozed(this)

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 405: core java

Java™ Module 13, slide 20 of 37Copyrig

Th ts:

d of the

eturn, ored code block

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 406: core java

Java™ Module 13, slide 21 of 37Copyrig

t Together

nchronized.ed should be

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Using synchronized– Putting I

• All access to delicate data should be sy• Delicate data protected by synchroniz

private.

Page 407: core java

Java™ Module 13, slide 22 of 37Copyrig

t Together

Th ent:

publ sy }}

publ//

}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Using synchronized– Putting I

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 408: core java

Java™ Module 13, slide 23 of 37Copyrig

T ronization

N Dead

run() Completes

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

hread State Diagram With Synch

Blocked inObject’s

Lock Pool

Runnable

ew

RunningScheduler

Blocked

Unblocked Event Blocked

Lock Acquired Synchronized

start()

Page 409: core java

Java™ Module 13, slide 24 of 37Copyrig

A d

from the other.

s

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 410: core java

Java™ Module 13, slide 25 of 37Copyrig

notify

two threads.

at your

stination and

pon arrival at

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Thread Interaction – waitand

• 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 411: core java

Java™ Module 13, slide 26 of 37Copyrig

Th

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Thread Interaction

read interactions include:

• The wait and notify methods• The pools:

• Wait pool• Lock pool

Page 412: core java

Java™ Module 13, slide 27 of 37Copyrig

Th nd notify

Blocked inObject’s

Wait Pool

New Dead

un() Completes

)

wait()[Must have lock]/Releases lock

st

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

read State Diagram With wait a

notify() orBlocked inObject’s

Lock Pool

Runnable RunningScheduler

Blocked

Unblocked Event Blocked

r

Lock Acquired Synchronized

interrupt(

art()

Page 413: core java

Java™ Module 13, slide 28 of 37Copyrig

zation

notifications in

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Monitor Model for Synchroni

• Leave shared data in a consistent state.• Ensure programs cannot deadlock.• Do not put threads expecting different

the same wait pool.

Page 414: core java

Java™ Module 13, slide 29 of 37Copyrig

123456789101112

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 415: core java

Java™ Module 13, slide 30 of 37Copyrig

13141516171819 c);202122232425262728

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 416: core java

Java™ Module 13, slide 31 of 37Copyrig

123456789101112

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 417: core java

Java™ Module 13, slide 32 of 37Copyrig

1314151617 c);181920212223242526

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 418: core java

Java™ Module 13, slide 33 of 37Copyrig

Th

publ

pr ter>(400);

pu

}

pu

}}

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 419: core java

Java™ Module 13, slide 34 of 37Copyrig

91011121314151617181920

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 420: core java

Java™ Module 13, slide 35 of 37Copyrig

22232425

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The pushMethod

public synchronized void push(char c) { this.notify(); buffer.add(c); }

Page 421: core java

Java™ Module 13, slide 36 of 37Copyrig

12345678910111213141516171819

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 422: core java

Java™ Module 13, slide 37 of 37Copyrig

ProdConsProdConsProdProdProdConsConsProdProdConsConsProdConsProdConsCons

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The SyncTestClass

ucer2: Fumer1: Fucer2: Kumer2: Kucer2: Tucer1: Nucer1: Vumer2: Vumer1: Nucer2: Vucer2: Uumer2: Uumer2: Vucer1: Fumer1: Fucer2: Mumer2: Mumer2: T

Page 423: core java

Sun

Java™ Programmi

s

Services

ng Language

Module 14

Advanced I/O Stream

Page 424: core java

Java™ Module 14, slide 2 of 22Copyrig

io package, and use them

treams, and

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Objectives

• Describe the main features of the java.• Construct node and processing streams

appropriately• Distinguish readers and writers from s

select appropriately between them

Page 425: core java

Java™ Module 14, slide 3 of 22Copyrig

he Javate from sources

pported in I/O

s of character

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Relevance

• What mechanisms are in place within tprogramming language to read and wri(or sinks) other than files?

• How are international character sets suoperations?

• What are the possible sources and sinkand byte streams?

Page 426: core java

Java™ Module 14, slide 4 of 22Copyrig

data from a

a, also called an

a, also called an

.y, and pipes

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

I/O Fundamentals

• A stream can be thought of as a flow of source or to a sink.

• A source stream initiates the flow of datinput stream.

• A sink stream terminates the flow of datoutput stream.

• Sources and sinks are both node streams• Types of node streams are files, memor

between threads or processes.

Page 427: core java

Java™ Module 14, slide 5 of 22Copyrig

ses

Str racter Streams

Sou der

Sin ter

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Fundamental Stream Clas

eam Byte Streams Cha

rce streams InputStream Rea

k streams OutputStream Wri

Page 428: core java

Java™ Module 14, slide 6 of 22Copyrig

streams:

andled by

d by input

byte stream.haracter

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 429: core java

Java™ Module 14, slide 7 of 22Copyrig

ds

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The InputStreamMetho

• 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 430: core java

Java™ Module 14, slide 8 of 22Copyrig

ds

h)

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The OutputStreamMetho

• 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 431: core java

Java™ Module 14, slide 9 of 22Copyrig

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 432: core java

Java™ Module 14, slide 10 of 22Copyrig

h)

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 433: core java

Java™ Module 14, slide 11 of 22Copyrig

Ty ms

Fil StreamtStream

Mearr

InputStreamOutputStream

Mestr

Pip tStreamutStream

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Node Streams

pe Character Streams Byte Strea

e FileReaderFileWriter

FileInputFileOutpu

mory:ay

CharArrayReaderCharArrayWriter

ByteArrayByteArray

mory:ing

StringReaderStringWriter

N/A

e PipedReaderPipedWriter

PipedInpuPipedOutp

Page 434: core java

Java™ Module 14, slide 12 of 22Copyrig

Th sing a manualbu

jav

123456789101112

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

A Simple Example

is program performs a copy file operation uffer:

a TestNodeStreams file1 file2

import java.io.*;

public class TestNodeStreams { public static void main(String[] args) { try { FileReader input = new FileReader(args[0]); FileWriter output = new FileWriter(args[1]); char[] buffer = new char[128]; int charsRead;

// read the first buffer charsRead = input.read(buffer);

Page 435: core java

Java™ Module 14, slide 13 of 22Copyrig

13141516171819202122232425262728

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

A Simple Example

while ( charsRead != -1 ) {// write the buffer out to the output fileoutput.write(buffer, 0, charsRead);

// read the next buffercharsRead = input.read(buffer);

}

input.close(); output.close(); } catch (IOException e) { e.printStackTrace(); } }}

Page 436: core java

Java™ Module 14, slide 14 of 22Copyrig

Th sing a built-inbu

jav

123456 s[0]);7 (input);8 s[1]);9 (output);10111213

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Buffered Streams

is program performs a copy file operation uffer:

a TestBufferedStreams file1 file2

import java.io.*;

public class TestBufferedStreams { public static void main(String[] args) { try { FileReader input = new FileReader(arg BufferedReader bufInput = new BufferedReader FileWriter output = new FileWriter(arg BufferedWriter bufOutput = new BufferedWriter String line;

// read the first line line = bufInput.readLine();

Page 437: core java

Java™ Module 14, slide 15 of 22Copyrig

141516171819202122232425262728

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Buffered Streams

while ( line != null ) {// write the line out to the output filebufOutput.write(line, 0, line.length());bufOutput.newLine();// read the next lineline = bufInput.readLine();

}bufInput.close();

bufOutput.close();} catch (IOException e) {

e.printStackTrace(); } }}

Page 438: core java

Java™ Module 14, slide 16 of 22Copyrig

Program

Data Sink

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

I/O Stream Chaining

Data Source

FileInputStreamBufferedInputStream

DataInputStream

Program

FileOutputStreamBufferedOutputStream

DataOutputStream

Input Stream Chain

Output Stream Chain

Page 439: core java

Java™ Module 14, slide 17 of 22Copyrig

Ty ams

Bu InputStreamOutputStream

Filt nputStreamutputStream

Cobetand

Perobjser

putStreamtputStream

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Processing Streams

pe Character Streams Byte Stre

ffering BufferedReaderBufferedWriter

BufferedBuffered

ering FilterReaderFilterWriter

FilterIFilterO

nvertingween bytes character

InputStreamReaderOutputStreamWriter

formingectialization

ObjectInObjectOu

Page 440: core java

Java™ Module 14, slide 18 of 22Copyrig

Ty ams

Percon

tStreamutStream

Co erInputStream

Pee InputStream

Pri eam

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Processing Streams

pe Character Streams Byte Stre

forming dataversion

DataInpuDataOutp

unting LineNumberReader LineNumb

king ahead PushbackReader Pushback

nting PrintWriter PrintStr

Page 441: core java

Java™ Module 14, slide 19 of 22Copyrig

rarchy

nputStream

ackInputStream

redInputStream

umberInputStream

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The InputStreamClass Hie

InputStream

FileInputStream

ObjectInputStream

PipedInputStream

StringBufferInputStream

FilterInputStream

ByteArrayInputStream

DataI

Pushb

Buffe

LineN

SequenceInputStream

Page 442: core java

Java™ Module 14, slide 20 of 22Copyrig

rarchy

aOutputStream

ntStreamntStream

feredOutputStream

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The OutputStreamClass Hie

OutputStream

FileOutputStream

ObjectOutputStream

FilterOutputStream

ByteArrayOutputStream

Dat

PriPri

Buf

PipedOutputStream

Page 443: core java

Java™ Module 14, slide 21 of 22Copyrig

hy

eader

erReader

ader

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The ReaderClass Hierarc

Reader

BufferedReader

CharArrayReader

PipedReader

FilterReader

StringReader

FileRInputStreamReader

LineNumb

PushbackRe

Page 444: core java

Java™ Module 14, slide 22 of 22Copyrig

hy

eWriter

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

The WriterClass Hierarc

Writer

BufferedWriter

CharArrayWriter

PrintWriter

PipedWriter

FilterWriter

StringWriter

FilOutputStreamWriter

Page 445: core java

Sun

Java™ Programmi

Services

ng Language

Module 15

Networking

Page 446: core java

Java™ Module 15, slide 2 of 12Copyrig

nection

forservers

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 447: core java

Java™ Module 15, slide 3 of 12Copyrig

Ho nt machine anda s

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Relevance

w can a communication link between a clieerver on the network be established?

Page 448: core java

Java™ Module 15, slide 4 of 12Copyrig

Th

So

am and an

ams.

Se

Set telephonesys ch must belist

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 449: core java

Java™ Module 15, slide 5 of 12Copyrig

o.com

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Networking

client.bar.com

client.baz.com

server.fo

18000

18002

3000

Page 450: core java

Java™ Module 15, slide 6 of 12Copyrig

ology

following:hinese at the server

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Networking With Java Techn

• 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 451: core java

Java™ Module 15, slide 7 of 12Copyrig

l

t#)

)

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.1

Java Networking Mode

Server

ServerSocket (port #)

OutputStream

InputStream

Socket.close()

Client

Socket (host, por

OutputStream

InputStream

Socket.close(

Register withthis service

Wait for aconnection

(Attempt to connect)Socket()

ServerSocket.accept()

Page 452: core java

Java™ Module 15, slide 8 of 12Copyrig

12345678910111213

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 453: core java

Java™ Module 15, slide 9 of 12Copyrig

1415161718192021 cket22 );2324252627

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 454: core java

Java™ Module 15, slide 10 of 12Copyrig

2829 socket303132333435363738394041

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 455: core java

Java™ Module 15, slide 11 of 12Copyrig

123456789 54321011 ;1213141516 ;

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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 456: core java

Java™ Module 15, slide 12 of 12Copyrig

1718192021 tion22232425262728293031323334

Sun Services

Programming Languageht 2006 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision F.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