418
Sun Microsystems, Inc. UBRM03-195 500 Eldorado Blvd. Broomfield, CO 80021 U.S.A. Revision G Student Guide Java™ Programming Language SL-275-SE6

Sl275 Sg

Embed Size (px)

Citation preview

Page 1: Sl275 Sg

Sun Microsystems, Inc.UBRM03-195

500 Eldorado Blvd.Broomfield, CO 80021

U.S.A.

Revision G

Student Guide

Java™ Programming LanguageSL-275-SE6

Page 2: Sl275 Sg

May 14, 2007 12:22 pm

Page 3: Sl275 Sg

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

This product or document is protected by copyright and distributed under licenses restricting its use, copying, distribution, anddecompilation. No part of this product or document may be reproduced in any form by any means without prior written authorization ofSun and its licensors, if any.

Netscape Navigator is a trademark or registered trademark of Netscape Communications Corporation in the United States and othercountries.

Third-party software, including font technology, is copyrighted and licensed from Sun suppliers.

Sun, Sun Microsystems, the Sun logo, EJB, Enterprise JavaBeans, Java, JDK, J2EE, Java, J2SE, Java SE, JavaBeans, JDBC, JavaServer Pages,JSP, JVM, Java Naming and Directory Interface, JMX, Java HotSpot, JRE, Sun Java and Solaris are trademarks or registered trademarks ofSun Microsystems, Inc. in the U.S. and other countries.

Federal Acquisitions: Commercial Software – Government Users Subject to Standard License Terms and Conditions

Export Laws. Products, Services, and technical data delivered by Sun may be subject to U.S. export controls or the trade laws of othercountries. You will comply with all such laws and obtain all licenses to export, re-export, or import as may be required after delivery toYou. You will not export or re-export to entities on the most current U.S. export exclusions lists or to any country subject to U.S. embargoor terrorist controls as specified in the U.S. export laws. You will not use or provide Products, Services, or technical data for nuclear, missile,or chemical biological weaponry end uses.

DOCUMENTATION IS PROVIDED “AS IS” AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS, ANDWARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSEOR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BELEGALLY INVALID.

THIS MANUAL IS DESIGNED TO SUPPORT AN INSTRUCTOR-LED TRAINING (ILT) COURSE AND IS INTENDED TO BEUSED FOR REFERENCE PURPOSES IN CONJUNCTION WITH THE ILT COURSE. THE MANUAL IS NOT A STANDALONETRAINING TOOL. USE OF THE MANUAL FOR SELF-STUDY WITHOUT CLASS ATTENDANCE IS NOT RECOMMENDED.

Export Control Classification Number (ECCN) assigned: 5 March 2003

PleaseRecycle

Page 4: Sl275 Sg

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

Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, la copie, la distribution,et la décompilation. Aucune partie de ce produit ou document ne peut être reproduite sous aucune forme, par quelque moyen que ce soit,sans l’autorisation préalable et écrite de Sun et de ses bailleurs de licence, s’il y en a.

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

Sun, Sun Microsystems, le logo Sun, EJB, Enterprise JavaBeans, Java, JDK, J2EE, J2SE, Java SE, JavaBeans, JDBC, JavaServer Pages, JSP, JVM,Java Naming and Directory Interface, JMX, Java HotSpot, JRE, Sun Java et Solaris sont des marques de fabrique ou des marques déposéesde Sun Microsystems, Inc. aux Etats-Unis et dans d’autres pays.

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

Législation en matière dexportations. Les Produits, Services et données techniques livrés par Sun peuvent être soumis aux contrôlesaméricains sur les exportations, ou à la législation commerciale dautres pays. Nous nous conformerons à lensemble de ces textes et nousobtiendrons toutes licences dexportation, de ré-exportation ou dimportation susceptibles dêtre requises après livraison à Vous. Vousnexporterez, ni ne ré-exporterez en aucun cas à des entités figurant sur les listes américaines dinterdiction dexportation les plus courantes,ni vers un quelconque pays soumis à embargo par les Etats-Unis, ou à des contrôles anti-terroristes, comme prévu par la législationaméricaine en matière dexportations. Vous nutiliserez, ni ne fournirez les Produits, Services ou données techniques pour aucune utilisationfinale liée aux armes nucléaires, chimiques ou biologiques ou aux missiles.

LA DOCUMENTATION EST FOURNIE “EN L’ETAT” ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET GARANTIESEXPRESSES OU TACITES SONT FORMELLEMENT EXCLUES, DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE, YCOMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITE MARCHANDE, A L’APTITUDE A UNEUTILISATION PARTICULIERE OU A L’ABSENCE DE CONTREFAÇON.

CE MANUEL DE RÉFÉRENCE DOIT ÊTRE UTILISÉ DANS LE CADRE D’UN COURS DE FORMATION DIRIGÉ PAR UNINSTRUCTEUR (ILT). IL NE S’AGIT PAS D’UN OUTIL DE FORMATION INDÉPENDANT. NOUS VOUS DÉCONSEILLONS DEL’UTILISER DANS LE CADRE D’UNE AUTO-FORMATION.

PleaseRecycle

Page 5: Sl275 Sg

Table of Contents

About This Course ..............................................................Preface-xvCourse Goals......................................................................... Preface-xvCourse Overview ................................................................Preface-xviiCourse Map........................................................................ Preface-xviiiModule-by-Module Overview ...........................................Preface-xixTopics Not Covered.............................................................Preface-xxiHow Prepared Are You?....................................................Preface-xxiiIntroductions ......................................................................Preface-xxiiiHow to Use Course Materials ..........................................Preface-xxivConventions .........................................................................Preface-xxv

Icons .............................................................................Preface-xxvTypographical Conventions ....................................Preface-xxviAdditional Conventions..........................................Preface-xxvii

Executing Your First Java Application...........................................1-1Objectives ........................................................................................... 1-1Additional Resources ........................................................................ 1-2Examining the JDK Software............................................................ 1-3

Examining the JDK Software Support for Developing JavaApplications........................................................................... 1-4

JDK Deployment Technologies............................................ 1-12The Java Virtual Machine (JVM)........................................... 1-13The Java™ Runtime Environment (JRE™)......................... 1-15

Examining Java Application Loading and Execution................. 1-16The Class Loader..................................................................... 1-17The Byte-Code Verifier........................................................... 1-17

Creating a Simple Java Application .............................................. 1-18The TestGreeting Application .......................................... 1-19The Greeting Class............................................................... 1-21Compiling and Running the TestGreeting Program..... 1-22Troubleshooting the Compilation ....................................... 1-23

vCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 6: Sl275 Sg

Creating Java Technology Applications........................................ 2-1Objectives ........................................................................................... 2-1Additional Resources ........................................................................ 2-2The Composition of a Java Application.......................................... 2-3Examining Custom Class Creation: Concept to Implementation2-6

Examining Class Creation........................................................ 2-6Examining Application Main Classes .................................. 2-11

Comparing Static and Dynamic Views of a Java Application... 2-12A Static View ........................................................................... 2-12A Dynamic View..................................................................... 2-13

Creating, Using, and Disposing of Objects .................................. 2-19

Creating a Class: Fields and Constructors Syntax ...................... 3-1Objectives ........................................................................................... 3-1Additional Resources ........................................................................ 3-2Introducing the class Declaration ................................................. 3-3

Associating a New Class With a Package.............................. 3-3Declaring the Foreign Classes Used by the New Class ....... 3-4Declaring the Fields of the Class............................................. 3-5Declaring the Constructors of the Class ................................ 3-6Declaring the Methods of the Class........................................ 3-7

Declaring Fields: Selecting Primitive Data Types ......................... 3-9Declaring Fields: Selecting Class Types........................................ 3-11

The Java SE Class Libraries.................................................... 3-11Declaring Fields: Formatting Identifiers....................................... 3-15Declaring Fields: Initializing Fields............................................... 3-16

Field Initialization Using Default Values ............................ 3-17Field Initialization Using Explicit Values............................ 3-18Field Initialization Using Constructors............................... 3-19

Examining Comments, White Space, and Keywords ................. 3-24Comments ................................................................................ 3-24White Space.............................................................................. 3-25Java Programming Language Keywords ............................ 3-25

Directory Layout and Packages ..................................................... 3-27Development ........................................................................... 3-27Compiling Using the -d Option ........................................... 3-28Deployment ............................................................................. 3-29

Declaring a Class: Methods Syntax ............................................... 4-1Objectives ........................................................................................... 4-1Additional Resources ........................................................................ 4-2Examining Methods........................................................................... 4-3

Examining the Class-to-Method Relationship...................... 4-4Examining the Method Interface-to-Method Body

Relationship ............................................................................ 4-5Examining the Fields, Parameters, and Local

Variables-to-Method Body Relationship ............................ 4-7

vi Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 7: Sl275 Sg

Examining the Method Body ........................................................... 4-8Examining Expressions ..................................................................... 4-9

Examining Simple Expressions............................................. 4-10Expressions: Advanced Issues ....................................................... 4-15

Numeric Promotions in Simple Expressions ...................... 4-15Casting...................................................................................... 4-16Autoboxing of Primitive Types............................................. 4-17Evaluating Compound Expressions..................................... 4-18

Introducing Statements ................................................................... 4-19Block Statements .............................................................................. 4-21Branching Statements ...................................................................... 4-22

Simple if Statements ............................................................. 4-22Simple if, else Statements................................................... 4-22Complex if, else Statements............................................... 4-23The switch Statement........................................................... 4-24

Looping Statements ......................................................................... 4-27The for Loops ......................................................................... 4-27The while Loop...................................................................... 4-28The do/while Loop ................................................................ 4-28Special Loop Flow Control .................................................... 4-29

Advanced Method Design Issues: Overloading Methods ......... 4-31Methods Using Variable Arguments ................................... 4-32

Advanced Method Design Issues: Pass-by-Value....................... 4-33Advanced Method Design Issues: The this Reference ............. 4-35

Creating a Class: Using Encapsulation..........................................5-1Objectives ........................................................................................... 5-1Additional Resources ........................................................................ 5-2Examining the Concept of Encapsulation ...................................... 5-3Implementing Encapsulation in Java Technology ........................ 5-6Using the static Keyword.............................................................. 5-9

Class Attributes ......................................................................... 5-9Class Methods ......................................................................... 5-10Static Initializers ...................................................................... 5-12

Static Imports.................................................................................... 5-13

Creating Arrays.................................................................................6-1Objectives ........................................................................................... 6-1Additional Resources ........................................................................ 6-2Declaring Arrays ................................................................................ 6-3Creating Arrays .................................................................................. 6-4Creating Reference Arrays................................................................ 6-5Initializing Arrays .............................................................................. 6-6Multi-Dimensional Arrays................................................................ 6-7Array Bounds ..................................................................................... 6-8

Using the Enhanced for Loop ................................................ 6-8Array Size Immutability ................................................................... 6-9

viiCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 8: Sl275 Sg

Creating a Subclass Using Inheritance ......................................... 7-1Objectives ........................................................................................... 7-1Additional Resources ........................................................................ 7-2Examining the Concept of Inheritance ........................................... 7-3

Examining the Benefits of Inheritance ................................... 7-5Implementing Inheritance in Java Technology ............................. 7-6

Step 1: Selecting the Parent Class ........................................... 7-7Step 2: Determining What Is Inherited From the Parent

Class ......................................................................................... 7-8Step 3: Declaring the Subclass ................................................. 7-9Step 4: Adding the Attributes and Methods Specific to the

Subclass ................................................................................... 7-9Step 5: If Required, Overriding Parent Class Methods ..... 7-10Step 6: Adding Constructors as Needed.............................. 7-13

Polymorphism .................................................................................. 7-20Virtual Method Invocation .................................................... 7-20Heterogeneous Collections.................................................... 7-22Polymorphic Arguments ....................................................... 7-22

The instanceof Operator.............................................................. 7-24Casting Object References..................................................... 7-25

The Object Class ............................................................................. 7-26The equals Method................................................................ 7-26The toString Method ........................................................... 7-29

The final Keyword ........................................................................ 7-30Final Classes............................................................................. 7-30Final Methods .......................................................................... 7-30Final Variables ......................................................................... 7-30

Error Handling Using Exception Classes and Assertions ........... 8-1Objectives ........................................................................................... 8-1Additional Resources ........................................................................ 8-2Exceptions and Assertions................................................................ 8-3

Exceptions .................................................................................. 8-3Exception Example ................................................................... 8-4

The try-catch Statement ................................................................ 8-6Call Stack Mechanism .............................................................. 8-8The finally Clause ................................................................. 8-9

Exception Categories ....................................................................... 8-10Common Exceptions........................................................................ 8-12The Handle or Declare Rule ........................................................... 8-13Method Overriding and Exceptions.............................................. 8-15Creating Your Own Exceptions ..................................................... 8-16

Throwing a User-Defined Exception .................................. 8-17Handling a User-Defined Exception ................................... 8-18

Assertions.......................................................................................... 8-19Recommended Uses of Assertions ....................................... 8-19Controlling Runtime Evaluation of Assertions .................. 8-22

viii Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 9: Sl275 Sg

Declaring and Using Specialized Class Types ..............................9-1Objectives ........................................................................................... 9-1Additional Resources ........................................................................ 9-2Abstract Methods and Abstract Classes ......................................... 9-3

Abstract Class Example............................................................ 9-5Interfaces ............................................................................................. 9-7

The Flyer Example .................................................................... 9-7Multiple Interface Example ................................................... 9-12Interface Declaration and Usage Rules................................ 9-13

Nested Classes.................................................................................. 9-14Examining the Nested Class Syntax..................................... 9-15Inner Classes ............................................................................ 9-16Static Nested Classes ............................................................. 9-19Inner Interfaces, EnumeratedTypes, and Annotations...... 9-19

Enumerated Types........................................................................... 9-20Switch Statements ................................................................... 9-20For Loops.................................................................................. 9-21Enumerated Types With Fields, Methods, and

Constructors.......................................................................... 9-22

Using Generics and the Collections Framework.........................10-1Objectives ......................................................................................... 10-1Additional Resources ...................................................................... 10-2The Collections API ......................................................................... 10-3Collection Implementations ........................................................... 10-5

A Set Example ........................................................................ 10-5A List Example ...................................................................... 10-6

The Map Interface.............................................................................. 10-8A Map example......................................................................... 10-9

Legacy Collection Classes............................................................. 10-10Ordering Collections ..................................................................... 10-11

The Comparable Interface .................................................. 10-11The Comparator Interface ................................................... 10-13

Generics ........................................................................................... 10-16Generic Set Example............................................................ 10-17Generic Map Example .......................................................... 10-18

Generics: Examining Type Parameters....................................... 10-19Wild Card Type Parameters ............................................... 10-21

Generics: Refactoring Existing Non-Generic Code................... 10-24Iterators............................................................................................ 10-26The Enhanced for Loop ............................................................... 10-28

I/O Fundamentals ...........................................................................11-1Objectives ......................................................................................... 11-1Additional Resources ...................................................................... 11-2Command-Line Arguments ........................................................... 11-3System Properties............................................................................. 11-4

ixCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 10: Sl275 Sg

The Properties Class .................................................................... 11-5I/O Stream Fundamentals.............................................................. 11-6

Data Within Streams............................................................... 11-6Byte Streams ..................................................................................... 11-7

The InputStream Methods................................................... 11-7The OutputStream Methods................................................. 11-8

Character Streams ............................................................................ 11-9The Reader Methods.............................................................. 11-9The Writer Methods........................................................... 11-10

Node Streams.................................................................................. 11-11A Simple Example................................................................. 11-11

Buffered Streams ............................................................................ 11-13I/O Stream Chaining..................................................................... 11-14Processing Streams ........................................................................ 11-15Basic Byte Stream Classes ............................................................. 11-16

The FileInputStream and FileOutputStreamClasses ................................................................................. 11-17

The BufferedInputStream and BufferedOutputStreamClasses ................................................................................. 11-17

The PipedInputStream and PipedOutputStreamClasses ................................................................................. 11-17

The DataInputStream and DataOutputStreamClasses ................................................................................. 11-17

The ObjectInputStream and ObjectOutputStreamClasses ................................................................................. 11-18

Serialization .................................................................................... 11-21Serialization and Object Graphs ......................................... 11-21Writing and Reading an Object Stream ............................. 11-22

Basic Character Stream Classes.................................................... 11-25The InputStreamReader and OutputStreamWriter

Methods.............................................................................. 11-26Byte and Character Conversions ........................................ 11-26Using Other Character Encoding ....................................... 11-26The FileReader and FileWriter Classes ....................... 11-27The BufferedReader and BufferedWriter Classes ..... 11-27The StringReader and StringWriter Classes .............. 11-27The PipedReader and PipedWriter Classes................... 11-27

Console I/ O and File I/O................................................................ 12-1Objectives ......................................................................................... 12-1Additional Resources ...................................................................... 12-2Console I/O ...................................................................................... 12-3

Writing to Standard Output .................................................. 12-3Reading From Standard Input .............................................. 12-4Simple Formatted Output..................................................... 12-6Simple Formatted Input ........................................................ 12-7

x Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 11: Sl275 Sg

Files and File I/O ............................................................................. 12-8Creating a New File Object ................................................. 12-8The File Tests and Utilities .................................................. 12-9File Stream I/O...................................................................... 12-10

Implementing Multi-Tier Applications Using Networking...........13-1Objectives ......................................................................................... 13-1Additional Resources ...................................................................... 13-2Networking....................................................................................... 13-3

Sockets ...................................................................................... 13-3Setting Up the Connection..................................................... 13-3Addressing the Connection ................................................... 13-5Port Numbers .......................................................................... 13-5Java Networking Model......................................................... 13-6

Minimal TCP/IP Server .................................................................. 13-7Minimal TCP/IP Client................................................................... 13-8

Accessing Information From a URL..................................... 13-9

Implementing Multithreaded Applications ...................................14-1Objectives ......................................................................................... 14-1Additional Resources ...................................................................... 14-2Threads .............................................................................................. 14-3

Creating the Thread................................................................ 14-4Starting the Thread ................................................................. 14-5Thread Scheduling.................................................................. 14-6Terminating theThread .......................................................... 14-7

Basic Control of Threads................................................................. 14-9Testing Threads ....................................................................... 14-9Accessing Thread Priority ..................................................... 14-9Putting Threads on Hold ....................................................... 14-9

Alternative Way to Create Threads............................................. 14-12Selecting a Way to Create Threads.................................... 14-13

Using the synchronized Keyword ............................................ 14-14The Problem........................................................................... 14-14The Object Lock Flag ............................................................ 14-16Releasing the Lock Flag........................................................ 14-18Using the synchronized Mechanism............................... 14-19Thread States ......................................................................... 14-20Deadlock................................................................................. 14-20

Thread Interaction.......................................................................... 14-21Scenario .................................................................................. 14-21The Problem........................................................................... 14-21The Solution ........................................................................... 14-21The wait and notify Methods .......................................... 14-21Thread States ......................................................................... 14-23Monitor Model for Synchronization ................................. 14-24

Putting It Together......................................................................... 14-25

xiCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 12: Sl275 Sg

The Producer Thread ......................................................... 14-26The Consumer Thread .......................................................... 14-26The SyncStack Class........................................................... 14-28The SyncTest Example........................................................ 14-31

Building Java GUIs Using the Swing API .................................... 15-1Objectives ......................................................................................... 15-1Additional Resources ...................................................................... 15-2

Pluggable Look-and-Feel ....................................................... 15-5Swing Architecture ................................................................. 15-6

Swing Packages ................................................................................ 15-8Examining the Composition of a Java Technology GUI .......... 15-10Swing Containers ........................................................................... 15-12

Top-level Containers ............................................................ 15-12General-purpose Containers ............................................... 15-14Special-purpose Containers................................................. 15-15

Swing Components........................................................................ 15-18The Swing Component Hierarchy...................................... 15-19Buttons.................................................................................... 15-20Text Components .................................................................. 15-21Uneditable Information Display Components ................. 15-23Menus ..................................................................................... 15-24Formatted Display Components......................................... 15-25Other Basic Controls............................................................. 15-26

Swing Components Properties .................................................... 15-28Common Component Properties........................................ 15-28Component-Specific Properties .......................................... 15-29

Layout Managers ........................................................................... 15-30The BorderLayout Layout Manager ................................. 15-30The FlowLayout Layout Manager ..................................... 15-31The BoxLayout Layout Manager........................................ 15-32The CardLayout Layout Manager ..................................... 15-33The GridLayout Layout Manager ..................................... 15-34The GridBagLayout Layout Manager............................... 15-34The GroupLayout Layout Manager ................................... 15-35

GUI Construction........................................................................... 15-36Programmatic Construction ................................................ 15-36

Handling GUI-Generated Events .................................................. 16-1Objectives ......................................................................................... 16-1Additional Resources ...................................................................... 16-2What Is an Event? ............................................................................ 16-3Java SE Event Model........................................................................ 16-4

Delegation Model.................................................................... 16-4A Listener Example................................................................. 16-5

GUI Behavior .................................................................................... 16-7Event Categories ..................................................................... 16-7

xii Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 13: Sl275 Sg

Complex Example................................................................... 16-9Multiple Listeners ................................................................. 16-12

Developing Event Listeners.......................................................... 16-13Event Adapters...................................................................... 16-13Event Handling Using Inner Classes ................................. 16-14Event Handling Using Anonymous Classes..................... 16-15

Concurrency in Swing................................................................... 16-17

xiiiCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 14: Sl275 Sg
Page 15: Sl275 Sg

Preface

AboutThis Course

Course Goals

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

● Create Java™ technology applications that leverage theobject-oriented features of the Java language, such as encapsulation,inheritance, and polymorphism

● Execute a Java technology application from the command line

● Use Java technology data types and expressions

● Use Java technology flow control constructs

● Use arrays and other data collections

● Implement error-handling techniques using exception handling

● Create an event-driven graphical user interface (GUI) by using Javatechnology GUI components: panels, buttons, labels, text fields, andtext areas

● Implement input/output (I/O) functionality to read from and writeto data and text files

● Create multithreaded programs

● Create a simple Transmission Control Protocol/Internet Protocol(TCP/IP) client that communicates through sockets

Preface-xvCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 16: Sl275 Sg

Course Goals

The main goal of the Java™ Programming Language course is to provideyou with the knowledge and skills necessary for object-orientedprogramming of advanced Java applications. In this course, you learn theJava programming language syntax and object-oriented concepts, as wellas more sophisticated features of the Java runtime environment, such assupport for GUIs, multithreading, and networking. This course coversprerequisite knowledge to help prepare you for the Sun CertifiedProgrammer for the Java™ Platform (SCJP) examination. For informationabout the exam, review the web site:

http://www.sun.com/training/certification/java/

However, SL-275 is not sufficient to immediately pass the exam. Youshould spend several months practicing these techniques by building realprograms. You should also review the exam objectives and study areasthat were not discussed in this course. The SCJP exam objectives can befound at the web site listed previously.

Preface-xvi Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 17: Sl275 Sg

Course Overview

Course Overview

This course first describes the Java runtime environment and the syntax ofthe Java programming language. The course then covers object-orientedconcepts as they apply to the Java programming language. As the courseprogresses, advanced features of the Java platform are discussed.

The audience for this course includes people who are familiar withimplementing elementary programming concepts using the Javaprogramming language or other languages. This is the follow-up courseto SL-110: Fundamentals of the Java™ Programming Language.

While the Java programming language is independent of an operatingsystem, the GUI that it produces can be dependent on the operatingsystem on which the code is executed. In this course, code examples arerun in the Solaris™ Operating System (Solaris OS) and in the MicrosoftWindows operating environment; therefore, the graphics in this guidehave both a Motif and a Windows GUI. The content of this course isapplicable to all Java operating system ports.

About This Course Preface-xviiCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 18: Sl275 Sg

Course Map

Course Map

The following course map enables you to see what you haveaccomplished and where you are going in reference to the course goal.

The Java Programming Language Basics

More Object-Oriented Programming

Building Applications

Developing Graphical User Interfaces

Advanced Java Programming

Executing Your Creating Java

Creating a Class:

Creating ArraysCreating a Subclass

Declaring and Using

Using Generics andI/O Fundamentals

Console I/O and

ImplementingImplementing

Building Java GUIs

Declaring a Class:

Error Handling

First JavaApplication

TechnologyApplications

Creating a Class:Fields andConstructorsSyntax

Methods Syntax Using Encapsulation

Using Exceptionsand Assertions

the CollectionsFramework

Specialized ClassTypes

Using Inheritance

File I/O

Multi-Tier

UsingNetworking

Applications MultithreadedApplications

Using theSwing API

HandlingGUI-GeneratedEvents

Preface-xviii Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 19: Sl275 Sg

Module-by-Module Overview

Module-by-Module Overview

● Module 1 – “Executing Your First Java Application”

This module provides a general overview of the Java programminglanguage and its main features and introduces a simple Javaapplication.

● Module 2 – “Creating Java Technology Applications”

This module examines the composition of a Java technologyapplication. It examines the concepts of classes, instances, andreferences.

● Module 3 – “Creating a Class: Fields and Constructors Syntax”

This module focuses on mapping object state using fields. Itdiscusses the syntax of field declarations and initializations usingdefault values, explicit values and using constructors.

● Module 4 – “Creating a Class: Methods Syntax”

This module focuses on implementing behavior using methods. Itlooks at method signatures and method bodies and also atexpressions, including operators, and the syntax of Java programcontrol.

● Module 5 – “Creating a Class Using Encapsulation”

This module discusses the concept of encapsulation and itsimplementation using the Java programming language. It examinesthe use of the package statement, access modifiers and the statickeyword.

● Module 6 – “Creating Arrays”

This module describes how Java arrays are declared, created,initialized, and copied.

● Module 7 – “Creating a Subclass Using Inheritance”

This module examines the concept of creating specialized typesusing inheritance and the implementation of polymorphism. Thismodule also contains a discussion of the use of the final keyword.

● Module 8 – “Error Handling Using Exceptions and Assertions”

Exceptions provide you with a mechanism for trapping errors atruntime. This module explores both predefined and user-definedexceptions. It also contains a discussion on the use of assertions.

About This Course Preface-xixCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 20: Sl275 Sg

Module-by-Module Overview

● Module 9 – “Declaring and Using Specialized Class Types”

This module contains a discussion of the declaration and use ofenumerated types, interfaces, and nested classes.

● Module 10 – “Using Generics and the Collections Framework”

This module examines the collections framework and the use ofgenerics in the Java programming language.

● Module 11 – “I/O Fundamentals”

This module describes the classes available for reading and writingboth data and text. It also contains a discussion on objectserialization.

● Module 12 – “Console I/O and File I/O”

This module introduces topics that are useful in implementing large,text-based applications, such as console and file I/O.

● Module 13 – “Implementing Multi-Tier Applications UsingNetworking”

This module introduces the Java network programming package anddemonstrates a TCP/IP client-server model.

● Module 14 – “Implementing Multithreaded Applications”

Threads are a complex topic; this module explains threading as itrelates to the Java programming language and introduces astraightforward example of thread communication andsynchronization.

● Module 15 – “Building Java GUIs Using the Swing API”

This module discusses a variety of Swing API GUI elements.

● Module 16 – “Handling GUI-Generated Events”

Creating a layout of GUI components in a frame is not enough. Youmust write code to handle the events that occur, such as clicking abutton or typing a character. This module demonstrates how to writeGUI event handlers.

Preface-xx Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 21: Sl275 Sg

Topics Not Covered

Topics Not Covered

This course does not cover the following topics. Many of these topics arecovered in other courses offered by Sun Educational Services:

● Object-oriented analysis and design – Covered in OO-226:Object-Oriented Application Analysis and Design Using UML

● General programming concepts – Covered in SL-110: Fundamentals ofthe Java™ Programming Language

Refer to the Sun Educational Services catalog for specific information andregistration.

About This Course Preface-xxiCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 22: Sl275 Sg

How Prepared Are You?

How Prepared Are You?

To be sure you are prepared to take this course, can you answer yes to thefollowing questions?

Before attending this course, you should have completed SL-110:Fundamentals of the Java™ Programming Language, or have:

● Created and compiled programs with C or C++

● Created and edited text files using a text editor

● Used a World Wide Web (WWW) browser, such as NetscapeNavigator™

Preface-xxii Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 23: Sl275 Sg

Introductions

Introductions

Now that you have been introduced to the course, introduce yourself tothe other students and the instructor, addressing the following items:

● Name

● Company affiliation

● Title, function, and job responsibility

● Experience related to topics presented in this course

● Reasons for enrolling in this course

● Expectations for this course

About This Course Preface-xxiiiCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 24: Sl275 Sg

How to Use Course Materials

How to Use Course Materials

To enable you to succeed in this course, these course materials contain alearning module that is composed of the following components:

● Goals – You should be able to accomplish the goals after finishingthis course and meeting all of its objectives.

● Objectives – You should be able to accomplish the objectives aftercompleting a portion of instructional content. Objectives supportgoals and can support other higher-level objectives.

● Lecture – The instructor presents information specific to the objectiveof the module. This information helps you learn the knowledge andskills necessary to succeed with the activities.

● Activities – The activities take various forms, such as an exercise,self-check, discussion, and demonstration. Activities help youfacilitate the mastery of an objective.

● Visual aids – The instructor might use several visual aids to convey aconcept, such as a process, in a visual form. Visual aids commonlycontain graphics, animation, and video.

Preface-xxiv Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 25: Sl275 Sg

Conventions

Conventions

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

Icons

Additional resources – Indicates other references that provide additionalinformation on the topics described in the module.

?!

Discussion – Indicates a small-group or class discussion on the currenttopic is recommended at this time.

Note – Indicates additional information that can help students but is notcrucial to their understanding of the concept being described. Studentsshould be able to understand the concept or complete the task withoutthis information. Examples of notational information include keywordshortcuts and minor system adjustments.

About This Course Preface-xxvCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 26: Sl275 Sg

Conventions

Typographical Conventions

Courier is used for the names of commands, files, directories,programming code, and on-screen computer output; for example:

Use ls -al to list all files.system% You have mail.

Courier is also used to indicate programming constructs, such as classnames, methods, and keywords; for example:

The getServletInfo method is used to get author information.The java.awt.Dialog class contains Dialog constructor.

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

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

Courier bold is also used for each line of programming code that isreferenced in a textual description; for example:

1 import java.io.*;2 import javax.servlet.*;3 import javax.servlet.http.*;

Notice the javax.servlet interface is imported to allow access to itslife-cycle methods (Line 2).

Courier italics is used for variables and command-line placeholdersthat are replaced with a real name or value; for example:

To delete a file, use the rm filename command.

Courier italic bold is used to represent variables whose values are tobe entered by the student as part of an activity; for example:

Type chmod a+rwx filename to grant read, write, and executerights for filename to world, group, and users.

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

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

Preface-xxvi Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 27: Sl275 Sg

Conventions

Additional Conventions

Java programming language examples use the following additionalconventions:

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

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

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

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

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

In the Solaris OE:

$CD SERVER_ROOT/BIN

In Microsoft Windows:

C:\>CD SERVER_ROOT\BIN

About This Course Preface-xxviiCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 28: Sl275 Sg
Page 29: Sl275 Sg

Module 1

Executing Your First JavaApplication

Objectives

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

● Examine the Java Development Kit (JDK™) software

● Examine Java application loading and executing

● Create a simple Java application

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

Page 30: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following reference provides additionalinformation on the topics described in this module:

● Gosling, Joy, Bracha, and Steele. The Java Language Specification, ThirdEdition. Prentice-Hall. 2005. [Also online at:http://java.sun.com/docs/books/jls/]. accessed May 1, 2007.

1-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 31: Sl275 Sg

Examining the JDK Software

Examining the JDK Software

The JDK software contains the components you need to perform thefollowing tasks:

● Develop Java technology applications

● Deploy Java technology applications

● Execute Java technology applications:

Figure 1-1 provides an overview of the JDK software. It shows thecomponents of the JDK and the activities with which they are associated.

Figure 1-1 The Java SE JDK Overview

The JDK consists of the following components

● The Java programming language

● Tools and tools API

● Deployment technologies

● Java Platform, Standard Edition (Java SE) libraries

● Virtual Machine for the Java platform (Java Virtual Machine(JVM™))

Note – Strictly speaking, the Java programming language is not acomponent of the JDK software. However, it is included in the discussionof the JDK software on the basis that the JDK is primarily provided tosupport Java programming language-based application development.

To use the JDK, you need to download and install both the JDK softwareand the associated JDK documentation on your development platform.The following URL contains the instructions to download and install boththe JDK software and the associated JDK documentation.

http://java.sun.com/javase/downloads/index.jsp

JDK

Java Programming Language

Tools and Tools API

Java SE Libraries

Deployment Technologies

Platform Specific JVMs

Applicationdevelopment

Applicationdeployment

Applicationexecution

Executing Your First Java Application 1-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 32: Sl275 Sg

Examining the JDK Software

Examining the JDK Software Support for DevelopingJava Applications

The following JDK components are provided to support the developmentof Java technology applications:

● The Java programming language

● The JDK tools

● The JDK libraries

The Java Programming Language

The Java Programming Language is a general-purpose, concurrent,strongly typed, class-based object-oriented language. The Javaprogramming language is defined by the Java language specification. Theprimary building block of a Java technology application is a class. Thelanguage specification specifies the language syntax for all Java languageconstructs including that of a class. Code 1-1 shows an example of a Javatechnology class.

Code 1-1 Example of a Java Technology Class

1 package trader;2 import java.io.Serializable;3 public class Stock implements Serializable {4 private String symbol;5 private float price;67 public Stock(String symbol, float price){8 this.symbol = symbol;9 this.price = price;10 }1112 // Methods to return the private values of this object13 public String getSymbol() {14 return symbol;15 }1617 public float getPrice() {18 return price;19 }2021 public void setPrice(float newPrice) {22 price = newPrice;

1-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 33: Sl275 Sg

Examining the JDK Software

23 }2425 public String toString() {26 return "Stock: " + symbol + " " + price;27 }28 }

The JDK Tools and Tools API

Figure 1-2 highlights the tools and tool categories available with the JavaSE JDK.

Figure 1-2 The Java SE JDK With the Java SE Tools Highlighted

Executing Your First Java Application 1-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 34: Sl275 Sg

Examining the JDK Software

The JDK tools provide support for the development and deployment ofJava technology applications. The JDK tools can be classified into twocategories.

● Basic tools

These tools are the tools you use to create, build, and execute Javatechnology applications. Table 1-1 lists the tools from this group thatyou are could encounter in the early stages of learning to programusing Java technology.

● Advanced user tools

The advanced user tools consist of several categories of tools. Eachcategory helps you leverage a particular technology when creating aJava technology application. Table 1-2 lists the advanced toolcategories.

Table 1-1 Java SE Basic Tools: A Sample Selection

Tool Name Function

javac The compiler for the Java programming language

java The launcher for Java technology applications

jdb The Java debugger

javadoc The API document generator

jar Java Archive (JAR) file creator and management tool

Table 1-2 Advanced Tool Categories

Tool Category Comment

Security tools Help you create applications that work withsecurity policies.

Internationalization tools Help create applications that can be localized.

Remote method invocation(RMI) tools

Help create applications that work across anetwork.

Common object requestbroker architecture (CORBA)tools

Help create network applications that are based onCORBA technology.

Java deployment tools Provide compression and decompressionfunctionality that assist with the deployment of Javatechnology applications.

1-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 35: Sl275 Sg

Examining the JDK Software

Note – The JDK tools API is a set of libraries and accompanyingdocumentation that enables the creation of custom tools. A discussion ofthis API is beyond the scope of this module. For more information, referto the Java Platform Debugger Architecture (JPDA) documentationsection of the JDK documentation.

Java Plug-in tools Utilities for use with the Java Plug-in.

Java web start tools Utilities for use with Java web start technology.

Java Monitoring andManagement (JMX) console

Used in conjunction with JMX technology.

Java web services tools Support the development of Java web serviceapplications.

Experimental tools These tools are experimental and might not beavailable with future releases of the Java SE JDK.

Table 1-2 Advanced Tool Categories

Tool Category Comment

Executing Your First Java Application 1-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 36: Sl275 Sg

Examining the JDK Software

JDK Libraries

The JDK libraries consist of predefined data types known as classes. Theseclasses are grouped on the basis of functionality into libraries. In Javatechnology, a library is called a package. Figure 1-3 highlights the librariesavailable with the Java SE JDK.

Figure 1-3 The Java SE JDK With the Java SE Libraries Highlighted

The major library groupings can be categorized as follows:

● User interface toolkits

The user interface toolkits consist of a set of libraries that contain theclasses necessary to create graphical user interfaces (GUI). Theselibraries range from libraries that provide GUI widgets (buttons,labels, tab panes, and so on) to libraries that support drag and drop,sound, accessibility, input, and printing.

● Integration libraries

The integration libraries provide support for the use of variousnetwork technologies that enable the integration of distributedapplications. These network technologies include RMI, CORBA,Java™ DataBase Connectivity (JDBC™), and Java Naming andDirectory Interface™ (JNDI) API.

1-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 37: Sl275 Sg

Examining the JDK Software

● Other base libraries

This is a general grouping of base-level libraries. This groupingincludes the security, internationalization, Java™ ManagementExtensions (JMX™) and other similar libraries.

● Language and utilities base libraries

This grouping consists of the core libraries required to create anapplication. At the core are the lang and util libraries. Otherlibraries included in this group are for concurrency (enabling thecreation of multithreaded applications), logging, and management.

Table 1-3 lists a small selection of the standard libraries and a sample ofclasses from the selected libraries.

Table 1-3 Sample Selection of Standard Libraries and Classes

Library Name Sample Classes in Library Purpose

java.lang Enum, Float, String,Object

Fundamental classes of the Javaprogramming language

java.util ArrayList, Calendar, Date Utility classes

java.io File, Reader, Writer Input and output supportclasses

java.math BigDecimal, BigInteger Arbitrary precision mathssupport classes

java.text DateFormat, Collator Text handling and formattingsupport classes

javax.crypto Cipher, KeyGenerator Cryptography support classes

java.net Socket, URL, InetAddress Networking support classes

java.sql ResultSet, Date,Timestamp

Structured Query Language(SQL) support classes.

javax.swing JFrame, JPanel Graphical user interface (GUI)classes

javax.xml.parsers DocumentBuilder,SAXParser

Extensible Markup Language(XML) support classes

Executing Your First Java Application 1-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 38: Sl275 Sg

Examining the JDK Software

Documentation for the JDK library classes (also known as Java technologyAPI documentation) is supplied as a set of HTML files. The layout of thisdocumentation is hierarchical, so that the home page lists all the packagesas hyperlinks. When you select a particular package hotlink, the classesthat are members of that package are listed. Selecting a class hotlink froma package page presents a page of information about that class. Figure 1-4shows one such class.

Figure 1-4 Java Technology API Documentation

1-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 39: Sl275 Sg

Examining the JDK Software

The main sections of a class document include the following:

● The class hierarchy

● A description of the class and its general purpose

● A list of attributes

● A list of constructors

● A list of methods

● A detailed list of attributes with descriptions

● A detailed list of constructors with descriptions and formalparameter lists

● A detailed list of methods with descriptions and formal parameterlists

Executing Your First Java Application 1-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 40: Sl275 Sg

Examining the JDK Software

JDK Deployment Technologies

Figure 1-5 highlights the deployment technologies available with the JDKsoftware.

Figure 1-5 The Java SE JDK With Deployment TechnologiesHighlighted

The JDK software contains support for deployment of client-side Javaapplications on the desktop. This support is provided by the followingtwo types of deployment technologies.

● Java Plug-in

Java Plug-in is a tool used for deploying Java applets that run insidea web browser. Supported web browsers include Internet Explorer,Mozilla, and Netscape Navigator.

Note – A Java applet is a restricted Java application that executes in abrowser.

● Java Web Start

Java Web Start is a tool used for deploying standalone Javaapplications on the desktop using the Java Network LaunchingProtocol (JNLP).

1-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 41: Sl275 Sg

Examining the JDK Software

The Java Virtual Machine (JVM)

This section provides an introduction to the JVM implementation byusing an Frequently Asked Questions (FAQ) format to highlight theinformation you need to know.

● What is a JVM implementation?

A JVM implementation executes Java technology applications, whichconsist of compiled Java classes. Compiled Java classes consist ofbyte code, so to be precise, a JVM implementation loads the classesthat compose a Java technology application and executes the bytecode contained in the classes. Figure 1-6 illustrates the relationshipbetween a Java technology application, the JVM implementation, theoperating system (OS) and the hardware platform.

Figure 1-6 The JVM Implementation, the Application, and the OS

● Are JVM implementations platform dependent?

JVM implementations are platform specific. For example, to executea Java application on a Solaris OS, you need the JVMimplementation that is specific to the Solaris OS. Similarly, to executea Java technology application on a Windows OS, you need the JVMimplementation that is specific to the Windows OS.

● Are Java technology applications platform dependent?

An application written using the Java programming language isplatform independent. Such an application can run on any platformthat contains a supporting JVM implementation.

Java Technology Application

JVM

OS

Hardware Platform

Executing Your First Java Application 1-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 42: Sl275 Sg

Examining the JDK Software

● What is a Java HotSpot™ virtual machine?

The first generation of JVM implementations interpreted byte code.The latest generation of JVM implementations compile the byte codeahead of its execution. This delayed dynamic compiling enables ahigh level of optimization and performance improvements overstatically compiled languages. The JVM compiler dynamicallyidentifies repeatedly executed blocks of code known as hotspots andpays particular attention to the optimization of the byte codes inthese hotspots. Hence the terminology hotspot JVM.

● What is a Java Hotspot™ Client VM?

On platforms typically used for client applications, the JDK softwarecomes with a virtual machine (VM) implementation called the JavaHotspot Client VM (client VM). The client VM is tuned for reducingstart-up time and memory footprint.

● What is a Java Hotspot Server VM?

On all platforms, the JDK software comes with an implementation ofthe Java virtual machine called the Java Hotspot Server VM (serverVM). The server VM is designed for maximum program executionspeed.

Figure 1-3 highlights the JVM implementations and supported platformsavailable for the JDK software.

Figure 1-7 The JDK Software Highlighting the JVM Implementationsand Supported Platforms

1-14 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 43: Sl275 Sg

Examining the JDK Software

The Java™ Runtime Environment (JRE™)

The JRE™ software is a subset of the JDK software and contains all thecomponents of the JDK that are required to execute a Java technologyapplication. It does not contain the components of the JDK required todevelop a Java technology application.

Figure 1-8 shows the components that are common to both the JDK andthe JRE.

Figure 1-8 Comparing the JDK With the JRE

Executing Your First Java Application 1-15Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 44: Sl275 Sg

Examining Java Application Loading and Execution

Examining Java Application Loading and Execution

Figure 1-9 illustrates the loading and execution of a Java application bythe JVM implementation.

Figure 1-9 Operation of the JRE

Java software source files are compiled in the sense that they are convertedinto a set of byte codes from the text format in which you write them. Thebyte codes are stored in .class files.

At runtime, the byte codes that make up a Java program are loaded,checked, and run by the Java HotSpot execution engine. In the case ofapplets, you can download the byte codes, and then they are executed bythe JVM implementation built into the browser.

The following section provides a more comprehensive discussion of thethree main tasks performed by the JVM implementation:

● Loads code – Performed by the class loader

● Verifies code – Performed by the byte-code verifier

● Executes code – Performed by the execution engine

Compile

TestGreeting.java

TestGreeting.class

javac

Runtime

Classloader

Bytecodeverifier

Hotspot Execution Engine

Hardware

Load fromhard disk,network,

orother

source

java

1-16 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 45: Sl275 Sg

Examining Java Application Loading and Execution

The Class Loader

The class loader loads all classes needed for the execution of a program.The class loader adds security by separating the namespaces for theclasses of the local file system from those imported from network sources.This limits any Trojan Horse applications, because local classes are alwaysloaded first.

After all of the classes have been loaded, the memory layout of theexecutable file is determined. At this point, specific memory addresses areassigned to symbolic references and the lookup table is created. Becausememory layout occurs at runtime, the Java technology interpreter addsprotection against unauthorized access into the restricted areas of code.

The Byte-Code Verifier

Java software code passes several tests before running on your machine.The JVM implementation puts the code through a byte-code verifier thattests the format of the code fragments and checks code fragments forillegal code, which is code that forges pointers, violates access rights onobjects, or attempts to change object type.

Note – All class files imported across the network pass through the byte-code verifier.

Verification Process

The byte-code verifier makes four passes on the code in a program. Itensures that the code adheres to the JVM specifications and does notviolate system integrity. If the verifier completes all four passes withoutreturning an error message, then the following is ensured:

● The classes adhere to the class file format of the JVM specification.

● There are no access restriction violations.

● The code causes no operand stack overflows or underflows.

● The types of parameters for all operational codes are correct.

● No illegal data conversions, such as converting integers to objectreferences, have occurred.

Executing Your First Java Application 1-17Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 46: Sl275 Sg

Creating a Simple Java Application

Creating a Simple Java Application

Like any other programming language, you use the Java programminglanguage to create applications. Code 1-2 and Code 1-3 show how tocreate a simple Java application that prints a greeting to the world.

Code 1-2 The TestGreeting.java Application

1 //2 // Sample "Hello World" application3 //4 public class TestGreeting {5 public static void main (String[] args) {6 Greeting hello = new Greeting();7 hello.greet();8 }9 }

Code 1-3 The Greeting.java Class

1 public class Greeting {2 public void greet() {3 System.out.println("hi");4 }5 }

1-18 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 47: Sl275 Sg

Creating a Simple Java Application

The TestGreetingApplication

This section describes the TestGreeting application.

Code 1-4 shows lines 1 to 3 of the sample application.

Code 1-4 Lines 1 to 3

1 //2 // Sample "Hello World" application3 //

Lines 1 to 3 in the program are comment lines, indicated by the //.

Code 1-5 Line 4

4 public class TestGreeting {

Line 4 declares the class name as TestGreeting. A class name specifiedin a source file creates a classname.class file when the source file iscompiled. If you do not specify a target directory for the compiler to use,this class file is in the same directory as the source code. In this case, thecompiler creates a file called TestGreeting.class. It contains thecompiled code for the public class TestGreeting.

Code 1-6 Line 5

5 public static void main (String args[]) {

Line 5 is where the program starts to execute. The Java technologyinterpreter must find this defined exactly as given or it refuses to run theprogram.

Other programming languages, notably C and C++, also use the main()declaration as the starting point for execution. The various parts of thisdeclaration are briefly described here. The details are covered later in thiscourse.

If the program is given any arguments on its command line, these arepassed into the main() method in an array of String called args. In thisexample, no arguments are used.

The following describes each element of Line 5:

Executing Your First Java Application 1-19Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 48: Sl275 Sg

Creating a Simple Java Application

● public – The method main() can be accessed by anything,including the Java technology interpreter.

● static – This keyword tells the compiler that the main() method isusable in the context of the class TestGreeting. No instance of theclass is needed to execute static methods.

● void – This keyword indicates that the method main() does notreturn any value. This is important because the Java programminglanguage performs careful type-checking to confirm that themethods called return the types with which they were declared.

● String args[] – This method declares the single parameter to themain method, args, and has the type of a String array. When thismethod is called, the args parameter contains the arguments typedon the command line following the class name; for example:

java TestGreeting args[0] args[1] . . .

Code 1-7 Line 6

6 Greeting hello = new Greeting();

Line 6 illustrates how to create an object, referred to by the hellovariable. The new Greeting syntax tells the Java technology interpreter toconstruct a new object of the class Greeting.

Code 1-8 Line 7

7 hello.greet();

Lines 7 demonstrates an object method call. This call tells the hello objectto greet the world. The implementation of this method is shown onLines 3–5 of the Greeting.java file.

Code 1-9 Lines 8 and 9

8 }9 }

Lines 8 and 9 of the program, the two braces, close the method main()and the class TestGreeting, respectively.

1-20 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 49: Sl275 Sg

Creating a Simple Java Application

The GreetingClass

This section describes the Greeting class.

Code 1-10 Line 1

1 public class Greeting {

Line 1 declares the Greeting class.

Code 1-11 Lines 2 to 4

2 public void greet() {3 System.out.println(“hi”);4 }

Lines 2 to 4 demonstrate the declaration of a method. This method isdeclared public, making it accessible to the TestGreeting program. Itdoes not return a value, so void is used as the return type.

The greet method sends a string message to the standard output stream.The println() method is used to write this message to the standardoutput stream.

Code 1-12 Line 5

5 }

Line 5 closes the class declaration for the Greeting class.

Executing Your First Java Application 1-21Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 50: Sl275 Sg

Creating a Simple Java Application

Compiling and Running the TestGreetingProgram

After you have created the TestGreeting.java source file, compile it bytyping the following line:

javac TestGreeting.java

If the compiler does not return any messages, the new fileTestGreeting.class is stored in the same directory as the source file,unless specified otherwise. The Greeting.java file has been compiledinto Greeting.class. This is done automatically by the compiler becausethe TestGreeting class uses the Greeting class.

To run your TestGreeting application, use the Java technologyinterpreter. The executables for the Java technology tools (javac, java,javadoc, and so on) are located in the bin directory.

java TestGreeting

Note – You must set the PATH environment variable to find java andjavac; ensure that it includes java_root/bin (where java_rootrepresents the directory root where the Java technology software isinstalled).

1-22 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 51: Sl275 Sg

Creating a Simple Java Application

Troubleshooting the Compilation

The following sections describe errors that you might encounter whencompiling code.

Compile-Time Errors

The following are common errors seen at compile time, with examples ofcompiler-generated messages. Your messages can vary depending onwhich version of the JDK you are using.

● javac: Command not found

The PATH variable is not set properly to include the javac compiler.The javac compiler is located in the bin directory below theinstalled JDK software directory.

● Greeting.java:4:cannot resolve symbolsymbol : method printl (java.lang.String)location: class java.io.PrintStreamSystem.out.printl("hi");

^

The method name println is typed incorrectly.

● Class and file naming

If the .java file contains a public class, then it must have the samefile name as that class. For example, the definition of the class in theprevious example is:

public class TestGreeting

The name of the source file must be TestGreeting.java. If younamed the file TestGreet.java, then you would get the errormessage:

TestGreet.java:4: Public class TestGreeting must bedefined in a file called "TestGreeting.java".

● Class count

You should declare only one top-level, non-static class to be public ineach source file, and it must have the same name as the source file. Ifyou have more than one public class, then you will get the samemessage as in the previous bullet for every public class in the filethat does not have the same name as the file.

Executing Your First Java Application 1-23Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 52: Sl275 Sg

Creating a Simple Java Application

Runtime Errors

Some of the errors generated when typing java TestGreeting are:

● Can't find class TestGreeting

Generally, this means that the class name specified on the commandline was spelled differently than the filename.class file. The Javaprogramming language is case-sensitive.

For example,

public class TestGreet {

creates a TestGreet.class, which is not the class name(TestGreeting.class) that the runtime expected.

● Exception in thread "main" java.lang.NoSuchMethodError:main

This means that the class you told the interpreter to execute does nothave a static main method. There might be a main method, but itmight not be declared with the static keyword or it might have thewrong parameters declared, such as:

public static void main(String args) {

In this example, args is a single string, not an array of strings.

public static void main() {

In this example, the coder forgot to include any parameter list.

1-24 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 53: Sl275 Sg

Creating a Simple Java Application

Figure 1-10 illustrates how Java technology programs can be compiledand then run on the JVM implementation. There are manyimplementations of JVM on different hardware and operating systemplatforms.

Figure 1-10 Java Technology Runtime Environment

JVM

Co

mp

ile

TestGreeting.java

TestGreeting.class

javac

Greeting.java

Greeting.class

Also compiles

Ru

nti

me

Also loads

UNIX®

JVM

DOS

JVMJavaOS™

Can run on multiple platforms

Executing Your First Java Application 1-25Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 54: Sl275 Sg
Page 55: Sl275 Sg

Module 2

Creating JavaTechnologyApplications

Objectives

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

● Investigate the composition of a Java technology application

● Examine custom class creation

● Compare static and dynamic views of a Java application

● Create, use, and dispose of objects

2-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 56: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following reference provides additionalinformation on the topics described in this module:

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

2-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 57: Sl275 Sg

The Composition of a Java Application

The Composition of a Java Application

A house is composed of rooms with (at least) one designated entry room.Similarly, a Java technology application is composed of classes with one classdesignated as the application main class. The application main class providesthe entry point for the execution of the application. Figure 2-1 comparesthe similarities between a house design and a Java application design.

Figure 2-1 Application Composition Concept Illustration

All houses require some degree of customization. You customize a houseby customizing its (composing) rooms. In most cases, you customize aroom by the selecting standard components required by the room,varying the quantity of each component, and arranging the componentsin the room. For example, you customize a kitchen by selectingcupboards, work surfaces, and appliances, and varying the quantity andlayout of each of these components.

House composed of rooms

Account

ATM

SimpleBank

SimpleBankApp

Bankingapplication composed of classes

Creating Java Technology Applications 2-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 58: Sl275 Sg

The Composition of a Java Application

Figure 2-2 shows the custom classes specific to the simple bankingapplication.

Figure 2-2 The Banking Application: Custom Classes

The custom classes required to build the banking application are:

● Account

The Account class is an abstraction of a bank account. Whenever thebanking application needs a new account, an Account object(Account instance) is created using the Account class.

● ATM

The ATM class is an abstraction of an Automatic Teller Machine(ATM). The simplified banking application presented in this modulecreates a single instance of the ATM class. The ATM instance providesthe GUI interface required by bank customers to create bankaccounts (Account instances) and use them (deposit or withdrawfunds or check the balance).

● SimpleBank

The SimpleBank class is a simplified abstraction of a bank. TheSimpleBank class defines a set of fields and methods that representthe key attributes and operations of a simplified version of a bank.

● SimpleBankApp

The SimpleBankApp class is an application entry class for thebanking application.

Account

ATM

SimpleBank

SimpleBankApp

<<uses>>

2-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 59: Sl275 Sg

The Composition of a Java Application

As stated earlier, the banking application is composed of a set of customclasses that are specific to the banking application. These classes usestandard classes from the JDK library or possibly other utility classesobtained from other projects. Figure 2-3 illustrates some of the standardclasses from the JDK software used by the banking application.

Figure 2-3 The Banking Application: Custom and Standard Classes

Account

ATM

SimpleBank

SimpleBankApp

JDK

JDK Library:StringJFrameJTableJlabel...

JDK standard classes Banking applicationcustom classes

<<uses>>

Creating Java Technology Applications 2-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 60: Sl275 Sg

Examining Custom Class Creation: Concept to Implementation

Examining Custom Class Creation: Concept toImplementation

This section examines the concepts and process associated with creatingclasses. It consists of the following sections.

● Examining class creation

● Examining the application main class

Examining Class Creation

This section uses the following FAQs to examine the design anddeclaration concepts of a Java class.

● What does a class represent?

A Java class represents a type definition (class type). For example,the Account class is a type of class that represents or defines a bankaccount. Similarly, the Date class from the JDK library is a type ofclass that represents or defines a date.

● What does an instance of a class represent?

An instance of a class represents a virtual entity of whatever the class(type) represents. For example, an instance of the Account classrepresents a virtual bank account entity. Similarly an instance of theDate class represents a virtual date instance. Each virtual instancecontains state. For example, my bank account contains state todistinguish itself from your bank account.

● What is an object?

An object has both state and behavior. An object is an alternativeterm for a class instance.

2-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 61: Sl275 Sg

Examining Custom Class Creation: Concept to Implementation

● What information is contained in a class (type definition)?

A class contains two types of information:

● The attributes of the type

Every type has an optional set of attributes. For example, theattributes of the Account class are customer and balance.Attributes are declared as fields in the class using name anddata type pairs. For example, Table 2-1 shows the attributes ofthe Account class.

● The operations of the type

The operations of the type are expressed using methoddeclarations in the class. For example, Table 2-2 shows possiblemethods of the Account class.

● What is a Unified Modelling Language (UML) class diagram?

A UML class diagram defines a set of notations to represent objecttechnology abstractions, such as class, object, and so on. The UMLnotations that are of most interest for this section are: concise classdiagram, detailed class diagram, and object diagram.

Table 2-1 Account Class Attributes

Attribute Name Attribute’s DataType Comment Field Declaration

customer String Unique customer ID String customer;

balance double The current balancein the account

double balance;

Table 2-2 Account Class Operations

Method Declaration Comment

double getBalance() {// ...} Returns current balance

void deposit(double sum) {// ...} Adds sum to balancefield

void withdraw(double sum){// ...} Subtracts sum frombalance field

String getCustomer(){// ...} Returns customer ID

String getDetails(){// ...} Returns account details

Creating Java Technology Applications 2-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 62: Sl275 Sg

Examining Custom Class Creation: Concept to Implementation

A class diagram represents a class. Figure 2-4 shows the detailedUML class diagram of the Account class.

Figure 2-4 Detailed UML Class Diagram of the Account Class

Note – Constructors are similar to methods in that they both containexecution code. However, they differ because a constructor is onlyexecuted when the JVM implementation creates an instance of the class. Aconstructor normally contains field initialization code.

Figure 2-5 shows the concise UML class diagram for the Accountclass.

Figure 2-5 Concise UML Class Diagram of the Account Class

Figure 2-5 shows the UML object diagram of an Account instance.The object diagram represents an instance of the class.

Figure 2-6 UML Object Diagram of the Account Class

● Where are the String and double data types used by the Accountclass defined?

The Account class uses the following Java technology data types.

● The String class

The String class is defined in the java.lang package. Thejava.lang package is part of the standard class library that issupplied with the JDK software.

Account

customer:Stringbalance:double

getBalance():doubledeposit(sum:double):voidwithdraw(sum:double):voidgetCustomer():StringgetDetails():String

Class name

Fields

Methods

ConstructorAccount(name:String)

Account

:Account

2-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 63: Sl275 Sg

Examining Custom Class Creation: Concept to Implementation

Every Account object contains a String object representing thecustomer ID. Figure 2-7 shows the composition relationshipbetween the Account and String classes.

Figure 2-7 UML Class Diagram Showing the Composition RelationshipBetween the Account Class and String Class

● The double primitive

The double data type is not a class type. It is one of eightprimitive data types defined by the Java language specification.The eight primitive types are: boolean, char, byte, short, int,long, float, and double.

● What are the different Java class file formats?

A Java technology class has two file formats:

● Source file format

The source file format is a human-readable form of a class file.All source files have java file name extensions. For example,Account.java and SimpleBank.java.

● Class file format

The class file format is a JVM-readable form of a class file. Allclass files have class file name extensions. For example,Account.class and SimpleBank.class.

● How do you create a Java class source file?

You create a source file using a text editor. Code 2-1 illustrates anexample of a Java technology class source file.

Code 2-1 The Account Class: Source File Format

1 public class Account{2 String customer;3 double balance;45 /** Creates a new instance of Account */6 public Account(String name) {7 customer = name;8 }910 public double getBalance() {11 return balance;

Account String

Creating Java Technology Applications 2-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 64: Sl275 Sg

Examining Custom Class Creation: Concept to Implementation

12 }1314 public void deposit(double sum) {15 if (sum > 0) {16 balance = balance + sum;17 }18 }1920 public void withdraw(double sum) {21 if ( sum <= balance && sum > 0) {22 balance = balance - sum;23 }24 }2526 public String getCustomer() {27 return customer;28 }2930 public String getDetails() {31 return "Type: " + "Account\n"32 + "Customer: " + customer + "\n"33 + "Balance: " + balance;34 }35 }

● How do you create a Java class .class file?

You create a .class file by compiling the corresponding source fileusing the Java compiler javac. For example, Figure 2-8 illustrates theapplication of the javac command.

Figure 2-8 Using the javac Command

The Java compiler javac is command-line tool contained in thetoolset supplied as part of the JDK software.

Account.java

Account.class

javacjavac Account.java

2-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 65: Sl275 Sg

Examining Custom Class Creation: Concept to Implementation

Examining Application Main Classes

This section uses the following FAQs to examine the design andimplementation concepts of a Java technology application main class.

● What is the function of an application main class?

Every Java application requires an application main class, which isthe entry point for the application. It can also be referred to as theapplication launch class.

● What is the primary requirement for the application main class?

An application main class must have a main method that conformsto the following method signature:

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

The code within the body of the method depends on the application.However, in principle, the main method initiates the creation of theobjects that form the application. For example, Code 2-2 illustratesan application main class.

Code 2-2 The Application Main Class of the Simple Bank Application

1 public class SimpleBankApp {2 public static void main(String[] args) {3 SimpleBank bank = new SimpleBank();4 ATM atm = new ATM(bank);5 }6 }

● Are main methods restricted to application main classes only?

The presence of a main method provides a code execution entrypoint to the Java application launcher java. Consequently, any classcan include a main method.

You can include a main method in a class for either of the followingreasons:

● To execute test code to test the code contained in the othermethods of the class.

● To launch an application

● What command is used to launch a Java application?

To launch a Java application, you use java, the Java applicationlauncher command-line tool. For example, to launch the simplebanking application, type the following command:

java SimpleBankApp

This command causes the main method of the SimpleBankApp classto execute.

Creating Java Technology Applications 2-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 66: Sl275 Sg

Comparing Static and Dynamic Views of a Java Application

Comparing Static and Dynamic Views of a JavaApplication

A Java application is an object-oriented application. An object-orientedapplication presents two views:

● A static view

● A dynamic view

This section examines the static and dynamic views of a Java application.

A Static View

A static view of an object-oriented application is the collection of classesthat together constitute the application. One way to think of a static viewof a Java application is to consider the view presented by the classes of theapplication when they are stored in the file system. Figure 2-9 illustratesthe static conceptual view of the simple banking application.

Figure 2-9 The Banking Application: Static Conceptual View

Your task as a Java application writer is to use the standard classessupplied by the JDK software to create the custom classes required foryour application. During application development, the predominant focusis on classes.

Note – A Java technology application is not stored in a pre-assembled(linked) format. Instead each class is stored individually.

Account

ATM

SimpleBank

SimpleBankApp

JDK

JDK Library:StringJFrameJTableJlabel...

JDK standard classes Banking applicationcustom classes

<<uses>>

2-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 67: Sl275 Sg

Comparing Static and Dynamic Views of a Java Application

A Dynamic View

The dynamic view of a Java technology application is the view it presentsduring execution. During execution, the predominant focus is on objectsrather than classes. In particular, the focus is on object creation, referencingand use.

Code 2-3 shows the main method of the application main class for thesimple banking application.

Code 2-3 The Simple Banking Application Main Class

1 public class SimpleBankApp {2 public static void main(String[] args) {3 SimpleBank bank = new SimpleBank();4 ATM atm = new ATM(bank);5 }6 }

1. The simple banking application is launched by the command:

java SimpleBankApp

This triggers the execution of the main method of theSimpleBankApp class (Code 2-3) resulting in the following sequenceof events.

2. The JVM implementation loads the SimpleBankApp class and all theclasses needed for the execution of the main method.

3. The execution of the following line of code results in the creation ofan instance of the SimpleBank class.

3 SimpleBank bank = new SimpleBank();

Figure 2-10. illustrates the object created in this step.

Figure 2-10 UML Class Diagram Showing the SimpleBank Object

bank:SimpleBank

Object reference

Object data type

Creating Java Technology Applications 2-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 68: Sl275 Sg

Comparing Static and Dynamic Views of a Java Application

2-14 Java™ Programming Language

You should note the following observations.

● A SimpleBank object is created by the execution of the clause:

new SimpleBank()

To create an object, you need to apply the new keyword on theconstructor of the class. A constructor contains initialization code forthe JVM implementation to initialize the fields of the new object itcreates.

A constructor has the same name as the class. For example, theconstructor of the SimpleBank class is SimpleBank().

● A SimpleBank reference with the name bank was declared by theexecution of the clause:

SimpleBank bank

An object reference has a name and a type associated with it. In thiscase, the name of the reference is bank and its type is SimpleBank.

An object reference is not an object. It is a reference to an object. Tohelp distinguish between an object and a reference, consider thefollowing analogy. If you had a son, your son might call you dad.Your neighbor might call you buddy and your father might call youson. In this analogy, you are the object but you are referred to bydifferent names.

The assignment operator in the following statement assigns the newlycreated SimpleBank object to the reference bank.

SimpleBank bank = new SimpleBank();

4. The execution of the following line of code creates an instance of theATM class.

4 ATM atm = new ATM(bank);

Figure 2-11. illustrates the objects resulting from this step.

Figure 2-11 UML Class Diagram Showing the ATM and SimpleBankObjects

You should note the following observations.

● An ATM object instance is created by the execution of the clause:

new ATM(bank)

In this example, the ATM constructor accepts a reference to aSimpleBank object, which in this case is bank.

atm:ATM bank:SimpleBank

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

Page 69: Sl275 Sg

Comparing Static and Dynamic Views of a Java Application

● An ATM reference with the name atm was declared by the executionof the clause:

ATM atm

The assignment operator in the following statement assigns thenewly created ATM object to the reference atm.

ATM atm = new ATM(bank);

Creating Java Technology Applications 2-15Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 70: Sl275 Sg

Comparing Static and Dynamic Views of a Java Application

5. The execution of the ATM class constructor (code not shown) resultsin the creation of many other objects. The most significant of these isa GUI-based user interface that mimics the user interfacefunctionality of an ATM machine. Figure 2-12 illustrates the simplebank application’s ATM user interface.

Figure 2-12 Simple Bank Application’s ATM User Interface

2-16 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 71: Sl275 Sg

Comparing Static and Dynamic Views of a Java Application

6. Using the ATM user interface, the simple banking application usercan perform the following actions.

● Create a new account

Creating a new account is a service provided by a method ofthe SimpleBank instance. Creating a new account results in thecreation of an Account instance. The SimpleBank instancemanages the reference to the account objects it creates.

Note – In normal circumstances, account creation is a function performedby a bank employee and not by a bank client at the ATM.

● Access an existing account

A user can access a previously created account by entering thecustomer information. The SimpleBank instance then locatesthe account and retrieves it.

● Operate on an account

An Account instance that is accessed can be operated on asfollows:

● Deposit

A user can deposit additional funds. This service isprovided by the deposit method of the Account instance.For example, to deposit 50 dollars into the currentlyaccessed account, you enter 50 in the amount text field andpress the Deposit button. Pressing he Deposit buttontriggers code execution similar to the following line ofcode:

account.deposit(50.0);

Where account is the reference variable referencing thecurrently accessed Account object. You should examine thedeposit method declared in the Account class shown inCode 2-1 on page 2-9.

● Withdraw

A user can withdraw funds. This service is provided by thewithdraw method of the Account instance. Assuming 10was entered in the amount text field, pressing theWithdraw button triggers code execution similar to thefollowing line of code:

account.withdraw(10.0);

Creating Java Technology Applications 2-17Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 72: Sl275 Sg

Comparing Static and Dynamic Views of a Java Application

Where account is the reference variable referencing thecurrently accessed Account object. You should examine thewithdraw method declared in the Account class shown inCode 2-1 on page 2-9.

● Get details

A user can obtain account details. This service is providedby the getDetails method of the Account instance.Pressing the Refresh button triggers code execution similarto the following line of code:

String details = account.getDetails();

Where account is the reference variable referencing thecurrently accessed Account object. The ATM GUI displaysthe details in the Account Details text area. You shouldexamine the getDetails method declared in the Accountclass shown in Code 2-1 on page 2-9.

● Save the account data

This service is performed automatically by the SimpleBankinstance.

2-18 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 73: Sl275 Sg

Creating, Using, and Disposing of Objects

Creating, Using, and Disposing of Objects

During the execution of a Java application, the application creates,interacts with, and disposes of objects. This section uses a FAQ list topresent object management in a Java application.

For the purposes of this discussion, this section references the Accountclass shown in Code 2-1 on page 2-9. Figure 2-13 shows the UML classdiagram that corresponds to the Account class.

Figure 2-13 The Account Class UML Class Diagram

● What information relevant to object structure is presented in a classdiagram?

Although the exact size of a Java object depends on theimplementation, the JVM implementation allocates sufficient spacefor the object to hold data for each field of the class.

In the case of the Account class, the balance field is a double,which is a primitive type, but the customer field is a String, whichis a class type. For the balance field, the JVM implementationallocates sufficient space to hold a double value. For the customerfield, the JVM implementation allocates space to hold a referencevalue. In simplistic terms, the reference value indicates the locationof the String object that represents the customer. Figure 2-14 showsan Account object in memory.

Figure 2-14 The Account Object: Illustrative Memory Footprint

Account

customer:Stringbalance:double

getBalance():doubledeposit(sum:double):voidwithdraw(sum:double):voidgetCustomer():StringgetDetails():String

Class name

Fields

Methods

ConstructorAccount(name:String)

balance

customer

a_double_value

a_reference_value

Creating Java Technology Applications 2-19Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 74: Sl275 Sg

Creating, Using, and Disposing of Objects

● What information relevant to object creation is presented in a classdiagram?

The class diagram shows that the Account class declares a singleconstructor: Account(name:String).

A constructor creates an object of the specified class type, initializesthe fields, and returns a reference to the newly created object. Youare required to assign the object reference returned by theconstructor for future interactions with the newly created object. Afailure to retain the reference results in an unusable object thateventually is purged (garbage collected) from memory. Code 2-4illustrates the creation of an object and the retention of its reference.

Code 2-4 Example of Using a Constructor

Account myAcct; // declaring a reference variablemyAcct = new Account(“Me”);

Code 2-4 illustrates the use of the new keyword in combination withthe Account class constructor to create an Account object.Figure 2-15 shows memory resulting from the execution of Code 2-4.

Figure 2-15 A Referenced Account Object

● What information relevant to object interaction is presented in a classdiagram?

The class diagram shows that the Account class declares two fields(balance and customer) and five methods (getBalance, deposit,withdraw, getCustomer, and getDetails).

To interact with an object, you need the following:

● A reference to the object

● The names of the accessible members of the object.

The class diagram shows that the Account class declares twofields (balance and customer) and five methods (getBalance,deposit, withdraw, getCustomer, and getDetails).

balance

customer

0.0

Reference to stringobject containing “Me”

:StringmyAcct:Account

2-20 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 75: Sl275 Sg

Creating, Using, and Disposing of Objects

Code 2-5 illustrates the use of the ‘.’ operator to interact with anobject.

Code 2-5 Example of Interacting With an Object

1 Account myAcct; // declaring a reference variable2 myAcct = new Account(“Me”); // creating an object3 myAcct.balance = 200.0; // assigning to a field4 myAcct.deposit(300.0); // invoking a method5 myAcct.withdraw(100.00); // invoking a method6 double myBalance; // declaring a primitive variable7 myBalance = myAcct.getBalance();

● Can you use multiple references to refer to the same object?

You can reference the same object using multiple references, asillustrated in Code 2-6.

Code 2-6 Using Multiple References

1 Account myAcct; // declaring a reference variable2 myAcct = new Account(“Me”); // creating an object3 myAcct.deposit(200); // use myAcct to deposit4 Account myChildAcct;5 myChildAcct = myAcct;6 myChildAcct.withdraw(300.0);

● Once assigned, can you reassign a reference?

You can reassign a reference to another object provided the object isof the same class type as the reference, as illustrated in Code 2-7.

Code 2-7 Reassigning References

1 Account myAcct; // declaring a reference variable2 myAcct = new Account(“Me”); // creating an object3 myAcct.deposit(200); // use myAcct to deposit4 Account myChildAcct;5 myChildAcct = myAcct;6 myChildAcct.withdraw(300.0);7 myChildAcct = new Account(“Child”);8 myAcct = myChildAcct;

Creating Java Technology Applications 2-21Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 76: Sl275 Sg

Creating, Using, and Disposing of Objects

● Once created how do you dispose of an object?

Java technology provides a garbage collector to dispose of unwantedobjects. Any object that is no longer referenced (that is an object thathas no reference variables referring to it) is a candidate for garbagecollection. Such objects are removed from memory at the next sweepof the garbage collector. For example, Table 2-3 illustrates the historyof the values contained in reference variables myAcct andmyChildAcct, shown in Code 2-7 on page 2-21.

At the execution of line 8 of Code 2-7 on page 2-21, the Accountobject Account(“Me”) is de-referenced and becomes a candidate forgarbage collection.

The garbage collector executes periodically as a background task.The frequency of the garbage collection depends on the garbagecollection algorithm used by the JVM implementation. You canoptionally configure the garbage collector for your particularapplication; however, modern JVM implementations have built-indynamic optimization strategies. A discussion of the selection andconfiguration of the garbage collector is beyond the scope of thismodule.

Table 2-3 Examining Object Referencing in Code 2-7

Line Number Reference Variable Object Referenced

1 myAcct none

2 myAcct Account(“Me”)

4 myAcctmyChildAcct

Account(“Me”)none

5 myAcctmyChildAcct

Account(“Me”)Account(“Me”)

7 myAcctmyChildAcct

Account(“Me”)Account(“Child”)

8 myAcctmyChildAcct

Account(“Child”)Account(“Child”)

2-22 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 77: Sl275 Sg

Module 3

Creating aClass:Fieldsand ConstructorsSyntax

Objectives

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

● Examine the class declaration

● Declare and initialize fields using defaults, explicit values, andconstructors

● Examine comments, white space, and keywords

● Examine directory layout and packages

3-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 78: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following reference provides additionalinformation on the topics described in this module:

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

● Bates, Sierra. Head First Java, Second Edition. O’Reilly Media. 2005.

3-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 79: Sl275 Sg

Introducing the classDeclaration

Introducing the classDeclaration

A class declaration defines a new type. This section demonstrates who candeclare a user-defined Java class using the following steps:

1. Associate the new class with a package.

2. Declare the foreign classes used by the new class.

3. Declare the fields of the class.

4. Declare the constructors (if any) required to initialize the fields of theclass.

5. Declare the methods of a class.

Associating a New Class With a Package

A package is a Java mechanism for organizing (related) classes. A packageprovides a namespace for the classes it contains. All class files in the samepackage are stored in the same directory. You can view a group of relatedclasses organized into a package as a library. Code 3-1 shows an exampleof how you associate a class with a package.

Code 3-1 Declaring a Class in a Package

1 package finance; // package statement23 class Stock {4 // Internals of the class declarations not shown for clarity reason5 }

Note – In a production environment, you use a Universal ResourceLocator (URL) type naming convention to uniquely specify a packagename. For example:package com.mycompany.myproject.finance;

The Stock class, shown in Code 3-1 is declared in the finance package.You should note the following information associated with the use of apackage statement.

● The package statement (Line 1 of Code 3-1) must be the first non-comment statement of a class declaration.

Creating a Class: Fields and Constructors Syntax 3-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 80: Sl275 Sg

Introducing the classDeclaration

● If you omit the package statement, the class is said to belong to thedefault package.

In the interest of avoiding name clashes, you should always declare aclass in a package.

● The fully qualified name of the Stock class, shown in Code 3-1 isfinance.Stock.

Note – Text in Code 3-1 on page 3-3 that is followed by // is a comment.

Declaring the Foreign Classes Used by the New Class

The term foreign class refers to any class that is declared in a differentpackage to that in which you are declaring the new class. The importstatement provides a mechanism to declare the classes from otherpackages used by your class. For example, line 3 of Code 3-2 shows theStock class importing the Date class from the java.util package.

Code 3-2 Declaring Imported Classes

1 package finance;23 import java.util.Date;4 // Additional import statements if required go here56 class Stock {7 // Implementation of the stock class8 }

You should note the following information associated with the use ofimport statements.

● Import statements are declared between the package statement andthe class declaration.

● Classes in the same package are not required to be imported. Eachclass used from an external package requires an import statement.

3-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 81: Sl275 Sg

Introducing the classDeclaration

The alternative to using the import statement is to reference theclasses that need importing using the fully qualified name of theclasses. For example, the omission of the import statement inCode 3-2 requires the use of java.util.Datewherever the Date classis referenced in the Stock class.

● The Java language provides a syntax to import all the classes from asingle package. For example, if the Stock class uses multiple classesfrom the java.util package, you might use the following importstatement.

import java.util.*;

● You are not required to provide import statements to import anyclasses from the java.lang package. These classes are automaticallyimported.

Declaring the Fields of the Class

Code 3-3 shows three field declarations made within the Stock class. Eachfield represents an attribute (or state) of objects of the Stock data type. Afield declaration is a variable declaration made within the class butoutside a method or constructor declaration.

Code 3-3 Declaring Fields in a Class

1 package finance;23 import java.util.Date;45 class Stock {6 // Field declarations7 String symbol;8 double price;9 Date date;1011 // Constructor declarations12 // Method declarations1314 }

You should note the following information associated with fielddeclarations.

● The following syntax is the simplest syntax for a field declaration:

data-type identifier;

Creating a Class: Fields and Constructors Syntax 3-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 82: Sl275 Sg

Introducing the classDeclaration

For example:

double price;

The data_type of a field can be any Java technology primitive datatype, such as double or a class data type, such as Date. Java datatypes are described in more detail in ‘‘Declaring Fields: SelectingClass Types’’ on page 3-11.

Identifiers are described in more detail in ‘‘Declaring Fields:Formatting Identifiers’’ on page 3-15.

● The following syntax includes the provision of an initial value for thefield:

data_type identifier = initial_value;

For example:

double price = 25.50;

● The following syntax enables multiple field declarations of the samedata type using a single declaration statement:

data_type identifier1, identifier2, identifier3;

For example:

Date birthDay, anniversary;

Declaring the Constructors of the Class

A constructor can dynamically provide initial values to the fields of aclass instance. Code 3-4 shows a single constructor declaration madewithin the Stock class. A class can have multiple constructors.

Code 3-4 Declaring Constructors in a Class

1 package finance;23 import java.util.Date;45 class Stock {6 // Field declarations7 String symbol;8 double price;9 Date date;1011 // Constructor declarations12 Stock(String stockSymbol) {13 symbol = stockSymbol;

3-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 83: Sl275 Sg

Introducing the classDeclaration

14 }1516 // Method declarations1718 }

The information about constructor declarations supplied in this section islimited to where constructors are declared. An in-depth discussion ofconstructor declarations is provided in ‘‘Field Initialization UsingConstructors’’ on page 3-19.

Declaring the Methods of the Class

Methods implement the behavior of the objects of the class type. Code 3-5shows method declarations made within the Stock class. A class can havemultiple methods.

Code 3-5 Declaring Methods in a Class

1 package finance;23 import java.util.Date;45 class Stock {6 // Field declarations7 String symbol;8 double price;9 Date date;1011 Stock(String stockSymbol) {12 symbol = stockSymbol;13 }1415 void updatePrice (Date updateTime, double newPrice) {16 date = updateTime;17 price = newPrice;18 }1920 double getSymbol() {21 return symbol;22 }2324 double getPrice() {25 return price;26 }

Creating a Class: Fields and Constructors Syntax 3-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 84: Sl275 Sg

Introducing the classDeclaration

2728 Date getDate() {29 return date;30 }31 }

The information about method declarations supplied in this section islimited to where methods are declared. An in-depth discussion of methoddeclarations is provided in a subsequent module.

3-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 85: Sl275 Sg

Declaring Fields: Selecting Primitive Data Types

Declaring Fields: Selecting Primitive Data Types

The Java programming language has many built-in data types that fallinto two broad categories:

● Primitive types – Are simple values as opposed to objects.

● Class types – Are used for more complex types, including all of thetypes that you declare yourself. Class types are used to create objects.

The Java programming language defines eight primitive data types thatcan be grouped into four categories:

● Logical – boolean

Logical values are represented using the boolean type, which takesone of two values: true or false.

● Textual – char

Single characters are represented by using the char type. A charrepresents a 16-bit, unsigned Unicode character.

● Integral – byte, short, int, and long

There are four integral types in the Java programming language.Each type is declared using one of the keywords byte, short, int,or long.

● Floating point – double and float

There are two floating point data types: float or double. The formatof a floating point number is defined by following the format of theInstitute of Electrical and Electronics Engineers (IEEE) 754, using thesizes shown in Table 3-1. This format is platform independent.

Table 3-1 provides a comparison of the eight primitive types.

Table 3-1 Primitive Data Type Comparisons

PrimitiveType Category Integer or Float

Length Range

boolean Logical Not applicable true, false

char Textual 16 bits 0 to 216-1

byte Integral 8 bits -27 to 27 -1

short Integral 16 bits -215 to 215 -1

int Integral 32 bits -231 to 231 -1

Creating a Class: Fields and Constructors Syntax 3-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 86: Sl275 Sg

Declaring Fields: Selecting Primitive Data Types

Primitive Type Literals

Table 3-2 provides the syntax for declaring literals of the primitive datatypes.

long Integral 64 bits -263 to 263 -1

float Floating point 32 bits

double Floating point 64 bits

Table 3-1 Primitive Data Type Comparisons

PrimitiveType Category Integer or Float

Length Range

Table 3-2 Primitive Data Type Literals

PrimitiveType Syntax or Example Comment

boolean true, false Boolean literals are limited to: true or false.

char ‘a’‘\t’‘\u????’

The letter a.A tab character.A specific Unicode character, ????, is replacedwith exactly four hexadecimal digits.For example, ’\u03A6’ is the Greek letter phi [✦].

byte 5 In range int literals.

short 300 In range int literals.

int 20770xBAAC

This is the decimal form for the integer 2.The leading 0 indicates an octal value.The 0x prefix indicates a hexadecimal value.All integer literals default to int.

long 2L

077L0xBAACL

The L (or lower case l) indicates that the decimalvalue 2 is represented as a long value.The leading 0 indicates an octal value.The 0x prefix indicates a hexadecimal value.

float 52.56f32.0F

You can declare a literal of type float byappending F or f to the value.

double 100.25100.25d100.25D

Floating point literals are double unless declaredexplicitly as float. You can optionally append afloating point literal with d or D.

3-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 87: Sl275 Sg

Declaring Fields: Selecting Class Types

Declaring Fields: Selecting Class Types

Class types are used for more complex types, including all of the typesthat you declare yourself. Class types are used to create objects and can beobtained from the following sources:

● Java SE class libraries – Supplied as part of the Java SE JDK software.Each new release of the Java SE JDK software has new classes addedto the pool of classes released with the first release of the JDK.

● Commercial or open source class libraries – Obtained from third-party vendors or from the open source community.

● User-created or in-house classes – Created by you or classes availableto you that have been created for other projects in your organization.

The Java SE Class Libraries

This section provides a brief look at some of the class libraries andassociated classes included in the Java SE JDK. Table 3-3 lists a smallselection of the standard libraries and a sample of classes from theselected libraries.

Table 3-3 Sample Selection of Standard Libraries and Classes

Library Name Sample Classes in Library Purpose

java.lang Enum, Float, String,Object

Fundamental classes of the Javaprogramming language

java.util ArrayList, Calendar, Date Utility classes

java.io File, Reader, Writer Input, output support classes

java.math BigDecimal, BigInteger Arbitrary precision mathssupport classes

java.text DateFormat, Collator Text handling and formattingsupport classes

javax.crypto Cipher, KeyGenerator Cryptography support classes

java.net Socket, URL, InetAddress Networking support classes

java.sql ResultSet, Date,Timestamp

Structured Query Language(SQL) support classes.

javax.swing JFrame, JPanel Graphical user interface (GUI)classes

Creating a Class: Fields and Constructors Syntax 3-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 88: Sl275 Sg

Declaring Fields: Selecting Class Types

The remainder of this section focuses on the String class and wrapperclasses (class equivalents of primitive types).

The StringClass

You use the String type, which is not a primitive but a class, to representsequences of characters. The characters themselves are Unicode, and thebackslash notation shown previously for the char type also works in aString.

A String literal is enclosed in double quote marks:

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

The following are examples of the declarations and initialization ofString type variables:

// declares two String variables and initializes themString greeting = "Good Morning !! \n";String errorMessage = "Record Not Found !";

// declares two String variablesString str1, str2;

Declaring a String literal creates a String object. You can also createString objects using the new keyword. For example,

// using the new keyword to create a String objectString s1 = new String(“Hello”);

javax.xml.parsers DocumentBuilder,SAXParser

Extensible Markup Language(XML) support classes

Table 3-3 Sample Selection of Standard Libraries and Classes

Library Name Sample Classes in Library Purpose

3-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 89: Sl275 Sg

Declaring Fields: Selecting Class Types

Wrapper Classes

The Java programming language does not look at primitive data types asobjects. For example, numerical, boolean, and character data are treated inthe primitive form for the sake of efficiency. The Java programminglanguage provides wrapper classes to manipulate primitive data elementsas objects. Such data elements are wrapped in an object created aroundthem. Each Java primitive data type has a corresponding wrapper class inthe java.lang package. Each wrapper class object encapsulates a singleprimitive value. (See Table 3-4.)

Note – These wrapper classes implement immutable objects. That meansthat after the primitive value is initialized in the wrapper object, thenthere is no way to change that value.

You can construct a wrapper class object by passing the value to bewrapped into the appropriate constructor, as shown in Code 3-6.

Code 3-6 Examples of Primitive Boxing Using Wrapper Classes

int pInt = 420;Integer wInt = new Integer(pInt); // this is called boxingint p2 = wInt.intValue(); // this is called unboxing

Table 3-4 Wrapper Classes

Primitive Data Type Wrapper Class

boolean Boolean

byte Byte

char Character

short Short

int Integer

long Long

float Float

double Double

Creating a Class: Fields and Constructors Syntax 3-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 90: Sl275 Sg

Declaring Fields: Selecting Class Types

Wrapper classes are useful when converting primitive data types becauseof the many wrapper class methods available; for example:

int x = Integer.valueOf(str).intValue();or:int x = Integer.parseInt(str);

3-14 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 91: Sl275 Sg

Declaring Fields: Formatting Identifiers

Declaring Fields: Formatting Identifiers

In the Java programming language, an identifier is a name given to avariable, class, or method. Identifiers start with a letter, underscore (_), ordollar sign ($) and valid currency symbols. Subsequent characters can bedigits. Identifiers are case-sensitive and have no maximum length.

The following are valid identifiers:

● identifier

● userName

● user_name

● _sys_var1

● $change // Legal but not encouraged

Java technology sources are in 16-bit Unicode rather than 8-bit AmericanStandard Code for Information Interchange (ASCII) text, so a letter is aconsiderably wider definition than just a–z and A–Z.

While identifiers can use non-ASCII characters, be aware of the followingcaveats:

● Unicode can support different characters that look the same.

● Class names should only be in ASCII characters because most filesystems do not support Unicode characters.

An identifier cannot be a keyword, but it can contain a keyword as part ofits name. For example, thisOne is a valid identifier, but this is notbecause this is a Java technology keyword.

Note – Identifiers containing a dollar sign ($) are generally unusual,although some other languages make extensive use of them. Because theyare unfamiliar, it is probably best to avoid them unless there is a localconvention or other pressing reason for including this symbol in theidentifier.

Creating a Class: Fields and Constructors Syntax 3-15Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 92: Sl275 Sg

Declaring Fields: Initializing Fields

Declaring Fields: Initializing Fields

This section addresses the initial values allocated to the fields (attributes)of a newly created object. For example, the Stock class shown inCode 3-7, contains three fields. This section explains the mechanisms youcan leverage to specify the initial value allocated to fields when classinstances are created.

Code 3-7 The Stock Class - Field Initialization Example

1 package finance;23 import java.util.Date;45 class Stock {6 // Field declarations7 String symbol;8 double price;9 Date date = new Date();;1011 // Constructor declarations12 Stock(String stockSymbol) {13 symbol = stockSymbol;14 }1516 // Method declarations1718 }

Java technology provides the following mechanisms for fieldinitialization.

● Initialize using default values

● Initialize using explicit values

● Initialize using constructors

Each of these mechanisms is explained in more detail in the followingsections.

3-16 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 93: Sl275 Sg

Declaring Fields: Initializing Fields

Field Initialization Using Default Values

Consider the Stock class shown in Code 3-8. The class does not declare aconstructor. None of the field’s declarations contain an initial value.Under these circumstances, each of the fields is assigned a default value.The assigned default value is based on the data type of the field.

Code 3-8 Default Initialization Example

1 package finance;23 import java.util.Date;45 class Stock {6 // Field declarations7 String symbol; // initialized to null8 double price; // initialized to 0.09 Date date; // initialized to null1011 // No constructors declared1213 // Method declarations1415 }

The default values for Java technology data types are listed in Table 3-5.

Table 3-5 Default Value table

Data Type Default Value

boolean false

byte 0

char ‘\u0000’

short 0

int 0

long 0L

float 0.0f

double 0.0d

Any class type null

Creating a Class: Fields and Constructors Syntax 3-17Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 94: Sl275 Sg

Declaring Fields: Initializing Fields

Field Initialization Using Explicit Values

Consider the Stock class shown in Code 3-9.

Code 3-9 Default and Explicit Initialization Example

1 package finance;23 import java.util.Date;45 class Stock {6 // Field declarations7 String symbol;8 double price;9 Date date = new Date();1011 // No constructors declared1213 // Method declarations1415 }

This class does not declare a constructor. One of the field declarationscontains an initial value. Table 3-6. shows the initial values that areassigned a new Stock instance using the following line of code:

Stock stock = new Stock();

Table 3-6 Initial Values Assigned to new Stock Instances

Field Name Initial Value Comment

symbol null Default initialization

price 0.0 Default initialization

date A reference toa new Dateobjectcontaining thedate and timewhen theobject wascreated.

Explicit initialization

3-18 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 95: Sl275 Sg

Declaring Fields: Initializing Fields

Field Initialization Using Constructors

Consider the Stock class shown in Code 3-10.

Code 3-10 The Stock Class With a Single Constructor

1 package finance;23 import java.util.Date;45 class Stock {6 // Field declarations7 String symbol;8 double price;9 Date date = new Date();1011 // Constructor declarations12 Stock(String stockSymbol) {13 symbol = stockSymbol;14 }1516 // Method declarations not shown1718 }

This Stock class declares a constructor. One of the field declarationscontains an initial value. Table 3-7 shows the initial values that areassigned a new Stock instance using the following line of code:

Stock stock1 = new Stock(“SUNW”);

Table 3-7 Initial Values Assigned to Stock Instance stock1

Field Name Initial Value Comment

symbol Reference tothe stringSUNW

Default initialization overwritten byconstructor

price 0.0 Default initialization

date A reference toa new Dateobjectcontaining thedate and timewhen theobject wascreated.

Explicit initialization

Creating a Class: Fields and Constructors Syntax 3-19Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 96: Sl275 Sg

Declaring Fields: Initializing Fields

A constructor is a set of instructions designed to initialize an instance.Parameters can be passed to the constructor in the same way as for amethod. The simplest declaration takes the following form:

<class_name> ( <argument>* ) {<statement>*

}

The name of the constructor must always be the same as the class name.

The <argument> list is the same as for method declarations.

Note – Constructors are not methods. They do not have return values.Constructors are invoked using the new keyword.

Constructor Overloading

When an object is instantiated, the program might be able to supplymultiple constructors based on the data for the object being created. Forexample, the Stock class shown in Code 3-11. contains two constructors.

Code 3-11 The Stock Class With Two Constructors

1 package finance;23 import java.util.Date;45 class Stock {6 // Field declarations7 String symbol;8 double price;9 Date date = new Date();1011 // Constructor declarations12 Stock(String stockSymbol) {13 symbol = stockSymbol;14 }1516 Stock(String stockSymbol, double newPrice) {17 this(stockSymbol): //invokes another constructor18 price = newPrice;19 }2021 // Method declarations2223 }

3-20 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 97: Sl275 Sg

Declaring Fields: Initializing Fields

Table 3-8 shows the initial values that are assigned a new instance usingthe following line of code.

Stock stock1 = new Stock(“ENCY”);

Table 3-9 shows the initial values that are assigned a new instance usingthe following line of code.

Stock stock2 = new Stock(“ZUMZ”, 52.00);

Table 3-8 Initial Values Assigned to Stock Instance stock1

Field Name Initial Value Comment

symbol Reference tothe stringENCY

Default initialization overwritten byconstructor

price 0.0 Default initialization

date A reference toa new Dateobjectcontaining thedate and timewhen theobject wascreated.

Explicit initialization

Table 3-9 Initial Values Assigned to Stock Instance stock2

Field Name Initial Value Comment

symbol Reference tothe stringZUMZ

Default initialization overwritten bythe constructor

price 52.00 Default initialization overwritten bythe constructor

date A reference toa new Dateobjectcontaining thedate and timewhen theobject wascreated.

Explicit initialization

Creating a Class: Fields and Constructors Syntax 3-21Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 98: Sl275 Sg

Declaring Fields: Initializing Fields

The Default Constructor

Every class has at least one constructor. If you do not write a constructor,the Java programming language provides one for you. This constructortakes no arguments and has an empty body.

The Stock class shown in Code 3-12 contains a default constructor.

Code 3-12 Default Constructor Example

1 package finance;23 import java.util.Date;45 class Stock {6 // Field declarations7 String symbol;8 double price;9 Date date;1011 // No constructors declared1213 // Method declarations1415 }

The default constructor enables you to create Stock object instances with:new Stock();.

Note – If you add any constructor declaration to a class that previouslyhad no explicit constructors, you lose the default constructor. Forexample, the Stock class shown in code Code 3-10 on page 3-19 does notcontain a default constructor. From that point, unless the constructor youwrote takes no arguments, calls to new Stock() cause compiler errors.

3-22 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 99: Sl275 Sg

Declaring Fields: Initializing Fields

You are permitted to replace the default constructor with a no-argconstructor, as shown in Code 3-13.

Code 3-13 The Stock Class With a Single No-arg Constructor

1 package finance;23 import java.util.Date;45 class Stock {6 // Field declarations7 String symbol;8 double price ;9 Date date;1011 // Constructor declarations12 Stock() {13 date = new Date();14 }1516 // Method declarations not shown for clarity reasons1718 }

Creating a Class: Fields and Constructors Syntax 3-23Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 100: Sl275 Sg

Examining Comments, White Space, and Keywords

Examining Comments, White Space, and Keywords

This section describes the rules and other relevant information associatedwith and the use of the following elements in a Java technology class.

● Comments

● White space

● Keywords

Comments

The three permissible styles for inserting comments are:

// comment on one line

/* comment on one* or more lines*/

/** documentation comment* can also span one or more lines*/

Documentation comments placed immediately before a declaration (of avariable, method, or class) indicate that the comments should be includedin any documentation that is generated automatically (for example, theHTML files generated by the javadoc command) to serve as a descriptionof the declared item.

Note – The format of these comments and the use of the Javadoc™ tool isdescribed in the documentation for the Java SE platform. Refer to thefollowing Universal Resource Locator (URL):http://java.sun.com/javase/6/docs/technotes/guides/javadoc/

3-24 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 101: Sl275 Sg

Examining Comments, White Space, and Keywords

White Space

You can have white space between elements of the source code. Anyamount of white space is allowed. You can use white space, includingspaces, tabs, and new lines, to enhance the clarity and visual appearanceof your source code. Compare:

{int x;x=23*54;}

with:

{int x;

x = 23 * 54;}

Java Programming Language Keywords

Java programming language keywords are defined by the Javaprogramming language specification. Keywords have special meaning tothe Java technology compiler. They identify a data type name or programconstruct name.

Table 3-10 lists keywords that are used in the Java programminglanguage.

Table 3-10 Java Programming Language Keywords

abstract continue for new switch

assert default goto package synchronized

boolean do if private this

break double implements protected throw

byte else import public throws

case enum instanceof return transient

catch extends int short try

char final interface static void

class finally long strictfp volatile

const float native super while

Creating a Class: Fields and Constructors Syntax 3-25Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 102: Sl275 Sg

Examining Comments, White Space, and Keywords

The following are important notes about the keywords:

● The literals true, false, and null are lower case, not upper case asin the C++ language. Strictly speaking, these are not keywords butliterals; however, the distinction is academic.

● There is no sizeof operator.

● The goto and const keywords are not used in the Javaprogramming language.

3-26 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 103: Sl275 Sg

Directory Layout and Packages

Directory Layout and Packages

Packages are stored in a directory tree containing a branch that is thepackage name. For example, the Company.class file should exist in thedirectory structure shown in Figure 3-1.

Figure 3-1 Example Class Package Directory Structure

Development

It is common to be working on several development projects at once.There are many ways to organize your development files. This sectiondescribes one such technique.

shipping/

domain/

GUI/

reports/

Vehicle.classRiverBarge.classTruck.class

VehicleCapacityReport.class

Company.class

Creating a Class: Fields and Constructors Syntax 3-27Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 104: Sl275 Sg

Directory Layout and Packages

Figure 3-2 demonstrates an example development directory hierarchy fora development project. The important element of this hierarchy is that thesource files of each project are separated from the compiled (.class) files.

Figure 3-2 Example Project Development Directory Structure

Compiling Using the -dOption

Normally, the Java compiler places the class files in the same directory asthe source files. You can reroute the class files to a parallel directory treeusing the -d option of the javac command. The simplest way to compilefiles within packages is to be working in the directory one level above thebeginning of the package. (In this example, the src directory.)

To compile all the files within the shipping.domain package and havethe compiled classes end up in their correct package directory underShippingPrj/classes/, type the following:

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

To execute a Java class named MyClass (belonging to theshipping.domain package) from the src directory, type the following:

java -cp ../classes shipping.domain.MyClass

JavaProjects/

ShippingPrj/

src/

docs/

shipping/

domain/GUI/reports/

classes/

shipping/

domain/GUI/reports/

3-28 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 105: Sl275 Sg

Directory Layout and Packages

Deployment

You can deploy an application on a client machine without manipulatingthe user’s CLASSPATH environment variable. Usually, this is best done bycreating an executable Java archive (JAR) file. To create an executable JARfile, you must create a temporary file that indicates the class name thatcontains your main method, as follows:

Main-Class: mypackage.MyClass

Next, build the JAR file as normal except that you add an additionaloption so that the contents of this temporary file are copied into theMETA-INF/MANIFEST.MF file. Do this using the m option, as follows:

jar cmf tempfile MyProgram.jar MyApp

Finally, the program can be run simply by executing a command asfollows:

java -jar /path/to/file/MyProgram.jar

Note – On some platforms, simply double clicking the icon for anexecutable JAR file is sufficient to launch the program.

Library Deployment

Sometimes you need to deploy library code in a JAR file. In suchsituations you can copy the JAR file into the ext subdirectory of the libdirectory in the main directory of the JRE. Be careful when you do this,because if you deploy classes in this way, they are usually granted fullsecurity privileges, and might cause runtime problems if any classes havenaming conflicts with other classes in the core JDK or that have beeninstalled in this way.

Creating a Class: Fields and Constructors Syntax 3-29Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 106: Sl275 Sg
Page 107: Sl275 Sg

Module 4

DeclaringaClass: Methods Syntax

Objectives

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

● Examine methods and the method body

● Examine expressions

● Examine advanced issues with expressions

● Create statements, including block, branch, and loop statements

● Use advanced method design techniques for:

● Method Overloading

● Pass-by-Value

● The this Reference

4-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 108: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following reference provides additionalinformation on the topics described in this module:

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

● Bates, Sierra. Head First Java, Second Edition. O’Reilly Media. 2005.

4-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 109: Sl275 Sg

Examining Methods

Examining Methods

Methods implement the behavior associated with instances of a particularclass type. This section provides the context in which a method isdeclared. It does so by examining the following relationships.

● The class-to-method relationship

● The method interface-to-method body relationship

● The fields, parameters, and local variables-to-method bodyrelationship

● The variable scope-to-block statement relationship

The following sections describe these relationships using the MoneyJarclass, along with its fields and its methods, shown in Code 4-1.

Code 4-1 Methods of the MoneyJar Class

1 public class MoneyJar {2 String purpose;3 double amount;4 double target;5 double surplus;67 void add(double sum) {8 amount = amount + sum;9 surplus = amount - target;10 }1112 double takeOut(double sum) {13 double sumReturned = 0;14 if (amount >= sum) {15 amount = amount - sum;16 sumReturned = sum;17 }18 else {19 sumReturned = amount;20 amount = 0;21 }22 surplus = amount - target;23 return sumReturned;24 }2526 double getAmount() {27 return amount;

Declaring a Class: Methods Syntax 4-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 110: Sl275 Sg

Examining Methods

28 }2930 void setTarget(double newTarget) {31 target = newTarget;32 surplus = amount - target;33 }3435 double getTarget() {36 return target;37 }3839 // other methods40 }

Examining the Class-to-Method Relationship

A class is a data type. It contains the following elements:

● Fields

Fields define the properties (attributes or state) of the data type andby inference, the properties of objects of the class type.

● Methods

Methods define the behavior of the data type and by inference, thebehavior of objects of the class type.

Methods use (the data stored in) fields. Methods can also change datastored in fields. On this basis, you can classify methods as follows:

● Mutator methods

A mutator method changes one or more field values.

● Non-mutator methods

A non-mutator method does not change any field values. Instead itsprimary purpose is to either return a field value (accessor method) ora value computed using field and parameter values.

4-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 111: Sl275 Sg

Examining Methods

● Table 4-1 classifies on a mutative basis, the methods of the MoneyJarclass shown in Code 4-1 on page 4-3.

Examining the Method Interface-to-Method BodyRelationship

Code 4-2 shows the method interface and the method body of thesetTarget method of the MoneyJar class.

Code 4-2 Method Example

1 public void setTarget(double newTarget) // method interface2 { // method body begin3 target = newTarget;4 surplus = amount - target;5 } // method body end

A Java method consists of the following two structures:

● Method interface

The method interface defines the service performed by (or behaviorof) a method. It can be thought of as a contract between the invoker(caller) of the method and the method. The method interface consistsof the following elements:

● Return type of the method

● Name of the method

● Ordered parameter list of the method

Table 4-1 Method Types of the MoneyJar Class

Method Name Method Type Purpose

add(double sum) Mutator Changes amount field

takeOut(double sum) Mutator Changes amount field

getAmount() Non-mutator Returns amount field

setTarget(double newTarget) Mutator Changes target field

getTarget() Non-mutator Returns target field

Declaring a Class: Methods Syntax 4-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 112: Sl275 Sg

Examining Methods

● Method body

The method body contains the code that implements the service (orbehavior) defined by the method’s interface. The method body codeis delimited by a pair of { }.

Comparing Method Interface and Method Signature

The method interface and the method signature should not be confused.The Java technology specification defines the method signature asconsisting of only the method’s name and the method’s orderedparameter list.

Table 4-2 contains examples of the method interfaces and methodsignatures taken from the MoneyJar class shown in Code 4-1 on page 4-3.

Table 4-2 Comparing Method Interface With Method Signatures

MethodName Method Interface Method Signature

add void add(double sum) add(double sum)

takeOut double takeOut(double sum) takeOut(double sum)

getAmount double getAmount() getAmount()

setTarget void setTarget(double newTarget) setTarget(double newTarget)

getTarget double getTarget() getTarget()

4-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 113: Sl275 Sg

Examining Methods

Examining the Fields, Parameters, and LocalVariables-to-Method Body Relationship

Fields, parameters, and local variables are all data carriers. From theperspective of code in a method body, all fields, parameters of themethod, and all in-scope local variables are operands. Table 4-3 examinesthe accessibility of the fields, parameters, and methods of the MoneyJarclass shown in Code 4-1 on page 4-3.

Table 4-4 compares the characteristics of fields, parameters, and localvariables.

Table 4-3 Examining the Data Holders in the MoneyJar Class

Variable Name Classification Accessible by

purpose Field All methods

amount Field All methods

target Field All methods

surplus Field All methods

sum (Declared in add method) Parameter add method

sum (Declared in takeOut method) Parameter takeOut method

sumReturned Local variable takeOut method

newTarget Parameter setTarget method

Table 4-4 Comparing Fields, Parameters and Local Variables

Analysis Factor Field Parameter Local Variable

Purpose Stores objectproperties

Passes input valuesto methods

Temporary variablefor method code use

Where declared Inside a class bodybut outside amethod.

In the methodsignature

Inside a method

How declared type name [= value]; type name type name [= value];

How initialized Default, explicit or bya constructor

By the invoking amethod duringmethod invocation

Explicit initialization

Variable scope Class body(accessible to allmethods of the class)

Method bodyassociated with thesignature

From the point of thedeclaration to the endof the enclosing block

Declaring a Class: Methods Syntax 4-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 114: Sl275 Sg

Examining the Method Body

Examining the Method Body

The method body implements behavior. This behavior is implementedusing Java technology language statements. You can classify statementsinto the following groups:

● Expression statements

● Declaration statements

● Assignment statements

● Flow control statements:

● Branch statements

● Loop statements

● Block statements

Most statement types use expressions. Code 4-3 shows examples ofstatements and expressions. The expressions are highlighted using boldtext.

Code 4-3 Examples of Expressions and Statements

1 public double takeOut(double sum) {2 double sumReturned = 0; // declaration statement3 if (amount >= sum) { // branch statement begin4 amount = amount - sum; // assignment statement5 sumReturned = sum;6 } // branch statement end7 else {8 sumReturned = amount;9 amount = 0;10 }11 surplus = amount - target;12 return sumReturned; // return statement13 }

Note – Code 4-3 contains several examples of block statements. A block,sometimes called a compound statement, is a group of statements boundby opening and closing braces ({ }).

4-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 115: Sl275 Sg

Examining Expressions

Examining Expressions

This section introduces Java technology expressions. All expressions havethe following common characteristics.

● An expression has at minimum one operator. An expression can befurther classified as simple or compound based on the number ofoperators it has. For example,

x + 5; // Simple expressions have a single operatorx + 5 * y; // Compound expressions have multiple operators

● The number of operands an operator has is determined by theoperator. Some operators are binary, that is they require twooperands. Some operators are unary, that is they require oneoperand. For example,

x < 2; // Binary operator example++x; // Unary operator example

● An expression evaluates to a type.

The data type an expression evaluates to depends on the:

● Operator

● Data types of the operand(s)

Table 4-5 contains the evaluation data types of Java technologyexpressions.

Table 4-5 Expression Evaluation Data Types

Expression Operator Type Operand DataType Result Type

x + y; Numeric addition Numeric Numeric

x < 2; Comparison Numeric boolean

“sun” + 22 Stringconcatenation

At least oneoperand is astring

String

x & 22; Bitwise AND int or long int or long

Declaring a Class: Methods Syntax 4-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 116: Sl275 Sg

Examining Expressions

Examining Simple Expressions

This section examines simple expressions, that is expressions that containa single operator.

Arithmetic Operators: An Introduction

Java technology supports both binary and unary arithmetic operators.Table 4-6 lists the binary arithmetic operators available in Java technology.The values in the result column of Table 4-6 are computed for x having anint value of 7 and y having an int value of 3.

Table 4-7 lists the unary arithmetic operators available in Java technology.

Table 4-6 Binary Arithmetic Operators

Purpose Operator Example Result

Addition + result = x + y; 10

Subtraction - result = x - y; 4

Multiplication * result = x * y; 21

Division / result = x / y; 2

Remainder % result = x % y; 1

Table 4-7 Unary Arithmetic Operators

Purpose Operator Examplenum1 preexpressionevaluation

resultnum1 postexpressionevaluation

Unary plus + result = +num1; 7 7 7

Unary minus - result = -num1; 7 -7 7

Pre-Increment ++ result = ++num1; 7 8 8

Post-Increment

++ result = num1++; 7 7 8

Pre-Decrement

-- result = --num1; 7 6 6

Post-Decrement

-- result = num1--; 7 7 6

4-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 117: Sl275 Sg

Examining Expressions

Bitwise Logical and Shift Operators

Bit manipulation operations, including logical and shift operations,perform low-level operations directly on the binary representations usedin integers. These operations are not often used in enterprise-type systemsbut might be critical in graphical, scientific, or control systems. The abilityto operate directly on binary representations can save large amounts ofmemory, can enable certain computations to be performed efficiently, andcan greatly simplify operations on collections of bits, such as data readfrom or written to parallel I/O ports.

The Java programming language supports bitwise operations on integraldata types. These are represented as the operators ~, &, ,̂ and | for thebitwise operations of NOT (bitwise complement), bitwise AND, bitwiseXOR, and bitwise OR, respectively.

Table 4-8 lists the bitwise logical and shift operators available in Javatechnology.

Table 4-8 Bitwise and Bitwise Shift Operators

Purpose Operator Usage Example

Bitwise complement ~ ~x

Bitwise ORBitwise ANDBitwise XOR

|&^

x | yx & yx ^ y

Bitwise signed left shiftBitwise signed right shiftBitwise unsigned rightshift

<<>>>>>

x << yx >> yx >>> y

Declaring a Class: Methods Syntax 4-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 118: Sl275 Sg

Examining Expressions

Figure 4-1 shows examples of the bitwise operators on byte-sized binarynumbers.

Figure 4-1 Examples of Applying Bitwise Operators

Figure 4-2 shows the bit patterns of a positive and a negative number andthe bit patterns resulting from the three shift operators: >>, >>>, and <<.

Figure 4-2 Examples of the Shift Operators

0 0 01 1 1 1 1

1 1 10 0 0 0 0

~

0 0 0 01 1 1 1

0 0 01 1 1 1 1

0 0 0 0 01 1 1

&

0 0 0 01 1 1 1

0 0 01 1 1 1 1|

0 01 1 1 1 1 1

0 0 0 01 1 1 1

0 0 01 1 1 1 1

0 0 0 00 11 1

^

0 10 0 1

1

0

00

111

11111

00

000

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 =

1357 >> 5 =

-1357 >> 5 =

1357 >>> 5 =

1357 >>> 5 =

1357 << 5 =

-1357 << 5 =

111 00011 1 1 11 1 111 1 1 11 1 1 11 1 1

1 10011111 00011 1 1 11 1 111 1 11 1 1

0 111 0000 0 000 0 000 0 000 0 000 0 0

0 10 0 1 10111 0000 0 000 0 000 0 000 0

0 00 0 0

11 1 11

0 111 0000 0 000 0 000 0 000 0 000 0 00 00 0 0

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

0 0 0 0

0 0 0 0

4-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 119: Sl275 Sg

Examining Expressions

Assignment Operators

You can classify assignment operators into simple and compound.Compound assignment operators combine an arithmetic operation or abitwise operation or a bitwise shift operation with an assignmentoperation. Table 4-9 lists the simple and compound operators available inJava technology.

Relational (Logical) Operators

Relational operators return a boolean result that is either true or false;The values in the result column of Table 4-10 are computed based onfollowing data values:

int x=7; int y=3; boolean a=true; boolean b=false;.

Table 4-9 Assignment Operators

Purpose Operator Example Equivalent

Simple assignment = x = y;

Compound arithmeticoperation and assignment

+=-=*=/=%=

x += y;x -= yx *= yx /= yx %= y

x = x + y;x = x - y;x = x * y;x = x / y;x = x % y;

Compound bitwiselogical operation andassignment

|=&=^=

x |= y;x &= y;x ^= y;

x = x | y;x = x & y;x = x ^ y;

Compound bitwise shiftoperation and assignment

<<=>>=>>>=

x <<= y;x >>= y;x >>>= y;

x = x << y;x = x >> y;x = x >>> y;

Table 4-10 Relational Operators

Purpose Operator Example Result

Greater than > result = x > 7; false

Greater than or equal to >= result = x >= 7; true

Equal to == result = x == y; false

Not equal to != result = x != y; true

Less than < result = x < y; false

Declaring a Class: Methods Syntax 4-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 120: Sl275 Sg

Examining Expressions

String Concatenation Operator

The + operator performs a concatenation of String objects, producing anew String.

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

The result of the last line is:

Dr. Pete Seymour

If either argument of the + operator is a String object, then the otherargument is converted to a String object. All objects can be converted toa String object automatically, although the result might be rather cryptic.The object that is not a String object is converted to a string equivalentusing the toString() member function.

Less than or equal to <= result = x <= y; false

Logical OR || result = a || b; true

Logical AND && result = a && b; false

Logical OR || result = (x<3) || (y>2); true

Logical AND && result = (x<3) && (y>2); false

Table 4-10 Relational Operators

Purpose Operator Example Result

4-14 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 121: Sl275 Sg

Expressions: Advanced Issues

Expressions: Advanced Issues

This section examines the following advanced topics associated withexpressions.

● Numeric promotions in simple expressions

● Casting

● Evaluating compound expressions

Numeric Promotions in Simple Expressions

Consider the following expression:

result = operand1 + operand2

The data type the expression evaluates to, that is the data type assigned tothe result variable, depends on the data types of the operands.Table 4-11 shows the resulting data type for various combinations ofoperand data types.

Table 4-11 Examining Numeric Data Type Promotion

Operand 1 Data Type Operand 2 Data Type Result

Byte, Character, Short,byte, char, short

Byte, Character, Short,byte, char, or short

int

Byte, Character, Short, Integerbyte, char, short, int

Integer or int int

Byte, Character, Short, Integerbyte, char, short, int

Long or long long

Byte, Character, Short, Integer, Longbyte, char, short, int, long

Float or float float

Byte, Character, Short, Integer, Long, Floatbyte, char, short, int, long, float

Double or double double

Declaring a Class: Methods Syntax 4-15Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 122: Sl275 Sg

Expressions: Advanced Issues

Java technology converts the data types of the operands, as required, tothe result type before it applies the operator to the operands. Thisphenomena is known as numeric promotion. Numeric promotions apply tothe following operators:

● Numeric operators

+ - * / %

● Bitwise operators

& | ^

● Relational Operators

< <= == != > >=

Casting

Variables can be promoted automatically to a longer form (such as int tolong) when there is no loss of information.

long bigval = 6; // 6 is an int type, OKint smallval = 99L; // 99L is a long, illegal

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

In general, you can think of an expression as being assignment-compatible ifthe variable type is at least as large (maximum value) as the expressiontype.

For binary operators, such as the + operator, when the two operands areof primitive numeric types, the result type is determined as the largesttype of either operand, or int. Therefore, all binary operations onnumeric types result in at least an int result, and possibly a larger one iflong, float, or double operands are in the expression. This might resultin overflow or loss of precision when the result is assigned to a variable.

4-16 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 123: Sl275 Sg

Expressions: Advanced Issues

For example, the following code fragment:

short a, b, c;a = 1;b = 2;c = a + b; // causes error

causes an error because it raises each short to an int before operatingon it. However, if c is declared as an int, or a cast is done as:

c = (short)(a + b);

then the code works.

Autoboxing of Primitive Types

If you have to change the primitive data types to their object equivalents(called boxing), then you must use the wrapper classes. Also, to get theprimitive data type from the object reference (called unboxing), you needto use the wrapper class methods. All of this boxing and unboxing canclutter up your code and thus make your code difficult to understand.The autoboxing feature introduced in versions of the Java Platform,Standard Edition 5.0 (Java SE 5.0) and later, enables you to assign andretrieve primitive types without the need of the wrapper classes.

Code 4-4 shows two simple cases of autoboxing and autounboxing.Compare this with Code 3-6 on page 3-13.

Code 4-4 Examples of Primitive Autoboxing

int pInt = 420;Integer wInt = pInt; // this is called autoboxingint p2 = wInt; // this is called autounboxing

Compilers of the Java SE 5.0 and later platforms create the wrapper objectautomatically when assigning a primitive to a variable of the wrapperclass type. The compiler also extracts the primitive value when assigningfrom a wrapper object to a primitive variable.

This can be done when passing parameters to methods or even withinarithmetic expressions.

Caution – Do not overuse the autoboxing feature. There is a hiddenperformance impact when a value is autoboxed or autounboxed. Mixingprimitives and wrapper objects in arithmetic expressions within a tightloop might have a negative impact on the performance and throughput ofyour applications.

Declaring a Class: Methods Syntax 4-17Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 124: Sl275 Sg

Expressions: Advanced Issues

Evaluating Compound Expressions

A compound expression involves two or more operators. For example,

x + 5 * y/25; // Compound expressions have multiple operators

When evaluating compound expressions, you must take into account thefollowing:

● Operator precedence

● Operator associativity

Table 4-12 lists the operators in order of precedence (L to R means left-to-right associative; R to L means right-to-left associative).

Table 4-12 Operators and Precedence

Associative Operators

R to L ++ -- + - ~ ! (<data_type>)

L to R * / %

L to R + -

L to R << >> >>>

L to R < > <= >= instanceof

L to R == !=

L to R &

L to R ^

L to R |

L to R &&

L to R ||

R to L <boolean_expr> ? <expr1> : <expr2>

R to L = *= /= %= += -= <<=>>= >>>= &= ^= |=

4-18 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 125: Sl275 Sg

Introducing Statements

Introducing Statements

A Java technology statement forms a complete unit of execution.Statements are the mechanism that enable a method to implementbehavior. In Java technology, statements are placed within the methodbody, as shown in Code 4-5.

Code 4-5 Examples of Statements

1 public double takeOut2(double sum) {2 double sumReturned = 0; // declaration statement3 if (amount > sum) // branch statement begin4 { // block statement begin5 amount = amount - sum;6 sumReturned = sum;7 } // block statement end8 else9 {10 sumReturned = amount;11 amount = 0;12 } // branch statement end13 surplus = amount - target; // assignment statement14 // method invocation statement15 System.out.println(“taking out “ + sumReturned);16 return sumReturned; // return statement17 }

Table 4-13 lists the most common types of Java technology statements.

Table 4-13 Java Technology Statement Types

Statement MajorType Statement Minor Type Comment or Example

Expression statements Assignment expressionsAny use of ++ or --Method invocationsObject creationExpressions

x = a + b;x++;System.out.println(“hello”);j = new Integer(25);

Block statements A block is a group of zero or morestatements between balanced bracesand can be used anywhere a singlestatement is allowed.

Declaring a Class: Methods Syntax 4-19Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 126: Sl275 Sg

Introducing Statements

The following sections explain block statements and flow controlstatements in more detail.

Declarationstatements

int x;

Flow controlstatements

Branching

Looping

Flow control helpertypes

if statementswitch statementfor loopwhile loopdo while loopLabel statementcontinue statementbreak statement

Table 4-13 Java Technology Statement Types

Statement MajorType Statement Minor Type Comment or Example

4-20 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 127: Sl275 Sg

Block Statements

Block Statements

A block, sometimes called a compound statement, is a group of statementsbound by opening and closing braces ({ }).

The following are examples of block statements or groupings:

// a block statement{x = y + 1;y = x + 1;

}

// a class definition is contained in a blockpublic class MyDate {private int day;private int month;private int year;

}

// a block statement can be nested within// another block statementwhile ( i < large ) {a = a + i;// nested blockif ( a == max ) {b = b + a;a = 0;

}i = i + 1;

}

Declaring a Class: Methods Syntax 4-21Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 128: Sl275 Sg

Branching Statements

Branching Statements

Conditional statements enable the selective execution of portions of theprogram according to the value of some expressions. The Javaprogramming language supports the if and switch statements for two-way and multiple-way branching, respectively.

Simple ifStatements

The basic syntax for an if statement is:

if ( <boolean_expression> )<statement_or_block>

For example:

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

However, you should place all then statements into a block. For example:

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

}

Simple if, elseStatements

If you require an else clause, then you must use the if-else statement:

if ( <boolean_expression> )<statement_or_block>

else<statement_or_block>

For example:

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

} else {System.out.println("Keep working...");

}

4-22 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 129: Sl275 Sg

Branching Statements

Complex if, elseStatements

If you require a series of conditional checks, then you can chain asequence of if-else-if statements:

if ( <boolean_expression> )<statement_or_block>

else if ( <boolean_expression> )<statement_or_block>

For example:

int count = getCount(); // a method defined in the classif (count < 0) {System.out.println("Error: count value is negative.");

} else if (count > getMaxCount()) {System.out.println("Error: count value is too big.");

} else {System.out.println("There will be " + count +

" people for lunch today.");}

The entire else part of the statement is optional, and you can omit it if noaction is to be taken when the tested condition is false.

Declaring a Class: Methods Syntax 4-23Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 130: Sl275 Sg

Branching Statements

The switchStatement

The switch statement syntax is:

switch ( <expression> ) {case <constant1>:<statement_or_block>*[break;]

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

default:<statement_or_block>*[break;]

}

In the switch (<expression>) statement, <expression> must beexpression-compatible with an int type. Promotion occurs with byte,short, or char types. Floating point, long expressions, or objectreferences (including Strings) are not permitted.

Note – An enumerated type value can also be used in the <expression>and <constantN> elements. A discussion of Java technology enumeratedtypes is outside the scope of this module.

The optional default label specifies the code segment to be executedwhen the value of the variable or expression cannot match any of thecase values. If there is no break statement as the last statement in thecode segment for a certain case, the execution continues into the codesegment for the next case without checking the case expression’s value.

If the switch is in a loop, then a continue statement would also causeexecution to exit out of the switch construct.

Note – Most switch statements require breaks in each case block.Forgetting the break statement causes the most programming errorswhen using switch statements.

An example switch statement is shown in Code 4-6 on page 4-25.

4-24 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 131: Sl275 Sg

Branching Statements

Code 4-6 The switch Statement Example 1

switch ( carModel ) {case ‘D’: // Deluxe modeladdAirConditioning();addRadio();addWheels();addEngine();break;

case ‘S’: // Standard modeladdRadio();addWheels();addEngine();break;

default:addWheels();addEngine();

}

Code 4-6 configures a car object based on the carModel. If carModel is(D)eluxe, then air conditioning is added to the car, as is a radio, and, ofcourse, wheels and an engine. However, if the carModel is only a(S)tandard, then only a radio, wheels, and an engine are added. Finally,by default, any car model has wheels and an engine added.

A second example switch statement is shown in Code 4-7.

Code 4-7 The switch Statement Example 2

switch ( carModel ) {case ‘D’: // Deluxe modeladdAirConditioning();// fall through

case ‘S’: // Standard modeladdRadio();// fall through

default:addWheels();addEngine();

}

Declaring a Class: Methods Syntax 4-25Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 132: Sl275 Sg

Branching Statements

Code 4-7 solves the redundant method calls in the previous example bypermitting the flow of control to descend through multiple case blocks.For example, if the carModel is (D)eluxe, then theaddAirConditioning method is called, and then the flow of control fallsthrough the next case statement and calls the addRadio method, andfinally the flow of control falls through the default statement and callsthe addWheels and addEngine methods.

4-26 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 133: Sl275 Sg

Looping Statements

Looping Statements

Looping statements enable you to execute blocks of statements repeatedly.The Java programming language supports four types of loop constructs:for (two variations), while, and do loops. The while loop and onevariation of the for loop test the loop condition before executing the loopbody; the do loop checks the loop condition after executing the loop body.This implies that the do loop always executes the loop body at least once.The second variation of the for loop, known as the enhanced for loop,which is used to iterate through the elements from a group (such as anarray), has no explicit loop condition.

The for Loops

The for loop syntax is:

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

For example:

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

However, you should place all loop-clause statements into a block. Forexample:

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

}

In the previous example, int i is declared and defined within the forblock. The variable i is accessible only within the scope of this particularfor block.

Note – The Java programming language permits the comma separator in afor() loop structure. For example,for (i = 0, j = 0; j < 10; i++, j++) { } is legal, and it initializesboth i and j to 0, and increments both i and j after executing the loopbody.

Declaring a Class: Methods Syntax 4-27Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 134: Sl275 Sg

Looping Statements

The while Loop

The while loop syntax is:

while ( <test_expr> )<statement_or_block>

For example:

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

}

Ensure that the loop-control variable is initialized appropriately before theloop body begins execution. You must update the control variableappropriately to prevent an infinite loop.

The do/while Loop

The syntax for the do/while loop is:

do<statement_or_block>

while ( <test_expr> );

For example:

int i = 0;do {System.out.println(i + " squared is " + (i*i));i++;

} while ( i < 10 );

As with the while loops, ensure that the loop-control variable isinitialized appropriately, updated in the body of the loop, and testedproperly.

Use the for loop in cases where the loop is to be executed apredetermined number of times. Use the while and do loops in caseswhere this is not determined beforehand.

4-28 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 135: Sl275 Sg

Looping Statements

Special Loop Flow Control

You can use the following statements to further control loop statements:

● break [<label>];

Use the break statement to prematurely exit from the switchstatements, loop statements, and labelled blocks.

● continue [<label>];

Use the continue statement to skip over and jump to the end of theloop body, and then return control to the loop-control statement.

● <label> : <statement>

The label statement identifies a statement or block, in most casesthe start of an outer loop. A labelled break statement allowspremature exit out of the block associated with the label.

A labelled continue statement must identify a loop construct. Onencountering a labelled continue statement, the JVMimplementation skips the remaining code of the current block andjumps to the beginning of the labelled block.

The breakStatement

The following is an example loop with an unlabelled break statement:

1 do {2 statement;3 if ( condition ) {4 break;5 }6 statement;7 } while ( test_expr );

The continueStatement

The following is an example loop with an unlabelled continue statement:

1 do {2 statement;3 if ( condition ) {4 continue;5 }6 statement;7 } while ( test_expr );

Declaring a Class: Methods Syntax 4-29Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 136: Sl275 Sg

Looping Statements

Using breakStatements with Labels

The following is an example loop with a labelled break statement:

1 outer:2 do {3 statement1;4 do {5 statement2;6 if ( condition ) {7 break outer;8 }9 statement3;10 } while ( test_expr );11 statement4;12 } while ( test_expr );

Using continueStatements with Labels

The following is an example loop with a labelled continue statement:

1 test:2 do {3 statement1;4 do {5 statement2;6 if ( condition ) {7 continue test;8 }9 statement3;10 } while ( test_expr );11 statement4;12 } while ( test_expr );

4-30 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 137: Sl275 Sg

Advanced Method Design Issues: Overloading Methods

Advanced Method Design Issues: Overloading Methods

In some circumstances, you might want to write several methods in thesame class that do the same basic job with different arguments. Considera simple method that is intended to output a textual representation of itsargument. This method could be called println().

Now, suppose that you need a different print method for printing each ofthe int, float, and String types. This is reasonable, because the variousdata types require different formatting and, probably, varied handling.You could create three methods, called printInt(), printFloat(), andprintString() respectively. However, this is tedious.

The Java programming language permits you to reuse a method name formore than one method. This works only if there is something in thecircumstances under which the call is made that distinguishes the methodthat is needed. In the case of the three print methods, this distinction isbased on the number and type of the arguments.

By reusing the method name, you end up with the following methods:

public void println(int i)public void println(float f)public void println(String s)

When you write code to call one of these methods, the appropriatemethod is chosen according to the type of argument or arguments yousupply.

Two rules apply to overloaded methods:

● Argument lists must differ.

The argument lists of the calling statement must differ enough toallow unambiguous determination of the proper method to call.Normal widening promotions (for example, float to double) mightbe applied; this can cause confusion under some conditions.

● Return types can be different.

The return type of the methods can be different, but it is notsufficient for the return type to be the only difference. The argumentlists of overloaded methods must differ.

Declaring a Class: Methods Syntax 4-31Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 138: Sl275 Sg

Advanced Method Design Issues: Overloading Methods

Methods Using Variable Arguments

A variation on overloading is when you need a method that takes anynumber of arguments of the same type. For example, imagine you need tocreate a method that calculates the average of a set of integers. You coulddefine the following methods:

public class Statistics {public float average(int x1, int x2) {}public float average(int x1, int x2, int x3) {}public float average(int x1, int x2, int x3, int x4) {}

}

These methods can be invoked as follows:

Statistics stats = new Statistics();float gradePointAverage = stats.average(4, 3, 4);float averageAge = stats.average(24, 32, 27, 18);

These three overloaded methods all share the same functionality. It wouldbe nice to collapse these methods into one method. Versions of Java SE 5.0and later provide a feature, called varargs or variable arguments, to enableyou to write a more generic method:

public class Statistics {public float average(int... nums) {int sum = 0;for ( int x : nums ) {sum += x;

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

}}

This new varargs method can be invoked in the same manner as the suiteof overloaded methods. The length attribute is an inbuilt feature thatreturns the number of arguments.

4-32 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 139: Sl275 Sg

Advanced Method Design Issues: Pass-by-Value

Advanced Method Design Issues: Pass-by-Value

The Java programming language passes arguments only by value, that is,you cannot change the argument value in the calling method from withinthe called method.

However, when an object instance is passed as an argument to a method,the value of the argument is not the object itself but a copy of thereference to the object. You can change the contents of the object in thecalled method but not the original object reference.

To many people, this looks like pass-by-reference, and behaviorally, it hasmuch in common with pass-by-reference. However, there are two reasonsthis is inaccurate. First, the ability to change the thing passed into amethod only applies to objects, not primitive values. Second, the actualvalue associated with a variable of object type is the reference to theobject, and not the object itself. This is an important distinction in otherways, and if clearly understood, is entirely supporting of the point thatthe Java programming language passes arguments by value.

The following code example illustrates this point:

1 public class PassTest {23 // Methods to change the current values4 public static void changeInt(int value) {5 value = 55;6 }7 public static void changeObjectRef(MyDate ref) {8 ref = new MyDate(1, 1, 2000);9 }10 public static void changeObjectAttr(MyDate ref) {11 ref.setDay(4);12 }1314 public static void main(String args[]) {15 MyDate date;16 int val;1718 // Assign the int19 val = 11;20 // Try to change it21 changeInt(val);22 // What is the current value?23 System.out.println("Int value is: " + val);

Declaring a Class: Methods Syntax 4-33Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 140: Sl275 Sg

Advanced Method Design Issues: Pass-by-Value

2425 // Assign the date26 date = new MyDate(22, 7, 1964);27 // Try to change it28 changeObjectRef(date);29 // What is the current value?30 System.out.println("MyDate: " + date);3132 // Now change the day attribute33 // through the object reference34 changeObjectAttr(date);35 // What is the current value?36 System.out.println("MyDate: " + date);37 }38 }

This code outputs the following:

java PassTest

Int value is: 11MyDate: 22-7-1964MyDate: 4-7-1964

The MyDate object is not changed by the changeObjectRef method;however, the changeObjectAttr method changes the day attribute of theMyDate object.

4-34 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 141: Sl275 Sg

Advanced Method Design Issues: The thisReference

Advanced Method Design Issues: The thisReference

Two further uses of the this keyword are:

● To resolve ambiguity between instance variables and parameters

● To pass the current object as a parameter to another method

Code 4-8 provides a class definition that demonstrates these uses. TheMyDate class declares instance variables, Lines 2–4. One of the parametersto one of the constructors (Lines 6–10) is also called day, so in that context,the keyword this resolves the ambiguity (Line 7). The addDays methodcreates a new date object (Line 18). In this constructor call, the methoduses the this keyword as an argument to refer to the current object.

Code 4-8 The Use of the this Keyword

1 public class MyDate {2 private int day = 1;3 private int month = 1;4 private int year = 2000;56 public MyDate(int day, int month, int year) {7 this.day = day;8 this.month = month;9 this.year = year;10 }11 public MyDate(MyDate date) {12 this.day = date.day;13 this.month = date.month;14 this.year = date.year;15 }1617 public MyDate addDays(int moreDays) {18 MyDate newDate = new MyDate(this);19 newDate.day = newDate.day + moreDays;20 // Not Yet Implemented: wrap around code...21 return newDate;22 }23 public String toString() {24 return "" + day + "-" + month + "-" + year;25 }26 }

Declaring a Class: Methods Syntax 4-35Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 142: Sl275 Sg
Page 143: Sl275 Sg

Module 5

Creating aClass:UsingEncapsulation

Objectives

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

● Understand the concept of encapsulation

● Implement encapsulation in the Java language

● Use the static keyword

● Examine static imports

5-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 144: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following references provide additionalinformation on the topics described in this module:

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

● Bates, Sierra. Head First Java, Second Edition. O’Reilly Media. 2005.

5-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 145: Sl275 Sg

Examining the Concept of Encapsulation

Examining the Concept of Encapsulation

Encapsulation is the separation of a data type’s (class’s) interface from thedata type’s (class’s) implementation. Figure 5-1 shows data elements thatare needed to hold date and stock information. These data elements asshown, are said to be unencapsulated.

Figure 5-1 Unencapsulated Data

To encapsulate these data elements, you must perform the followingsteps:

1. Separate out the data elements associated with date informationfrom data elements that store stock information. Figure 5-2 showsthe separation of the date-related data elements from the stock-related data elements.

Figure 5-2 Encapsulation Step 1: Group Related Data

year:int

day:int

month:int

symbol:String

name:String

price:double

MyDate

day : int

month : int

year : int

Stock

symbol : String

name : String

price : double

Creating a Class: Using Encapsulation 5-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 146: Sl275 Sg

Examining the Concept of Encapsulation

2. Group date data elements in a single unit with operations (methods)associated with date information. Similarly, create another unit toassociate stock data elements with stock operations. Figure 5-3shows the grouping of data elements with their associated methods.

Figure 5-3 Encapsulation Step 2: Group Data With Behavior

3. The final step in encapsulation is to prevent direct access to dataelements but enable indirect access through the methods associatedwith the data elements. This step is known as implementing accesscontrol. Figure 5-4 shows the implementation of access control.

Figure 5-4 Encapsulation Step 3: Implement Access Control

setDay(int) : boolean

setYear(int) : boolean

setMonth(int) : boolean

getDay() : int

getMonth() : int

getYear() : int

MyDate

day : int

month : int

year : int

Verify days in month

setName()

setPrice(double)

Stock(symbol : String)

getName() : String

getPrice() : double

Stock

symbol : String

name : String

price : double

getSymbol() : String

+setDay(int) : boolean

+setYear(int) : boolean

+setMonth(int) : boolean

+getDay()

+getMonth()

+getYear()

MyDate

-day : int

-month : int

-year : int

+setName()

+setPrice(double)

+Stock(symbol : String)

+getName() : String

+getPrice() : double

Stock

-symbol : String

-name : String

-price : double

+getSymbol() : String

+ symbol represents external or public access- symbol represents internal or private access

5-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 147: Sl275 Sg

Examining the Concept of Encapsulation

The benefits of encapsulation are:

● Protecting data integrity

Encapsulation provides a mechanism to control access to the internaldata structures of a data type. This control enables the designer ofthe data type to restrict access to the internal structures throughpublic methods. These methods can enforce business rules thatensure that the integrity of the internal data structures. For example,in the case of the MyDate class, the set methods can ensure that aMyDate object always represents a valid date. That is, a date such asday 30 in the month of February is never possible.

● Application maintainability

Limiting access to a data type through its public interface enablesinternals of the data type to be changed without impacting the usersof the data type.

Creating a Class: Using Encapsulation 5-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 148: Sl275 Sg

Implementing Encapsulation in Java Technology

Implementing Encapsulation in Java Technology

Java technology provides the following elements to supportencapsulation.

● The package statement

The package statement places a class in a package (library). Thepackage statement enables the encapsulation (grouping) of relatedclasses into packages. The following statements explain thesemantics of package-level encapsulation.

● A class in a package is visible and accessible to all other classesin the same package.

● A class marked public is visible to classes in other packages.

● A class not marked public is hidden to classes in otherpackages.

● The class statement

The class statement encapsulates attributes, constructors (attributeinitializers) and methods into a single compilable unit.

● Access modifiers

Access modifiers provide coarse-grained access control to wholeclasses and fine-grained access control to class members (attributes,constructors and methods).

The Java technology specification defines four access modifiers.

● Public

Public access is defined using the public keyword. The publicaccess modifier can be applied to both the class statement andto class member declaration statements.

● Protected

Protected access is defined using the protected keyword.Protected access is relevant for classes that have an inheritancerelationship with another class. That is when a child class isdefined by extending another class. Protected members of theparent class are accessible to the child class.

Note – A more detailed discussion of Inheritance and the use of theprotected access modifier is outside the scope of this module.

5-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 149: Sl275 Sg

Implementing Encapsulation in Java Technology

● Private

Private access is defined using the private keyword. The privateaccess modifier limits access of the private member (attributes,constructors, and methods) to other members of the same class.

● Default

The Java language specification does not provide a keyword tospecify default access. Instead, default access is specified by theabsence of an access modifier (public, private, orprotected).

Table 5-1 shows a summary of the access levels in four possiblerelationship contexts. The four possible relationship contexts are:

● Same class context

The same class context applies to the access of any member of theclass by a method in the same class.

● Same package context

The same package context applies to the access of any member of theclass by a method in a different class that is in the same package.

● Subclass context

The subclass context applies to the inheritance of any member of theclass by a child class in a different package.

● Universe context

The universe context applies to the access of any member of the classby a method in a different class that is in a different package.

Table 5-1 Accessibility Criteria

Modifier Same Class Same Package Subclass Universe

private Yes

default Yes Yes

protected Yes Yes Yes

public Yes Yes Yes Yes

Creating a Class: Using Encapsulation 5-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 150: Sl275 Sg

Implementing Encapsulation in Java Technology

Code 5-1 shows a reduced version of a Date class as an example of apublic class containing private, public, and default members.

Code 5-1 The Date Class

1 package com.abc.util;23 public class Date {4 private int day;56 public Date() {//... }78 public void addDays(int days) { }9 int getDaysInMonth(int month) { }10 }

Code 5-2 shows a reduced version of a Stock class as an example of aclass in a different package to the Date class.

Code 5-2 The Stock Class

1 package com.abc.brokerage;23 public class Stock {4 private String symbol;5 public Stock(String symbol, double price) { }67 public String getSymbol() { }8 public void setSymbol(String symbol) { }9 }

Code 5-3 shows a reduced version of a StockAnalyzer class as anexample of a class in a different package to the Date class but the samepackage as the Stock class.

Code 5-3

1 package com.abc.brokerage;2 import com.abc.util.Date;34 class StockAnalyzer {5 private Date date;67 double sell(Stock stock, int quantity) { }8 public double buy(Stock stock, int quantity) { }9 }

5-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 151: Sl275 Sg

Using the staticKeyword

Using the staticKeyword

You can use the static keyword to declare members (fields, methods,and nested classes) that are associated with the class rather than theinstances of the class.

The following sections describe the most common uses of the statickeyword: class variables and class methods.

Class Attributes

Sometimes it is desirable to have a field that is shared among all instancesof a class. For example, you could use this field as the basis forcommunication between instances or to keep track of the number ofinstances that have been created (see Figure 5-5).

Figure 5-5 UML Object Diagram of the Count Class and Two UniqueInstances

You achieve this shared effect by marking the field with the keywordstatic. Such a field is sometimes called a class field to distinguish it froma member or instance field, which is not shared. Code 5-4 illustrates theuse of a class field.

Code 5-4 Class Field Example

1 public class Count {2 private int serialNumber;3 public static int counter = 0;45 public Count() {6 counter++;7 serialNumber = counter;8 }9 }

c1 : Count

Count

serialNumber=1

-serialNumber : int

+counter : int = 0

c2 : Count

serialNumber=2

«instanceOf»«instanceOf»

Creating a Class: Using Encapsulation 5-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 152: Sl275 Sg

Using the staticKeyword

In this example, every object that is created is assigned a unique serialnumber, starting at 1 and counting upwards. The field counter is sharedamong all instances, so when the constructor of one object incrementscounter, the next object to be created receives the incremented value.

A static field is similar in some ways to a global variable in otherlanguages. The Java programming language does not have global fields,but a static field is a single field that is accessible from any instance ofthe class.

If a static field is not marked as private, you can access it fromoutside the class. To do this, you do not need an instance of the class, youcan refer to it through the class name, as shown in Code 5-5.

Code 5-5 Accessing a Class Field

1 public class OtherClass {2 public void incrementNumber() {3 Count.counter++;4 }5 }

Class Methods

Sometimes you need to access program code when you do not have aninstance of a particular object available. A method that is marked usingthe keyword static can be used in this way and is sometimes called aclass method. The getTotalCount method in Code 5-6 is an example of aclass method.

Code 5-6 Class Methods Example

1 public class Count2 {2 private int serialNumber;3 private static int counter = 0;45 public static int getTotalCount() {6 return counter;7 }89 public Count2() {10 counter++;11 serialNumber = counter;12 }

5-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 153: Sl275 Sg

Using the staticKeyword

You should access methods that are static using the class name rather thanan object reference, as illustrated in Code 5-7:

Code 5-7 Accessing a Class Method

1 public class TestCounter {2 public static void main(String[] args) {3 System.out.println("Number of counter is "4 + Count2.getTotalCount());5 Count2 count1 = new Count2();6 System.out.println("Number of counter is "7 + Count2.getTotalCount());8 }9 }

The output of the TestCounter program is:

Number of counter is 0Number of counter is 1

Because you can invoke a static method without any instance of theclass to which it belongs, there is no this value. The consequence is thata static method cannot access any variables other than the localvariables, static attributes, and its parameters. Attempting to accessnon-static attributes causes a compiler error.

Non-static attributes are bound to an instance and can be accessedthrough instance references only as illustrated by Code 5-8.

Code 5-8 Missing Instance Reference Example

1 public class Count3 {2 private int serialNumber;3 private static int counter = 0;45 public static int getSerialNumber() {6 return serialNumber; // COMPILER ERROR!7 }8 }

Note – The main() method is a static method because the JVMimplementation does not create an instance of the class when executingthe main method. So, if you have member data, you must create an objectto access it.

Creating a Class: Using Encapsulation 5-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 154: Sl275 Sg

Using the staticKeyword

Static Initializers

A class can contain code in static blocks that are not part of normalmethods. Static block code executes once when the class is loaded. If aclass contains more than one static block, they are executed in the order oftheir appearance in the class.

1 import com.mycompany.utilities.Database;2 public class Count4 {3 public static int counter;4 static {5 if (Database.tableExists("COUNTER")) {6 counter = Database.getSingleField("COUNTER");7 }8 }9 }

1 public class TestStaticInit {2 public static void main(String[] args) {3 System.out.println("counter = "+ Count4.counter);4 }5 }

The static initializer either retrieves the existing counter value from thedatabase (the package, class and methods mentioned are entirelyfictitious) or starts it at 1.

5-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 155: Sl275 Sg

Static Imports

Static Imports

If you have to access the static members of a class, then you must qualifythe references with the class. For example, see code lines 3 and 7 ofCode 5-7 on page 5-11. Since Java SE version 5.0, the Java programminglanguage provides the static import feature that enables unqualifiedaccess to static members without having to qualify them with the classname. Code 5-9 shows the use of static imports. Line 2 tells the compilerto include the static variable Math.PI in the symbol table when compilingthis program. Therefore, lines 12 and 16 can use PI without the Math.namespace prefix.

Code 5-9 The Circle Program Using Static Imports

1 package com.myproject.shapes;2 import static java.lang.Math.PI:34 public class Circle {5 private double radius;67 public Circle(double radius) {8 this.radius = radius;9 }1011 public double area() {12 return PI*radius*radius;13 }1415 public double circumferance {16 return 2*PI*radius;17 }18 }

Caution – Use static imports sparingly. If you overuse the static importfeature, it can make your program unreadable and unmaintainable,polluting its namespace with all of the static members that you import.Readers of your code (including you, a few months after you wrote it)will not know from which class a static member comes. Importing all ofthe static members from a class can be harmful to the readability; if youneed one or two members only, import them individually. Usedappropriately, static imports can make your program more readable, byremoving the repetition of class names.

Creating a Class: Using Encapsulation 5-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 156: Sl275 Sg
Page 157: Sl275 Sg

Module 6

Creating Arrays

Objectives

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

● Declare arrays

● Create arrays and reference arrays

● Initialize arrays

● Examine multi-dimensional arrays

● Examine array bounds and array size immutability

6-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 158: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following references provide additionalinformation on the topics described in this module:

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

● Bates, Sierra. Head First Java, Second Edition. O’Reilly Media. 2005.

6-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 159: Sl275 Sg

Declaring Arrays

Declaring Arrays

Arrays are used to group objects of the same type. Arrays enable you torefer to the group of objects by a common name.

You can declare arrays of any type: either primitive or class. For example,you can declare an array of char primitives as follows:

char[] s;

Similarly, an array of Point class (shown in Code 6-1) objects can bedeclared as follows:

Point[] p; // where Point is a class

Code 6-1 The Point Class

public class Point {int x;int y;

//constructors// methods

}

When declaring arrays with the brackets to the left, the brackets apply toall variables to the right of the brackets.

char[] myChars, yourChars, theirChars;Point[] myPoints, yourPoints, theirPoints;

In the Java programming language, an array is an object even when thearray is made up of primitive types, and as with other class types, thedeclaration does not create the object itself. Instead, the declaration of anarray creates a reference that you can use to refer to an array. The actualmemory used by the array elements is allocated dynamically either by anew statement or by an array initializer.

You can declare arrays using the square brackets after the variable name:

char s[];Point p[];

You see both formats used, but you should decide on one or the other foryour own use. The declarations do not specify the actual size of the array.

Creating Arrays 6-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 160: Sl275 Sg

Creating Arrays

Creating Arrays

You can create arrays, like all objects, using the new keyword. Forexample, to create an array of a primitive (char) type:

s = new char[26];

The first line creates an array of 26 char values. After creation, the arrayelements are initialized to the default value (‘\u0000’ for characters).You must fill in the array for it to be useful, for example:

1 public char[] createArray() {2 char[] s;3 s = new char[26];4 for ( int i=0; i<26; i++ ) {5 s[i] = (char) (’A’ + i);6 }7 return s;8 }

This code generates an array in the heap memory with the upper caseletters of the English alphabet. The array in heap is shown in Figure 6-1.

Figure 6-1 Creating an Array of Character Primitives

The subscript that indexes the individual array elements always beginsfrom 0 and must be maintained in the legal range: greater than or equal to0 and less than the array length. Any attempt to access an array elementoutside these bounds causes a runtime exception.

main

createArray s

this

char[]

A

Execution Stack

Heap Memory

B

C

D

Z

6-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 161: Sl275 Sg

Creating Reference Arrays

Creating Reference Arrays

You can create arrays of objects. You use the same syntax:

p = new Point[10];

This line creates an array of 10 references of type Point. However, it doesnot create 10 Point objects. Create these separately as follows:

1 public Point[] createArray() {2 Point[] p;34 p = new Point[10];5 for ( int i=0; i<10; i++ ) {6 p[i] = new Point(i, i+1);7 }8 return p;9 }

This code generates an array in the heap memory with each array elementfilled with a reference to a Point object. The array in heap is shown inFigure 6-2.

Figure 6-2 Creating an Array of References to Point Objects

main

createArray p

this

Point[]

Execution Stack

Heap Memory

Point

x

y

0

1

Point

x

y

1

2

Point

x

y

2

3

Creating Arrays 6-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 162: Sl275 Sg

Initializing Arrays

Initializing Arrays

When you create an array, every element is initialized. In the case of thechar array s in the previous section, each value is initialized to the null(‘\u0000’) character. In the case of the array p, each value is initialized tonull, indicating that it does not (yet) refer to a Point object. After theassignment p[0] = new Point(), the first element of the array refersto a real Point object.

Note – Initializing all variables, including elements of arrays, is essentialto the security of the system. You must not use variables in anuninitialized state.

The Java programming language allows a shorthand that creates arrayswith initial values:

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

};

This code is equivalent to:

String[] names;names = new String[3];names[0] = "Georgianna";names[1] = "Jen";names[2] = "Simon";

You can use this shorthand for any element type; for example:

MyDate[] dates = {new MyDate(22, 7, 1964),new MyDate(1, 1, 2000),new MyDate(22, 12, 1964)

};

6-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 163: Sl275 Sg

Multi-Dimensional Arrays

Multi-Dimensional Arrays

The Java programming language does not provide multi-dimensionalarrays in the same way that other languages do. Because you can declarean array to have any base type, you can create arrays of arrays (and arraysof arrays of arrays, and so on). The following example shows a two-dimensional array:

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

The object that is created by the first call to new is an array that containsfour elements. Each element is a null reference to an element of typearray of int and you must initialize each element separately so thateach element points to its array.

Note – Although the declaration format allows the square brackets to beat the left or right of the variable name, this flexibility does not carry overto other aspects of the array syntax. For example, new int[][4] is notlegal.

Because of this separation, you can create non-rectangular arrays ofarrays. That is, you can initialize the elements of twoDim as follows:

twoDim[0] = new int[2];twoDim[1] = new int[4];twoDim[2] = new int[6];twoDim[3] = new int[8];

Because this type of initialization is tedious, and the rectangular array ofarrays is the most common form, there is a shorthand to create two-dimensional arrays. For example, you can use the following to create anarray of four arrays of five integers each:

int[][] twoDim = new int[4][5];

Creating Arrays 6-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 164: Sl275 Sg

Array Bounds

Array Bounds

In the Java programming language, all array indices begin at 0. Thenumber of elements in an array is stored as part of the array object in thelength attribute. If an out-of-bounds runtime access occurs, then aruntime exception is thrown.

Use the length attribute to iterate on an array, as shown in Code 6-2.

Code 6-2 Using the Array Bounds to Iterate Over the Array

public void printElements(int[] list) {for ( int i = 0; i < list.length; i++ ) {

System.out.println(list[i]);}

}

Using the length attribute of the array makes program maintenanceeasier because you do not need to know the number of elements in thearray at compile time.

Using the Enhanced for Loop

Iterating over an array is a common task. The Java SE 5.0 platform hasadded an enhanced for loop to make array iteration easier. This is shownin Code 6-3.

Code 6-3 Using the Enhanced for Loop to Iterate Over the Array

public void printElements(int[] list) {for ( int element : list ) {

System.out.println(element);}

}

This version of the for loop can be read as for each element in list do.The compiler handles the iteration code. Code 6-3 is equivalent toCode 6-2.

Note – You should be aware that you cannot update array elements usingthe enhanced for loop.

6-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 165: Sl275 Sg

Array Size Immutability

Array Size Immutability

After it is created, you cannot resize an array. However, you can use thesame reference variable to refer to an entirely new array:

int[] myArray = new int[6];myArray = new int[10];

In this case, the first array effectively is lost unless another reference to itis retained elsewhere.

Creating Arrays 6-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 166: Sl275 Sg
Page 167: Sl275 Sg

Module 7

Creating aSubclassUsing Inheritance

Objectives

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

● Examine the concept of inheritance

● Implement inheritance in Java technology

● Override methods of the Object class

● Create polymorphism through subclasses

● Use the instanceof operator

● Use the final keyword

7-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 168: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following references provide additionalinformation on the topics described in this module:

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

● Bates, Sierra. Head First Java, Second Edition. O’Reilly Media. 2005.

7-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 169: Sl275 Sg

Examining the Concept of Inheritance

Examining the Concept of Inheritance

Inheritance is the mechanism for creating one or more subtypes from anexisting type. In Java technology, a class represents a type. Inheritanceallows you to create subclasses from existing classes.

In programming, you often create a model of something (for example, anemployee), and then need a more specialized version of that originalmodel. For example, you might want a model for a manager. A manageris an employee, but an employee with additional features.

Figure 7-1 shows the UML class diagrams that model the Employee andManager classes.

Figure 7-1 Class Diagrams for Employee and Manager

Code 7-1 and Code 7-2 show possible implementations of the Employeeand Manager classes as they are modeled in Figure 7-1.

Code 7-1 A Possible Implementation of the Employee Class

import java.util.Date;public class Employee {

public String name = "";public double salary;public Date birthDate;

public String getDetails() {...}}

Code 7-2 A Possible Implementation of the Manager Class

import java.util.Date;public class Manager {

public String name = "";public double salary;public Date birthDate;public String department;

Employee

+name : String = ""

+salary : double

+birthDate : Date

+getDetails() : String

Manager

+name : String = ""

+salary : double

+birthDate : Date

+department : String

+getDetails() : String

Creating a Subclass Using Inheritance 7-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 170: Sl275 Sg

Examining the Concept of Inheritance

public String getDetails() {...}}

This example illustrates the duplication of data between the Manager classand the Employee class. Additionally, there could be a number ofmethods applicable to both Employee and Manager. Therefore, you need away to create a new class from an existing class; this is called subclassing.

In object-oriented languages, special mechanisms are provided that enableyou to define a class in terms of a previously defined class. Figure 7-2shows the UML class diagram in which the Manager class is a subclass ofthe Employee class.

Figure 7-2 Class Diagrams for Employee and Manager UsingInheritance

Code 7-3 shows an implementation of the Manager class that inherits fromthe Employee class as modeled in Figure 7-2.

Code 7-3 Alternative Implementation of the Manager Class

public class Manager extends Employee {public String department;

}

Manager

+department : String

Employee

+name : String = ""

+salary : double

+birthDate : Date

+getDetails() : String

7-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 171: Sl275 Sg

Examining the Concept of Inheritance

Examining the Benefits of Inheritance

Inheritance provides the following benefits.

● Enables the creation of specialized types

A Manager class that inherits from an Employee class is said to be avariant or a specialized version (type) of the Employee class. Aspecialized type is a parent type in every way but it differs from itsparent in that it contains additional properties that give itspecialization.

● Eliminates duplication

As shown in Code 7-3 on page 7-4, the use of inheritance eliminatesthe duplication of code (Code 7-1 and Code 7-2 on page 7-3) thatwould have otherwise been needed to create specialized versions ofexisting types.

● Assists maintainability

The creation of a hierarchical set of types enables a single point oftouch style of maintenance. If the affected class is a child class thenonly the child class needs to be updated. The remaining classes areunaffected. If the affected class is a common parent then only theparent class needs to be updated. This update is inherited by allchild classes.

Creating a Subclass Using Inheritance 7-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 172: Sl275 Sg

Implementing Inheritance in Java Technology

Implementing Inheritance in Java Technology

The following steps provide a process for creating a subclass in Javatechnology.

1. Select the parent class.

2. Examine the parent class to determine what is inherited from theparent class.

3. Declare the subclass.

4. Add the attributes and methods specific to the subclass.

5. If required override parent class methods.

6. Add constructors to the subclass as needed.

These steps are explained in more detail in the following sections.

Note – The Java programming language permits a class to extend oneother class only. This restriction is called single inheritance. The relativemerits of single and multiple inheritance are the subject of extensivediscussions among object-oriented programmers. The Java programminglanguage contains a feature called interfaces that provides most of thebenefits of multiple inheritance without suffering from any of itsdrawbacks. A discussion of interfaces is outside the scope of this module.

7-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 173: Sl275 Sg

Implementing Inheritance in Java Technology

Step 1: Selecting the Parent Class

Figure 7-3 shows the base (parent) class Employee and three subclasses:Engineer, Manager, and Secretary. The Manager is also subclassed byDirector.

Figure 7-3 An Example Inheritance Tree

In Figure 7-3, the Employee class is selected as the parent class fromwhich three separate subclasses (Engineer, Manager and Secretary) willbe created.

Also in Figure 7-3, the Manager class is selected as the parent class fromwhich the Director will be subclassed.

Manager

+department : String = ""

Employee

+name : String = ""

+salary : double

+birthDate : Date

Director

+carAllowance : double

Engineer Secretary

+getDetails() : String

+increaseAllowance()

Creating a Subclass Using Inheritance 7-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 174: Sl275 Sg

Implementing Inheritance in Java Technology

Step 2: Determining What Is Inherited From the ParentClass

In this step, you examine the parent class to determine what is inheritedby the child class.

Code 7-4 shows a reduced implementation of an Employee class. Forillustrative purposes, the Employee class shown in Code 7-4 uses a varietyof access modifier settings for its attributes, constructor, and methods.

Code 7-4 Parent Class: Employee

import java.util.Date;public class Employee {

protected String name;private double salary;protected Date birthDate;

public Employee(String name) {}

public void setSalary(double salary) {} double getSalary() {return salary;}

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

+ “Salary: “ + salary;}

}

Table 7-1 illustrates the rules you can use to determine the attributes andmethods that any subclass of the Employee class inherits.

Table 7-1 Parent Class Attributes and Methods Inheritance Rules

AccessModifier Inheritance Rule Comment

private Inherited but notaccessible

For example, the private salary attribute isnot accessible to subclasses of the Employeeclass.

default Inherited and accessible ifthe subclass is in the samepackage as the parentclass

For example, if the child class is in the samepackage as the Employee class, the defaultgetSalary method is inherited andaccessible.

7-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 175: Sl275 Sg

Implementing Inheritance in Java Technology

Note – Constructors of the parent class are never inherited. Theinvolvement of the parent class constructors is discussed in ‘‘Step 6:Adding Constructors as Needed’’ on page 7-13.

Step 3: Declaring the Subclass

A subclass is declared using the extends keyword, as shown in Code 7-5.

Code 7-5 Example of Declaring a Subclass

public class Manager extends Employee {//

}

Note – The Java programming language permits a class to extend oneother class only. This restriction is called single inheritance.

Step 4: Adding the Attributes and Methods Specific tothe Subclass

In this step you add the attributes and methods that are unique to thesubclass. For example, the Manager class shown in Code 7-6 on page 7-10shows the addition of a department attribute and the corresponding getand set methods.

protected Inherited and accessible For example, the protectedattributes nameand birthDate are inherited andaccessible.

public Inherited and accessible For example, the public setSalarymethod is inherited and accessible.

Table 7-1 Parent Class Attributes and Methods Inheritance Rules

AccessModifier Inheritance Rule Comment

Creating a Subclass Using Inheritance 7-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 176: Sl275 Sg

Implementing Inheritance in Java Technology

Code 7-6 Manager Class With Attributes and Methods

public class Manager extends Employee {protected String department;

public String getDepartment() {return department;}public void setDepartment(String department) { }

}

Step 5: If Required, Overriding Parent Class Methods

An examination of the Manager class shown in Code 7-6 on page 7-10,shows that it does not define a getDetailsmethod. Instead it inherits thegetDetails method from its parent Employee class (shown in Code 7-7).However, the getDetailsmethod of the Employee class does not provideany Manager class attribute details such as the department attribute.

Code 7-7 The getDetails Method of the Employee Class

1 import java.util.Date;2 public class Employee {3 protected String name;4 protected double salary;5 protected Date birthDate;67 public Employee(String name) {}89 public void setSalary(double salary) {}10 public double getSalary() {return salary;}1112 public String getDetails() {13 return “Name: “ + name + “\n”14 + “Salary: “ + salary;15 }16 }

7-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 177: Sl275 Sg

Implementing Inheritance in Java Technology

In this situation, the Manager class is required to provide its owngetDetailsmethod to override its parents getDetailsmethod, as shownin Code 7-8.

Code 7-8 Manager Class Overriding the Parent’s getDetails Method

1 public class Manager extends Employee {2 protected String department;34 public String getDepartment() {return department;}5 public void setDepartment(String department) { }67 @Override8 public String getDetails() {9 return “Name: “ + name + “\n”10 + “Salary: “ + salary + “\n”11 + “Manager of: “ + department;12 }13 }

The Java technology specification imposes the following conditions towhich you must conform, when declaring an overriding method.

● Matching method interface requirements

If a method is defined in a subclass so that the name, return type,and argument list match exactly those of a method in the parentclass, then the new method is said to override the old one.

Since the Java SE 5.0 platform, these matching rules have changedslightly. The return type of the overriding method can now be asubclass of the inherited method. This is called a covariant return.

● The optional Override annotation

Since the Java SE 5.0 platform, you can use the Override annotationto inform the compiler that the method is meant to override amethod declared in a superclass. While it is not required to use thisannotation when overriding a method, it helps to prevent errors. If amethod marked with Override fails to correctly override a methodin one of its superclasses, the compiler generates an error. For moreinformation about annotations, refer to the following URL:

http://java.sun.com/javase/6/docs/technotes/guides/language/annotations.html

● Overriding methods cannot be less accessible

An overriding method cannot be less accessible than the method itoverrides.

Creating a Subclass Using Inheritance 7-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 178: Sl275 Sg

Implementing Inheritance in Java Technology

Consider the invalid scenario shown in Code 7-9:

Code 7-9 Invalid Access Modifier Setting Scenario

public class Parent {public void doSomething() {}

}

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

}

Invoking Overridden Methods

A subclass method can invoke a superclass method using the superkeyword.

The super keyword refers to the superclass of the class in which thekeyword is used. It is used to refer to the member variables or themethods of the superclass.

This can be achieved using the keyword super as follows:

import java.util.Date;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;}

}

7-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 179: Sl275 Sg

Implementing Inheritance in Java Technology

A call of the form super.method() invokes the entire behavior, alongwith any side effects of the method that would have been invoked if theobject had been of the parent class type. The method does not have to bedefined in that parent class; it could be inherited from some class evenfurther up the hierarchy.

Note – In the previous example, member variables have been declared asprivate. This is not necessary but is a generally good programmingpractice.

Step 6: Adding Constructors as Needed

If you provide a constructor for the subclass, its purpose is to initialize theattributes of the child class. The construction of a subclass instancerequires the prior construction and initialization of the superclassinstance. For example, the construction of the Manager class instanceresults in the prior construction of the Employee class. When declaringconstructors in the child class, you should take the followingconsiderations into account.

● Unless the superclass is in development, the superclass should betreated as immutable and no new superclass constructors should beadded.

● The subclass constructor is responsible for invoking the appropriatesuperclass constructor either explicitly or implicitly.

● The superclass fields must be initialized before the subclass fields.

The following steps provide one possible approach you could take todeclare subclass constructors.

Step A: Analyzing the Superclass Constructors

This section shows three alternative declarations of a superclass namedEmployee. The constructor declaration is the differentiation between thealternative declarations. Code 7-10 is an example of a superclass with acompiler-provided default (no-arg) constructor.

Code 7-10 Superclass With a No-arg Constructor Only

1 public class Employee {2 private String name;3 // methods4 }

Creating a Subclass Using Inheritance 7-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 180: Sl275 Sg

Implementing Inheritance in Java Technology

Code 7-11 is an example of a parent class without a no-arg constructor. Ithas an explicitly declared with-arg constructor.

Code 7-11 Superclass Without a No-arg Constructor

1 public class Employee {2 private String name;3 public Employee(String name) {4 this.name = name;5 }6 }

Code 7-12 is an example of a parent class with an explicitly declaredconstructor and a no-arg constructor.

Code 7-12 Superclass With a No-arg and arg Constructor

1 public class Employee {2 private String name;3 public Employee() {// some code here}4 public Employee(String name) {5 this.name = name;6 }7 }

Step B: Declaring the Subclass Constructors

You should declare the constructors in the child class that you need toinitialize the variables of the child class. Code 7-13 shows a constructordeclaration in a subclass of the Employee class.

Code 7-13 Subclass With Constructor

1 public class Manager extends Employee {2 private String department;3 public Manager(String department) {4 this.department = department;5 }6 // remaining code not shown7 }

7-14 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 181: Sl275 Sg

Implementing Inheritance in Java Technology

Step C: Invoking the Appropriate Superclass Constructor FromEach Subclass Constructor

In this step, you address the requirement for superclass attributes to beinitialized before the subclass attributes. What this means in practice isthat before the body of a child class constructor can execute, a parent classconstructor must execute. This might require the modification of theconstructors of the child class you declared in the previous step. Themodifications involve the following actions.

● For each child class constructor, determine the pre-invoked parentclass constructor.

● If the pre-invoked parent class constructor accepts one or moreparameters, you must modify the child class constructor to acceptand pass these parameters to the parent constructor. You do this byinvoking a super (<arg-list>) as the first line of code in the childconstructor. These arguments are, in most cases, sent as parametersto the child constructor.

Note – There is an exception to the requirement to explicitly invoke theparent class constructor. You do not need to explicitly invoke the no-arg ordefault parent class constructor. In the absence of an explicit super( ) orthis( ) in the first line of the child class constructor, the compiler insertsa hidden invocation to the parent class no-arg constructor.

Line 4 of the Manager class, shown in Code 7-14, demonstrates theoptional requirement for the subclass constructor to explicitly invoke thesuperclass no-arg (in this case the default) constructor of the Employeeclass.

Code 7-14 Example 1: Explicit Invocation of a Parent No-arg Constructor

1 public class Employee {2 private String name;3 // methods4 }

1 public class Manager extends Employee {2 private String department;3 public Manager(String department) {4 super(); // Note: explicit super is optional5 this.department = department;6 }7 }

Creating a Subclass Using Inheritance 7-15Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 182: Sl275 Sg

Implementing Inheritance in Java Technology

Line 4 of the Manager class, shown in Code 7-15, demonstrates therequirement for the subclass constructor to explicitly invoke the with-argconstructor of the Employee class. You should also note the addition ofthe name parameter to the Manager class constructor to pass it to thesuperclass constructor.

Code 7-15 Example 2: Explicit Invocation of a Parent’s With-argConstructor

1 public class Employee {2 private String name;3 public Employee(String name) {4 this.name = name;5 }6 }

1 public class Manager extends Employee {2 private String department;3 public Manager(String name, String department) {4 super(name); // Note: explicit super required5 this.department = department;6 }7 }

Line 4 of the Manager class shown in Code 7-16 demonstrates therequirement for the subclass constructor to explicitly invoke thesuperclass with-arg constructor of the Employee class. In this situation,you do not get a compiler error if you did not explicitly invokesuper(name). The compiler adds an invocation to the superclass’s no-argconstructor. Although the code compiles, the name attribute of thesuperclass is set to null. From an application perspective, this is an errorcondition.

Code 7-16 Example 3: Parent With-arg and No-arg Constructors

1 public class Employee {2 private String name;3 public Employee() {// some code here}4 public Employee(String name) {5 this.name = name;6 }7 }

1 public class Manager extends Employee {2 private String department;3 public Manager(String name, String department) {

7-16 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 183: Sl275 Sg

Implementing Inheritance in Java Technology

4 super(name); // Note: code will compile with this line removed5 this.department = department;6 }7 }

Creating a Subclass Using Inheritance 7-17Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 184: Sl275 Sg

Implementing Inheritance in Java Technology

A Complex Constructor Chaining Example

Many classes, both superclasses and subclasses, have overloadedconstructors. This can lead to constructor chaining using the thiskeyword, as shown in Code 7-17:

Code 7-17 Example 4: Employee and Manager Classes With ConstructorChaining

1 public class Employee {2 private String name;3 private double salary;45 public Employee(String name, double salary) {6 this.name = name;7 this.salary = salary;8 }910 public Employee(String name) {11 this(name, 15000.00);12 }13 }

1 public class Manager extends Employee {2 private String department;34 public Manager(String name, double salary, String department) {5 super(name, salary);6 this.department = department;7 }89 public Manager(String name, String department) {10 super(name);11 this.department = department;12 }1314 public Manager(String name) {15 this(name, “**NO DEPARTMENT YET**”);16 }17 }

7-18 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 185: Sl275 Sg

Implementing Inheritance in Java Technology

If some external code were to instantiate a manager as follows:

Manager m = new Manager(“Joe Soap”);

then the sequence of events would be as follows:

● Start the constructor at line 14 of the Manager class.

● Transfer the supplied name and a dummy department identifier tothe constructor at line 9 of Manager.

● Call the constructor at line 10 of Employee and forward the suppliedname.

● Transfer the supplied name and a fixed starting salary to theconstructor at line 5 of Employee.

● Automatically call the Employee’s superclass (the Object class) no-argument constructor.

● Execute line 6 of Employee, that is store “Joe Soap” in the name field.

● Execute line 7 of Employee, that is store 15000.00 in the salary field.

● Return to execute line 11 of Manager, that is store “**NODEPARTMENT YET**” in the department field.

Note – The automatic call to super() is inserted only when the firststatement within the constructor is neither a call to a parent constructornor a transfer to a sibling constructor. The use of the this or superkeywords in constructor invocation is restricted to the first executable lineof a constructor.

Creating a Subclass Using Inheritance 7-19Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 186: Sl275 Sg

Polymorphism

Polymorphism

Describing a Manager as is an Employee is not just a convenient way ofdescribing the relationship between these two classes. Recall that theManager has all the members, both fields and methods, of the parent classEmployee. This means that any operation that is legitimate on anEmployee is also legitimate on a Manager. If the Employee has the methodgetDetails, then the Manager class does also.

It might seem unrealistic to create a Manager and deliberately assign thereference to it to a variable of type Employee. However, this is possible,and there are reasons why you might want to achieve this effect.

An object has only one form: the one that is given to it when constructed.However, a variable is polymorphic because it can refer to objects ofdifferent forms.

The Java programming language, like most object-oriented languages,actually permits you to refer to an object with a variable that is one of theparent class types. So you can say:

Employee e = new Manager(); //legal

Using the variable e as is, you can access only the parts of the object thatare part of Employee; the Manager-specific parts are hidden. This isbecause as far as the compiler is concerned, e is an Employee, not aManager. Therefore, the following is not permitted:

// Illegal attempt to assign Manager fielde.department = "Sales"; // assume department declared as a public field// the variable is declared as an Employee type,// even though the Manager object has that field

Virtual Method Invocation

Assume that the following scenario is true:

Employee worker = new Employee();Manager boss = new Manager();

7-20 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 187: Sl275 Sg

Polymorphism

If you ask for worker.getDetails() and boss.getDetails(), youinvoke different behaviors. The Employee object executes the version ofgetDetails() associated with the Employee class, and the Managerobject executes the version of getDetails() associated with the Managerclass.

What is less obvious is what happens if you have:

Employee worker = new Manager();worker.getDetails();

or something similar, such as a general method argument or an item froma heterogeneous collection.

In fact, you get the behavior associated with the object to which thevariable refers at runtime. The behavior is not determined by the compiletime type of the variable. This is an aspect of polymorphism, and is animportant feature of object-oriented languages. This behavior is oftenreferred to as virtual method invocation.

In the previous example, the worker.getDetails() method executed isfrom the object’s real type, a Manager.

Polymorphism and staticMethods

You cannot override a static method but you can hide it. For a methodto be overridden, it must be non-static. Two static methods with the samesignature in a class hierarchy means that there are two independent classmethods. If a class method is applied to an object reference, the methodinvoked is the one for the class for which the variable was declared.

For example:

// Assume ClassB extends ClassA// Assume ClassA contains a static method named staticMethod// Assume ClassB declares a static method named staticMethod with// the same method signature as that in ClassAClassA obj = new ClassB();obj.staticMethod(); // The classA.staticMethod will be called.

Creating a Subclass Using Inheritance 7-21Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 188: Sl275 Sg

Polymorphism

Heterogeneous Collections

You can create collections of objects that have a common class. Suchcollections are called homogeneous collections. For example:

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

The Java programming language has an Object class, so you can makecollections of all kinds of elements because all classes extend class Object.These collections are called heterogeneous collections.

A heterogeneous collection is a collection of dissimilar items. Inobject-oriented languages, you can create collections of many items. Allhave a common ancestor class: the Employee class. For example:

Employee [] staff = new Employee[1024];staff[0] = new Manager();staff[1] = new Employee();staff[2] = new Engineer();

You can even write a sort method that puts the employees into age orsalary order, regardless of whether some of these employees aremanagers.

Note – Every class is a subclass of Object, so you can use an array ofObject as a container for any combination of objects. The only items thatcannot be added to an array of Object are primitive variables. However,you can create objects from primitive data using wrapper classes.

Polymorphic Arguments

You can write methods that accept any object (in this case, the classEmployee) and work properly on objects of any subclass of this object.You might produce a method in an application class that takes anemployee and compares it with a certain threshold salary to determine thetax liability of that employee. Using the polymorphic features, you can dothis as follows:

public class TaxService {public TaxRate findTaxRate(Employee e) {

// do calculations and return a tax rate for e

7-22 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 189: Sl275 Sg

Polymorphism

}}

// Meanwhile, elsewhere in the application classTaxService taxSvc = new TaxService();Manager m = new Manager();TaxRate t = taxSvc.findTaxRate(m);

This is legal because a Manager is an Employee. However, thefindTaxRate method has access only to the members (both variables andmethods) that are defined in the Employee class.

Creating a Subclass Using Inheritance 7-23Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 190: Sl275 Sg

The instanceofOperator

The instanceofOperator

Given that you can pass objects around using references to their parentclasses, sometimes you might want to know what actual objects you have.This is the purpose of the instanceof operator. Suppose the classhierarchy is extended so that you have the following:

public class Employeepublic class Manager extends Employeepublic class Engineer extends Employee

If you receive an object using a reference of type Employee, it might turnout to be a Manager or an Engineer. You can test it by using instanceofas follows:

public void doSomething(Employee e) {if ( e instanceof Manager ) {

// Process a Manager} else if ( e instanceof Engineer ) {

// Process an Engineer} else {

// Process any other type of Employee}

}

7-24 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 191: Sl275 Sg

The instanceofOperator

Casting Object References

In circumstances where you have received a reference to a parent class,and you have determined that the object is a particular subclass by usingthe instanceof operator, you can access the full functionality of theobject by casting the reference.

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

}

If you do not make the cast, an attempt to execute e.getDepartment()fails because the compiler cannot locate a method called getDepartmentin the Employee class.

If you do not make the test using instanceof, you run the risk of the castfailing. Generally, any attempt to cast an object reference is subjected toseveral checks:

● Casts upward in the class hierarchy are always permitted and, in fact,do not require the cast operator. They can be done by simpleassignment.

● For downward casts, the compiler must be satisfied that the cast is atleast possible. For example, any attempt to cast a Manager referenceto a Engineer reference is not permitted, because the Engineer isnot a Manager. The class to which the cast is taking place must besome subclass of the current reference type.

● If the compiler permits the cast, then the object type is checked atruntime. For example, if it turns out that the instanceof check isomitted from the source, and the object being cast is not in fact anobject of the type to which it is being cast, then a runtime error(exception) occurs. Exceptions are a form of runtime error and are thesubject of a later module.

Creating a Subclass Using Inheritance 7-25Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 192: Sl275 Sg

The ObjectClass

The ObjectClass

The Object class is the root of all classes in the Java programminglanguage. If a class is declared with a no extends clause, then the compileradds implicitly the code extends Object to the declaration; for example:

public class Employee {// more code here

}

is equivalent to:

public class Employee extends Object {// more code here

}

This enables you to override several methods inherited from the Objectclass. The following sections describe two important Object methods.

The equalsMethod

The == operator performs an equivalent comparison. That is, for anyreference values x and y, x==y returns true if and only if x and y refer tothe same object.

The Object class in the java.lang package has the methodpublic boolean equals(Object obj), which compares two objects forequality. When not overridden, an object’s equals()method returns trueonly if the two references being compared refer to the same object.However, the intention of the equals() method is to compare thecontents of two objects whenever possible. This is why the method isfrequently overridden. For example, the equals() method in the Stringclass returns true if the argument is not null and is a String object thatrepresents the same sequence of characters as the String object withwhich the method is invoked.

Note – You should override the hashCodemethod whenever you overridethe equals method. A simple implementation could use a bitwise XORon the hash codes of the elements tested for equality.

7-26 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 193: Sl275 Sg

The ObjectClass

An equalsMethod Example

In the equals method example shown in Code 7-18, the MyDate class hasbeen modified to include an equals method that tests against the year,month, and day attributes.

Code 7-18 An equals and hashCode Method Example

1 public class MyDate {2 private int day;3 private int month;4 private int year;56 public MyDate(int day, int month, int year) {7 this.day = day;8 this.month = month;9 this.year = year;10 }1112 @Override13 public boolean equals(Object o) {14 boolean result = false;15 if ( (o != null) && (o instanceof MyDate) ) {16 MyDate d = (MyDate) o;17 if ( (day == d.day) && (month == d.month)18 && (year == d.year) ) {19 result = true;20 }21 }22 return result;23 }2425 @Override26 public int hashCode() {27 return (day<<4 ^ month ^ year);28 }29 }

A hashCodeMethod

The hashCode method shown in Code 7-18 implements a bitwise XOR ofthe date attributes. This guarantees that hash codes for equal MyDateobjects have the same value while making it likely that different datesreturn different values.

Creating a Subclass Using Inheritance 7-27Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 194: Sl275 Sg

The ObjectClass

The following program (Code 7-19) tests two MyDate objects that are notidentical, but are equal relative to the year-month-day test.

Code 7-19 Hash Code Test

1 class TestEquals {2 public static void main(String[] args) {3 MyDate date1 = new MyDate(14, 3, 1976);4 MyDate date2 = new MyDate(14, 3, 1976);56 if ( date1 == date2 ) {7 System.out.println("date1 is identical to date2");8 } else {9 System.out.println("date1 is not identical to date2");10 }1112 if ( date1.equals(date2) ) {13 System.out.println("date1 is equal to date2");14 } else {15 System.out.println("date1 is not equal to date2");16 }1718 System.out.println(“set date2 = date1;”);19 date2 = date1;2021 if ( date1 == date2) {22 System.out.println(“date1 is identical to date2”);23 } else {24 System out.println(“date1 is not identical to date2”);25 }26 }27 }

This example generates the following output:

date1 is not identical to date2date1 is equal to date2set date2 = date1;date1 is identical to date2

7-28 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 195: Sl275 Sg

The ObjectClass

The toStringMethod

The toString method converts an object to a String representation. It isreferenced by the compiler when automatic string conversion takes place.For example, the System.out.println() call:

Date now = new Date();System.out.println(now);

is equivalent to:

System.out.println(now.toString());

The Object class defines a default toStringmethod that returns the classname and its hash code. Many classes override toString to provide moreuseful information. For example, all wrapper classes override toStringto provide a string form of the value they represent. Even classesrepresenting items without a string form often implement toString toreturn object state information for debugging purposes.

Creating a Subclass Using Inheritance 7-29Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 196: Sl275 Sg

The finalKeyword

The finalKeyword

The Java technology specification contains a final keyword that can beapplied to classes, methods, and variables. The application of the finalkeyword makes the applied element immutable. The following sectionsprovide more detail on the application of the final keyword to classes,methods, and variables.

Final Classes

The Java programming language permits you to apply the keywordfinal to classes. If you do this, the class cannot be subclassed. Forexample, the class java.lang.String is a final class. This is done forsecurity reasons, because it ensures that if a method references a string, itis a definite string of class String and not a string of a class that is amodified subclass of String that might have been changed.

Final Methods

You can also mark individual methods as final. Methods marked finalcannot be overridden. For security reasons, you should make a methodfinal if the method has an implementation that should not be changedand is critical to the consistent state of the object.

Making a method final has no performance effect. The compiler cangenerate code that causes a direct call to the method, rather than the usualvirtual method invocation that involves a runtime lookup. Methodsmarked as static or private can be optimized by the compiler as if theyhad been marked final, because dynamic binding cannot be applied ineither case.

Final Variables

If a variable is marked as final, the effect is to make it a constant. Anyattempt to change the value of a final variable causes a compiler error.The following example shows a final variable that is defined properly:

public class Bank {private static final double DEFAULT_INTEREST_RATE=3.2;// more declarations

}

7-30 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 197: Sl275 Sg

The finalKeyword

Note – If you mark a variable of reference type (that is, any class type) asfinal, that variable cannot refer to any other object. However, you canchange the object’s contents, because only the reference itself is final.

Blank Final Variables

A blank final variable is a final variable that is not initialized in itsdeclaration. The initialization is delayed. A blank final variable must haveits value set before the end of the instantiation process. To achieve this, ablank final instance variable must be assigned in every constructor, but itcan be set once only. A blank final variable that is a local variable can beset at any time in the body of the method, but it can be set once only. Thefollowing code fragment is an example of how you can use a blank finalvariable in a class:

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

}

Creating a Subclass Using Inheritance 7-31Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 198: Sl275 Sg
Page 199: Sl275 Sg

Module 8

ErrorHandlingUsingExceptionClassesandAssertions

Objectives

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

● Define exceptions and assertions

● Handle exceptions using the try-catch statement, multiple catchclauses, and the finally clause

● Describe common exceptions

● Examine the handle or declare rule

● Describe method overriding and exceptions

● Create your own exceptions

● Use assertions

8-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 200: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following references provide additionalinformation on the topics described in this module:

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

● Bates, Sierra. Head First Java, Second Edition. O’Reilly Media. 2005.

8-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 201: Sl275 Sg

Exceptions and Assertions

Exceptions and Assertions

Exceptions are a mechanism used by many programming languages todescribe what to do when something unexpected happens. Typically,something unexpected is an error of some sort, for example when amethod is invoked with unacceptable arguments, or a network connectionfails, or the user asks to open a non-existent file.

Assertions are a way to test certain assumptions about the logic of aprogram. For example, if you believe that at a particular point, the valueof a variable is always positive, then you can test this with an assertion.Assertions are used to test assumptions about local program logic inside amethod, and usually not to test that external expectations are met.

One important feature of assertions is that they can be removed entirelyfrom the code when it runs. This means you can enable assertions duringprogram development, but not have the tests executed at runtime whenthe final product is delivered to a customer. This is an importantdifference between assertions and exceptions.

Exceptions

The Java programming language provides two broad categories ofexceptions, known as checked and unchecked exceptions.

Checked exceptions are those that the programmer is expected to handlein the program, and that arise from external conditions that can readilyoccur in a working program. Examples would be a requested file notbeing found or a network failure.

Unchecked exceptions might arise from conditions that represent bugs, orsituations that are considered too difficult for a program to handlereasonably. They are called unchecked because you are not required tocheck for them or do anything about them if they occur. Exceptions thatarise from a category of situations that probably represent bugs are calledruntime exceptions. An example of a runtime exception is attempting toaccess beyond the end of an array.

Exceptions that arise as a result of environmental issues that are rareenough or hard enough to recover from are called errors. An example ofan error is running out of memory. Errors are also unchecked exceptions.

Error Handling Using Exception Classes and Assertions 8-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 202: Sl275 Sg

Exceptions and Assertions

The Exception class is the base class that represents checked andunchecked exceptions. Rather than terminating the program, it is best ifyou write code to handle the exception and continue.

The Error class is the base class used for the unchecked, serious errorconditions from which your program is not expected to attempt recovery.In most cases, you should let the program terminate when you encounterthis type of error, although you might attempt to preserve as much of theuser’s work as possible.

The RuntimeException class is the base class that is used for theunchecked exceptions that might arise as a result of program bugs. Inmost cases, you should terminate the program when one of these arises.Again, attempting to preserve as much of the user’s work as possible is agood idea.

When an exception occurs in your program, the method that finds theerror can handle the exception itself or throw the exception back to itscaller to signal that a problem has occurred. The calling method then hasthe same choices: handle the exception or throw it back to its caller. If anexception reaches the top of an execution thread, then that thread is killed.This scheme gives the programmer the option of writing a handler to dealwith the exception at an appropriate point in the code.

You can determine the checked exceptions a method throws by browsingthe API. Sometimes you might also find documentation describing one ormore unchecked exceptions, but this is usually unnecessary, and youcannot rely on such information being listed.

Exception Example

Code 8-1 shows a program that adds all of the command-line arguments.

Code 8-1 Example Program that Throws an Exception

1 public class AddArguments {2 public static void main(String args[]) {3 int sum = 0;4 for ( int i = 0; i < args.length; i++ ) {5 sum += Integer.parseInt(args[i]);6 }7 System.out.println("Sum = " + sum);8 }9 }

8-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 203: Sl275 Sg

Exceptions and Assertions

This program works fine if all of the command-line arguments areintegers. For example:

java AddArguments 1 2 3 4Sum = 10

This program fails if any of the arguments are not integers:

java AddArguments 1 two 3.0 4Exception in thread "main" java.lang.NumberFormatException:For input string: "two"atjava.lang.NumberFormatException.forInputString(NumberFormatException.java:48)

at java.lang.Integer.parseInt(Integer.java:447)at java.lang.Integer.parseInt(Integer.java:497)at AddArguments.main(AddArguments.java:5)

Error Handling Using Exception Classes and Assertions 8-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 204: Sl275 Sg

The try-catchStatement

The try-catchStatement

The Java programming language provides a mechanism for figuring outwhich exception was thrown and how to recover from it. Code 8-2demonstrates a modified AddArguments program that uses a try-catchstatement to catch the exception, in this case ajava.lang.NumberFormatException.

Code 8-2 Example Program that Handles an Exception

1 public class AddArguments2 {2 public static void main(String args[]) {3 try {4 int sum = 0;5 for ( int i = 0; i < args.length; i++ ) {6 sum += Integer.parseInt(args[i]);7 }8 System.out.println("Sum = " + sum);9 } catch (NumberFormatException nfe) {10 System.err.println("One of the command-line "11 + "arguments is not an integer.");12 }13 }14 }

This program captures the exception and then quits with an errormessage:

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

8-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 205: Sl275 Sg

The try-catchStatement

Fine-Grained Exception Handling

The try-catch statement can be used on smaller chunks of code.Code 8-3 shows the try-catch statement used inside of the for loop.This enables the program to discard only those command-line argumentsthat are not integers. This code demonstrates a more graceful degradationin behavior than the AddArguments2 program.

Code 8-3 A Refined AddArguments Program

1 public class AddArguments3 {2 public static void main (String args[]) {3 int sum = 0;4 for ( int i = 0; i < args.length; i++ ) {5 try {6 sum += Integer.parseInt(args[i]);7 } catch (NumberFormatException nfe) {8 System.err.println("[" + args[i] + "] is not an integer"9 + " and will not be included in the sum.");10 }11 }12 System.out.println("Sum = " + sum);13 }14 }

This program captures the exception for each non-integer, command-lineargument and generates an warning message. However, this programproceeds to sum all of the valid integers:

java AddArguments3 1 two 3.0 4[two] is not an integer and will not be included in thesum.[3.0] is not an integer and will not be included in thesum.Sum = 5

Error Handling Using Exception Classes and Assertions 8-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 206: Sl275 Sg

The try-catchStatement

Using Multiple catchClauses

There can be multiple catch blocks after a try block, each handling adifferent exception type. Code 8-4 illustrates the syntax of using multiplecatch clauses.

Code 8-4 Example Using Multiple catch Clauses

try {// code that might throw one or more exceptions

} catch (MyException e1) {// code to execute if a MyException is thrown

} catch (MyOtherException e2) {// code to execute if a MyOtherException is thrown

} catch (Exception e3) {// code to execute if any other exception is thrown

}

If you have multiple catch clauses for a try block, the wrong order of thecatch clauses causes a compilation error. That is because an exceptionthrown from the try block is handled by the first catch clause that canhandle it. If, in this example, the Exception catch clause is put first, thenit handles all exceptions, and the MyException or MyOtherExceptioncatch clauses are never invoked.

Call Stack Mechanism

If a statement throws an exception, and that exception is not handled inthe immediately enclosing method, then that exception is thrown to thecalling method. If the exception is not handled in the calling method, it isthrown to the caller of that method. This process continues. If theexception is still not handled by the time it gets back to the main()method and main() method does not handle it, the exception terminatesthe program abnormally.

8-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 207: Sl275 Sg

The try-catchStatement

Consider a case in which the main()method calls another method namedfirst(), and this, in turn, calls another method named second(). If anexception occurs in second() and is not handled there, it is thrown backto first(). Imagine that in first() there is a catch for that type ofexception. In this case, the exception is handled and goes no further.However, if the first()method does not have any catch for this type ofexception, then the next method in the call stack, main(), is checked. Ifthe exception is not handled in main(), then the exception is printed tothe standard output and the program stops executing.

The finallyClause

The finally clause defines a block of code that always executes,regardless of whether an exception was caught. The following samplecode and description is taken from the white paper, Low Level Security inJava, by Frank Yellin:

1 Hose myHose = new Hose();2 try {3 myHose.startFaucet();4 myHose.waterLawn();5 } catch (BrokenPipeException e) {6 logProblem(e);7 } finally {8 myHose.stopFaucet();9 }

In the previous example, the faucet is turned off regardless of whether anexception occurs while starting the faucet or while watering the lawn. Thecode inside the braces after try is called the protected code.

The only situations that prevent the finally clause executing are avirtual machine shutdown (for example if the System.exit method isexecuted, or the machine is shut down or has its power turned off). Thisimplies that the control flow can deviate from normal sequentialexecution. For example, if a return statement is embedded in the codeinside the try block, the code in the finally clause executes before thereturn.

Error Handling Using Exception Classes and Assertions 8-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 208: Sl275 Sg

Exception Categories

Exception Categories

Earlier in this module you were introduced to two broad categories ofexceptions. This section examines the class hierarchy that represents thosecategories. The class java.lang.Throwable acts as the parent class for allobjects that can be thrown and caught using the exception-handlingmechanisms. Methods defined in the Throwable class retrieve the errormessage associated with the exception and print the stack trace showingwhere the exception occurred. There are three key subclasses ofThrowable: Error, RuntimeException, and Exception, which are shownin Figure 8-1.

Figure 8-1 Subclasses and Exceptions

Throwable

Error

Exception

RuntimeException

IOException

ArithmeticException

NullPointerException

IllegalArgumentException

FileNotFoundException

VirtualMachineError

AssertionError

StackOverflowError

OutOfMemoryError

EOFException

SQLException

8-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 209: Sl275 Sg

Exception Categories

You should not use the Throwable class; instead, use one of the subclassexceptions to describe any particular exception. The following describesthe purpose of each exception:

● The value Error indicates a severe problem from which recovery isdifficult, if not impossible. An example is running out of memory. Aprogram is not expected to handle such conditions.

● The value RuntimeException indicates a design or implementationproblem. That is, it indicates conditions that should never happen ifthe program is operating properly. A NullPointerException, forexample, should never be thrown if the developer remembers toassociate reference variables with new or existing objects on theheap. Because a program that is designed and implemented correctlynever issues this type of exception, it is usual to leave it unhandled.This results in a message at runtime, and ensures that action is takento correct the problem, rather than hiding it where (you think) noone will notice.

● Other exceptions indicate a difficulty at runtime that is most oftencaused by environmental effects and can be handled. Examplesinclude a file not found or invalid URL exceptions (the user typed awrong URL), both of which could occur easily if the user mistypedsomething. Because these occur usually as a result of user error, youare encouraged to handle them.

Error Handling Using Exception Classes and Assertions 8-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 210: Sl275 Sg

Common Exceptions

Common Exceptions

The Java programming language provides several predefined exceptions.Some of the more common exceptions are:

● NullPointerException

This is an attempt to access an attribute or method of an object usinga variable that does not refer to an object. For example, when thevariable has not been initialized or when no object has beeninstantiated.

Employee emp = null;System.out.println( emp.getName() );

● FileNotFoundException

This exception is an attempt to read from a file that does not exist.

● NumberFormatException

This exception is an attempt to parse a string into a number (integeror floating point number) that has an illegal number format.

● ArithmeticException

This is the result of a divide-by-zero operation for integers.

int i = 0;int j = 12 / i;

● SecurityException

Typically thrown in a browser, the SecurityManager class throws anexception for applets that attempt to perform any operation thatmight be dangerous to the host or its files. The following areexamples of operations that can cause security exceptions:

● Access the local file system.

● Open a socket to a host that is not the same host that served theapplet.

● Execute another program in a runtime environment.

8-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 211: Sl275 Sg

The Handle or Declare Rule

The Handle or Declare Rule

To encourage the writing of robust code, the Java programming languagerequires that if any checked exception (that is, a subclass of Exceptionbut not a subclass of RuntimeException) might occur at any given pointin the code, then the method that contains that point must defineexplicitly what action is to be taken if the problem arises.

You can do the following to satisfy this requirement:

● Handle the exception by using the try-catch-finally block.

Have the enclosing method handle the exception by including atry-catch block around the possible problem. The catch clausemust name either the expected exception class or a superclass. Thiscounts as handling the situation, even if the catch clause is empty.

● Declare exceptions that a method can throw.

Have the called method indicate that it does not handle theexception, and that the exception is thrown back to its callingmethod. This is, declaring the exception and passing responsibility todeclare or handle the exception to the calling method.

A method can declare that an exception might be thrown in the bodyof the method with a throws clause as follows:

void trouble() throws IOException {...}

Following the keyword throws is a list of all the exceptions that themethod can throw back to its caller. Although only one exception isshown here, you can use a comma-separated list if this methodthrows multiple possible exceptions, like this:

void trouble() throws IOException, OtherException {...}

You do not need to declare runtime exceptions or errors. All subclasses ofRuntimeException and Error are called unchecked and do not need tobe included in the throws clause of the method declaration.

You can choose to handle runtime exceptions. Usually, most runtimeexceptions indicate a programming logic bug. It is most appropriate todiscover these bugs during testing and fix them before the code is put intoproduction. Therefore, there is no need to include catch clauses forruntime exceptions. There are a few notable exceptions to this rule. Forexample, catching a NumberFormatException when parsing auser-entered string is useful.

Error Handling Using Exception Classes and Assertions 8-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 212: Sl275 Sg

The Handle or Declare Rule

Whether you choose to handle or declare an exception depends onwhether you consider yourself or your caller a more appropriatecandidate for dealing with the exception.

Note – Because the exception classes are organized into hierarchies, thesame as other classes, and because you can use a class whenever asubclass is expected, you can catch groups of exceptions and handle themwith the same catch code. For example, although there are severaldifferent types of IOExceptions (EOFException,FileNotFoundException, and so on), by trapping IOException, you canalso catch instances of any subclass of IOException.

8-14 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 213: Sl275 Sg

Method Overriding and Exceptions

Method Overriding and Exceptions

When overriding a method that throws exceptions, the overriding methodcan declare only exceptions that are either the same class or a subclass ofthe exceptions. For example, if the superclass method throws anIOException, then the overriding method can throw an IOException, aFileNotFoundException (a subclass of IOException), but not anException (the superclass of IOException) or an SQLException. You candeclare fewer or more specific exceptions in the throws clause.

In the following example, three classes are declared: TestA, TestB1, andTestB2. TestA is the superclass of TestB1 and TestB2.

1 public class TestA {2 public void methodA() throws IOException {3 // do some number crunching4 }5 }

1 public class TestB1 extends TestA {2 public void methodA() throws EOFException {3 // do some number crunching4 }5 }

1 public class TestB2 extends TestA {2 public void methodA() throws Exception {3 // do some number crunching4 }5 }

The class TestB1 compiles because EOFException is a subclass ofIOException. However, class TestB2 fails to compile because Exceptionis a superclass of IOException.

You can declare that an overriding method throws fewer exceptions thanthe superclass method, including no exceptions at all. The new restrictedset becomes the limits on what might be thrown by any sub-subclassesthat are created.

Error Handling Using Exception Classes and Assertions 8-15Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 214: Sl275 Sg

Creating Your Own Exceptions

Creating Your Own Exceptions

User-defined exceptions are created by extending the Exception class.Exception classes contain anything that a regular class contains. Thefollowing is an example of a user-defined exception class containing aconstructor, some variables, and methods.

1 public class ServerTimedOutException extends Exception {2 private int port;34 public ServerTimedOutException(String message, int port) {5 super(message);6 this.port = port;7 }89 public int getPort() {10 return port;11 }12 }

Note – Use the getMessage method, inherited from the Exception class,to get the reason the exception was made.

To throw an exception that you have created, use the following syntax:

throw new ServerTimedOutException("Could not connect", 80);

Always instantiate the exception on the same line on which you throw it,because the exception can carry line number information that is addedwhen the exception is created.

8-16 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 215: Sl275 Sg

Creating Your Own Exceptions

Throwing a User-Defined Exception

Consider a client-server program. In the client code, you try to connect tothe server and expect the server to respond within five seconds. If theserver does not respond, your code could throw an exception (such as auser-defined ServerTimedOutException) as follows:

1 public void connectMe(String serverName)2 throws ServerTimedOutException {3 boolean successful;4 int portToConnect = 80;56 successful = open(serverName, portToConnect);78 if ( ! successful ) {9 throw new ServerTimedOutException("Could not connect",10 portToConnect);11 }12 }

Error Handling Using Exception Classes and Assertions 8-17Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 216: Sl275 Sg

Creating Your Own Exceptions

Handling a User-Defined Exception

To catch your exception, use the try statement:

1 public void findServer() {2 try {3 connectMe(defaultServer);4 } catch (ServerTimedOutException e) {5 System.out.println("Server timed out, trying alternative");6 try {7 connectMe(alternativeServer);8 } catch (ServerTimedOutException e1) {9 System.out.println("Error: " + e1.getMessage() +10 " connecting to port " + e1.getPort());11 }12 }13 }

Note – You can nest the try and catch blocks, as shown in the previousexample.

You can also process an exception partially and then throw it; forexample:

try { connectMe(defaultServer);} catch (ServerTimedOutException e) { System.out.println(“Error caught and rethrown”); throw e;}

8-18 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 217: Sl275 Sg

Assertions

Assertions

The following two syntactic forms are permitted for assertion statements:

assert <boolean_expression> ;assert <boolean_expression> : <detail_expression> ;

In either case, if the Boolean expression evaluates to false, then anAssertionError is thrown. This error should not be caught, and theprogram should be terminated abnormally.

If the second form is used, then the second expression, which can be ofany type, is converted to a String and used to supplement the messagethat prints when the assertion is reported.

Note – The assertion mechanism can break code that was written for theJDK version 1.3 or older if it uses the word assert as a variable name orlabel. You can use the -source 1.3 option to tell the javac command tocompile the code for the JDK 1.3 version.

Recommended Uses of Assertions

Assertions can provide valuable documentation about the programmer’sassumptions and expectations. Because of this, assertions can be valuableduring maintenance when other programmers are working on the code.

Assertions should be used generally to verify the internal logic of a singlemethod or a small group of tightly coupled methods. Generally, assertionsshould not be used to verify that code is being used correctly, but ratherthat its own internal expectations are being met.

Examples of good uses of assertions are internal invariants, control flowinvariants, postconditions, and class invariants.

Internal Invariants

An internal invariant exists when you believe that a situation is always ornever the case and you code accordingly. For example, consider this code:

1 if (x > 0) {2 // do this3 } else {4 // do that5 }

Error Handling Using Exception Classes and Assertions 8-19Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 218: Sl275 Sg

Assertions

If you have made the assumption that x has the value 0, and is nevernegative, and yet x turns out to be negative, then the code does somethingunplanned and almost certainly the behavior will not be correct. Worse,because the code does not stop and report the problem, you will not findout about the problem until later when more damage has been done. Theoriginal source of the problem then becomes difficult to determine.

In this case, adding an assertion statement to the opening of the elseblock helps ensure the correctness of your assumption, and brings thebugs to light quickly if you are wrong, or if someone changes the code soas to invalidate the assumption during maintenance. With the assertion inplace, the code would look like the following:

1 if (x > 0) {2 // do this3 } else {4 assert (x == 0);5 // do that, unless x is negative6 }

Control Flow Invariants

Control flow invariants describe assumptions similar to the assumptionsof internal invariants, but they relate to the way the execution flows,rather than to the value or relationships of variables. For example, in aswitch statement, you might believe that you have enumerated everypossible value of the control variable, and that therefore a defaultstatement would never be executed. This should be verified by adding anassertion statement like the following:

1 char myGrade = employee.getGrade();2 switch (myGrade) {3 case ‘A’: // …4 break;5 case ‘B’: // …6 break;7 case ‘C’: // …8 break;9 default: assert false : “impossible grade: “ + myGrade;10 }

8-20 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 219: Sl275 Sg

Assertions

Postconditions and Class Invariants

Postconditions are assumptions about the value or relationships ofvariables at the completion of a method. A simple example of apostcondition test would be that after a pop method on a stack, the stackshould contain one less element than when the method was called, unlessthe stack was already empty. This might be coded like the following:

1 public Object pop() {2 int size = this.getElementCount();3 if (size == 0) {4 throw new IllegalStateException5 (“Attempt to pop from empty stack”);6 }78 Object result = /* code to retrieve the popped element */ ;910 // test the postcondition11 assert (this.getElementCount() == size - 1);1213 return result;14 }

If the pop method did not throw an exception if called on an empty stack,then it would be harder to express the assertion, because an original sizeof zero still results in a zero final size. The precondition test, that is thetest that determines if the method is being called on an empty stack, doesnot use an assertion. This is because it is not an error in the local logic ofthe method if such a situation occurs, rather it is an error in the way theobject is being used. Such tests on external behavior should, in general,not use assertions, but should use simple exceptions. This ensures that thetest is always made and cannot be disabled, as is the case with assertions.

A class invariant is something that can be tested at the end of everymethod call for the class. For the example of a stack class, an invariantcondition is one in which the element count is never negative.

Inappropriate Uses of Assertions

Do not use assertions to check the parameters of a public method. Instead,the method should test each parameter and throw an appropriateexception, such as IllegalArgumentException. The reason why youshould not use assertions for parameter checking is because the assertionmechanism can be turned off, but you still want to perform parameterchecking.

Error Handling Using Exception Classes and Assertions 8-21Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 220: Sl275 Sg

Assertions

Do not use methods in the assertion check that can cause side-effects,because the assertion checks can be turned off at runtime. If yourapplication depends upon these side-effects, then your application exhibitsdifferent behavior when the assertion checks are turned off.

Controlling Runtime Evaluation of Assertions

One of the major advantages of assertions over using exceptions is thatassertion checking can be disabled at runtime. If this is done, then there isno overhead involved in checking the assertions, and the code runs as fastas if the assertion test had never been present. This is better than usingconditional compilation for two reasons. First, it does not require a differentcompile phase for production. Second, if required, the assertions can be re-enabled in the field to determine if the assertions have become invalid dueto some unforeseen environmental effect.

By default, assertions are disabled. To turn assertions on, use either of theseforms:

java -enableassertions MyProgramjava -ea MyProgram

Assertions can be controlled on packages, package hierarchies, orindividual classes. For information on this, consult the documentation at:http://java.sun.com/javase/6/docs/technotes/guides/language/assert.html under the installation of your JDK software.

8-22 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 221: Sl275 Sg

Module 9

Declaringand UsingSpecializedClassTypes

Objectives

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

● Declare and use abstract methods and abstract classes

● Declare and use interfaces

● Declare and use nested classes

● Use enumerated types

9-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 222: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following references provide additionalinformation on the topics described in this module:

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

● Bates, Sierra. Head First Java, Second Edition. O’Reilly Media. 2005.

9-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 223: Sl275 Sg

Abstract Methods and Abstract Classes

Abstract Methods and Abstract Classes

This section introduces the concept of abstract methods and abstractclasses. Consider the inheritance hierarchy presented in Figure 9-1.

Figure 9-1 Vehicle Inheritance Hierarchy

Figure 9-1 presents a UML showing a Vehicle class that has two childclasses. The Vehicle class in this hierarchy represents a generic vehicleclass that represents the common elements of its subclasses. The Vehicleclass contains the following two methods:

● calcFuelEfficiency

● calcTripDistance

The problem in this scenario is that the implementations of each of thesemethods by the respective child classes is significantly different.Consequently, you cannot provide a meaningful common implementationin the parent Vehicle class. One option for these methods in the Vehicleclass is to provide a minimal implementation (concrete method) thatcompiles, as shown in the following code lines and allow the child classesto override the minimal implementation.

public double calcFuelEfficiency() { return -1; }public double calcTripDistance() { return -1; }

However, this is not a safe situation. For example, one of the child classesmight not override the parent class and instead inherit the place holderimplementation.

RiverBarge

Vehicle

+calcFuelEfficiency() : double

+calcTripDistance() : double

Truck

+calcFuelEfficiency() : double

+calcTripDistance() : double

+Truck(maxLoad : double)

«constructors»

«methods»+calcFuelEfficiency() : double

+calcTripDistance() : double

+RiverBarge(maxLoad : double)

«constructors»

«methods»

Declaring and Using Specialized Class Types 9-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 224: Sl275 Sg

Abstract Methods and Abstract Classes

To avoid this situation the Java technology specification permits thedeclaration of abstract methods and corresponding abstract classes.

● Abstract methods

An abstract method (as opposed to a concrete method) is a methodinterface declaration without the corresponding method body. Forexample,

public abstract double calcFuelEfficiency();public abstract double calcTripDistance();

Abstract methods contain the abstract keyword. The abstract methoddeclaration is terminated with a ‘;’. An abstract subclass of the classcontaining the abstract method can optionally provide a concreteoverriding method. A concrete subclass of the class containing theabstract method must provide a concrete overriding method.

● Abstract classes

An abstract class (as opposed to a concrete class) is a class that isdeclared abstract. It can contain zero or more abstract methods. Forexample,

public abstract class Vehicle {protected String registrationAuthority;public abstract double calcFuelEfficiency();public abstract double calcTripDistance();public getAuthority() {

return registrationAuthority;}

}

The following statements apply to an abstract class:

● An abstract class declaration must contain the abstractkeyword.

● An abstract class can contain abstract methods.

Any class declared as abstract is an abstract class even if it doesnot contain any abstract methods.

● An abstract class can contain concrete methods.

● An abstract class can contain attribute declarations.

9-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 225: Sl275 Sg

Abstract Methods and Abstract Classes

Abstract Class Example

The Java programming language enables a class designer to specify that asuperclass declares a method that does not supply an implementation.This is called an abstract method. The implementation of this method issupplied by the subclasses. Any class with one or more abstract methodsis called an abstract class (see Figure 9-2).

Figure 9-2 UML Model of the Abstract Vehicle Class

Figure 9-2 presents a UML model of the solution. Vehicle is an abstractclass with two public, abstract methods.

Note – UML uses the italic font to indicate abstract elements in a classdiagram. You can also indicate an abstract class with the {abstract}constraint flag in the name compartment.

The Java compiler prevents you from instantiating an abstract class. Forexample, the statement new Vehicle() is illegal.

Code 9-1 shows the declaration of the Vehicle class.

Code 9-1 Abstract Vehicle Class

1 public abstract class Vehicle {2 public abstract double calcFuelEfficiency();3 public abstract double calcTripDistance();4 }

RiverBarge

Vehicle

+calcFuelEfficiency() : double

+calcTripDistance() : double

Truck

+calcFuelEfficiency() : double

+calcTripDistance() : double

+Truck(maxLoad : double)

{abstract}

«constructors»

«methods»+calcFuelEfficiency() : double

+calcTripDistance() : double

+RiverBarge(maxLoad : double)

«constructors»

«methods»

Declaring and Using Specialized Class Types 9-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 226: Sl275 Sg

Abstract Methods and Abstract Classes

Code 9-2 shows the concrete Truck class.

Code 9-2 Concrete Truck Class

1 public class Truck extends Vehicle {2 public Truck(double maxLoad) {...}3 public double calcFuelEfficiency() {4 // calculate the fuel consumption of a truck5 }67 public double calcTripDistance() {8 // calculate the distance of this trip on highways9 }10 }

Code 9-3 shows the concrete RiverBarge class.

Code 9-3 Concrete RiverBarge Class

1 public class RiverBarge extends Vehicle {2 public RiverBarge(double maxLoad) {...}3 public double calcFuelEfficiency() {4 // calculate the fuel consumption of a river barge5 }67 public double calcTripDistance() {8 // calculate the distance of this trip along rivers9 }10 }

However, abstract classes can have data fields, concrete methods, andconstructors. For example, the Vehicle class might include load andmaxLoad fields and a constructor to initialize them. It is a good practice tomake these constructors protected rather than public, because it is onlymeaningful for these constructors to be invoked by the subclasses of theabstract class. Making these constructors protected makes it more obviousto the programmer that the constructor should not be called fromarbitrary classes.

9-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 227: Sl275 Sg

Interfaces

Interfaces

The following statements characterize an interface:

● An interface declares method interfaces without the correspondingmethod body.

● The methods of an interface are implemented by a class.

● Multiple classes can implement the same interface.

● A class can implement multiple interfaces.

● An interface (similar to a class) defines a Java technology type.

You can use an interface name as a type reference. You can castreferences to and from interface types, and you use the instanceofoperator to determine if an object’s class implements an interface.

The Flyer Example

Imagine a group of objects that all share the same ability: they fly. You canconstruct a public interface, called Flyer, that supports three operations:takeOff, land, and fly. (see Figure 9-3).

Figure 9-3 The Flyer Interface and Airplane Implementation

+takeOff()

+land()

+fly()

«interface»

Flyer

+takeOff()

+land()

+fly()

Airplane

Declaring and Using Specialized Class Types 9-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 228: Sl275 Sg

Interfaces

Code 9-4 shows the declaration of the Flyer interface.

Code 9-4 The Flyer Interface

1 public interface Flyer {2 public void takeOff();3 public void land();4 public void fly();5 }

Code 9-5 shows the Airplane class’s implementation of the Flyerinterface.

Code 9-5 The Flyer Interface Implementation

1 public class Airplane implements Flyer {2 public void takeOff() {3 // accelerate until lift-off4 // raise landing gear5 }6 public void land() {7 // lower landing gear8 // decelerate and lower flaps until touch-down9 // apply brakes10 }11 public void fly() {12 // keep those engines running13 }14 }

9-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 229: Sl275 Sg

Interfaces

There can be multiple classes that implement the Flyer interface, asshown in Figure 9-4. An airplane can fly, a bird can also fly, Superman canfly, and so on.

Figure 9-4 Multiple Implementations of the Flyer Interface

An Airplane is a Vehicle, and it can fly. A Bird is an Animal, and it canfly. These examples show that a class can inherit from one class but alsoimplement some other interface.

+takeOff()

+land()

+fly()

«interface»

Flyer

+takeOff()

+land()

+fly()

Airplane

+takeOff()

+land()

+fly()

Bird

+takeOff()

+land()

+fly()

Superman

+buildNest()

+layEggs()

+leapBuilding()

+stopBullet()

Declaring and Using Specialized Class Types 9-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 230: Sl275 Sg

Interfaces

This sounds like multiple inheritance, but it is not quite that. The dangerof multiple inheritance is that a class could inherit two distinctimplementations of the same method. This is not possible with interfacesbecause an interface method declaration supplies no implementation, asshown in Figure 9-5. Interfaces allow multiple type inheritance with singleimplementation inheritance.

Figure 9-5 A Mixture of Inheritance and Implementation

Code 9-6 describes the Bird class:

Code 9-6 The Bird Class Declaration

public class Bird extends Animal implements Flyer {public void takeOff() { /* take-off implementation */ }public void land() { /* landing implementation */ }public void fly() { /* fly implementation */ }public void buildNest(){ /* nest building behavior */ }public void layEggs() { /* egg laying behavior */ }public void eat() { /* override eating behavior */ }

}

The extends clause must come before the implements clause. The Birdclass can supply its own methods (buildNest and layEggs), as well asoverride the Animal class methods (eat).

Vehicle

Animal

+eat()

Kryptonian

+takeOff()

+land()

+fly()

«interface»

Flyer

+takeOff()

+land()

+fly()

Airplane

+takeOff()

+land()

+fly()

Bird

+takeOff()

+land()

+fly()

Superman

+buildNest()

+layEggs()

+leapBuilding()

+stopBullet()

+eat() +eat()

9-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 231: Sl275 Sg

Interfaces

Suppose that you are constructing an aircraft control software system. Itmust grant permission to land and take off for flying objects of all types.This is shown in Figure 9-6.

Figure 9-6 Class Hierarchy for the Airport Example

Code 9-7 shows a possible declaration for the Airport class:

Code 9-7 The Airport Class Declaration

1 public class Airport {2 public static void main(String[] args) {3 Airport metropolisAirport = new Airport();4 Helicopter copter = new Helicopter();5 SeaPlane sPlane = new SeaPlane();67 metropolisAirport.givePermissionToLand(copter);8 metropolisAirport.givePermissionToLand(sPlane);9 }1011 private void givePermissionToLand(Flyer f) {12 f.land();13 }14 }

Vehicle

Animal

+eat()

Kryptonian

+takeOff()

+land()

+fly()

«interface»

Flyer

+takeOff()

+land()

+fly()

Airplane

+takeOff()

+land()

+fly()

Bird

+takeOff()

+land()

+fly()

Superman

+buildNest()

+layEggs()

+leapBuilding()

+stopBullet()

+eat() +eat()

HelicopterSeaPlane

Declaring and Using Specialized Class Types 9-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 232: Sl275 Sg

Interfaces

Multiple Interface Example

A class can implement more than one interface. Not only can theSeaPlane fly, but it can also sail. The SeaPlane class extends theAirplane class, so it inherits that implementation of the Flyer interface.The SeaPlane class also implements the Sailer interface. This is shownin Figure 9-7.

Figure 9-7 An Example of Multiple Implementations

Now write the Harbor class to give docking permission:

1 public class Harbor {2 public static void main(String[] args) {3 Harbor bostonHarbor = new Harbor();4 RiverBarge barge = new RiverBarge();5 SeaPlane sPlane = new SeaPlane();67 bostonHarbor.givePermissionToDock(barge);8 bostonHarbor.givePermissionToDock(sPlane);9 }10 private void givePermissionToDock(Sailer s) {11 s.dock();12 }13 }

The seaplane can take off from Metropolis airport and dock in Bostonharbor.

+takeOff()

+land()

+fly()

«interface»

Flyer

+takeOff()

+land()

+fly()

Airplane

+dock()

+cruise()

«interface»

Sailer

SeaPlane

+dock()

+cruise()

Helicopter

Vehicle

RiverBarge

+dock()

+cruise()

9-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 233: Sl275 Sg

Interfaces

Interface Declaration and Usage Rules

The public interface of a class is a contract between the client code and theclass that provides the service.

● Concrete classes implement each method.

● Abstract classes can defer the implementation by declaring themethod to be abstract.

● Java interfaces declare only the contract and no implementation.

Interfaces cannot be instantiated: they can be implemented only by classes(or extended by other interfaces). A concrete class implements an interfaceby defining all methods declared by the interface. Many classes canimplement the same interface. These classes do not need to share the sameclass hierarchy. Also, importantly, a class can implement more than oneinterface. The ability for a class to implement multiple interfaces givesJava technology much of the power that multiple inheritance provides inother languages, but without the complexity that multiple inheritance canintroduce.

Note – All methods declared in an interface are public and abstract,even if these modifiers are not explicitly mentioned in the code. Similarly,all attributes are public, static, and final; in other words, you canonly declare constant attributes.

An interface can contain only the following:

● Constants (field declarations in an interface body are implicitlypublic, static, and final.)

● Method interfaces (but no method bodies)

Declaring and Using Specialized Class Types 9-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 234: Sl275 Sg

Nested Classes

Nested Classes

Java technology allows you to declare a class within another class.Theseare called nested classes. Code 9-8 shows an example of a nested class.

Code 9-8 Inner Class Example

1 public class StackOfInts {2 private int[] stack;3 private int next = 0; // index of last item in stack + 145 public StackOfInts(int size) {//...}6 public void push(int on) {// ... }7 public int pop(){ // ...}89 private class StepThrough { // ... }10 private int i;11 public increment() { // ... }12 public int current() { // ... }13 public boolean isLast(){ // ...}14 }1516 public StepThrough stepThrough() { // ... }17 public static void main(String[] args) { // ... }18 }

A nested class has complete access to all the fields and methods (andother nested classes) of the outer class.

Nested classes often are used to implement helper classes, that is, codethat is tightly related to and highly dependent on the purpose of the outerclass. There are several benefits to using nested classes, such as:

● New levels of encapsulation – Encapsulation refers to keepingrelevant data and methods together in a class. Nesting classessupport encapsulation by declaring the tight coupling of the nestedclass declaration within the environment of the outer class

● Improved readability and maintainability of your code – Declaringclasses near to where they are used can make the relationshipbetween the declaration and usage clearer. Also, because the nestedclass shares the outer class’s namespace, your code can be moreconcise because object references require few qualifiers.

9-14 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 235: Sl275 Sg

Nested Classes

● More levels for organizing a class hierarchy – Nested classes providea way to organize helper classes in a more detailed way than thePackage structure. Deployment and distribution of related ordependent classes is simpler because those classes can be bundledtogether in the outer class.

Note – Nested classes are implemented at the time of compilation. Whenit processes nested class code, the Java Compiler outputs Java code for thenested classes as top-level classes with automatically generated names,such as StackOfInts$StepThrough.class. The compiler also createsextra Java code (for example, special getter and setter methods) in theouter class that gives the inner class access to private members of theouter class. The new extra Java code is compiled to byte code along withthe rest of the Java code in your program. During runtime there is nothingspecial about nested classes with regard to the JVM implementation.

Examining the Nested Class Syntax

Code 9-9 shows the basic syntax for nested classes.

Code 9-9 Syntax for Nested Classes

1 [public] class OuterClass {2 ...3 [public | protected | private | static]class NestedClass {4 ...5 }6 }

A nested class can be declared private, public, protected, or packageprivate just like any other member of the class. Remember that top-levelclasses can be declared only public or default (package private).

Unlike a top-level class, a nested class can be declared static. Nestedclasses can be divided into two categories:

● Non-static nested classes, which are called inner classes.

● Static nested classes

Declaring and Using Specialized Class Types 9-15Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 236: Sl275 Sg

Nested Classes

Inner Classes

As with instance variables, at runtime an inner class is directly tied to anobject instance of its outer class. The inner class has direct access to thatobject's methods and fields, as well as the methods and fields it inheritsfrom its superclass. But, because an inner class is loaded only within thecontext of an instance of its outer class, it cannot define any staticmembers.

Code 9-10 shows a simplified version of the syntax for the declaration ofan inner class:

Code 9-10 Syntax for Inner Class

class OuterClass {...class InnerClass {

...}...

}

Objects that are instances of an inner class are considered to exist insidean instance of the outer class. Therefore, these objects have direct access tothe methods and fields of their enclosing instance:

To instantiate an inner class from somewhere other than the outer class,you must first instantiate the outer class. Then, create the inner classobject instance within the outer object with the following syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Additionally, there are two special kinds of inner classes: local classes andanonymous inner classes.

9-16 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 237: Sl275 Sg

Nested Classes

Local Inner Classes

A Local Inner Class (sometimes called local class) is a class declared insidea block of code in a method body. Just like a local data field, a local innerclass is visible only within the block of code in which it is defined.However, it has runtime access to final arguments and final local variablesin the enclosing method. Code 9-11 shows an example of a local innerclass.

Code 9-11 Local Inner Class

class OuterClass {......void aMethod(){

...

...class InnerClass {

...}...InnerClass x = new InnerClass();// do something with instance variable x...

}......

}

Declaring and Using Specialized Class Types 9-17Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 238: Sl275 Sg

Nested Classes

Anonymous Inner Classes

An anonymous inner class (also called an anonymous class) is an innerclass with no declared name. However, because there is no class name, thesyntax for declaring an anonymous inner class is significantly different:

new existingTypeName ( [ argumentList ] ) {// class code here

}

Instead of using the more familiar extends syntax, the declaration of ananonymous inner class looks like a call to one of its superclass’sconstructors, followed by a block of code that defines the class’s state andbehavior. For example if the superclass is Object, then the parameter listmust be empty, because Object’s constructor method takes no parameters.Code 9-12 shows an example of an anonymous inner class, that extendsthe Airplane class declared in Code 9-5 on page 9-8.

Code 9-12 Anonymous Inner Class Example

1 metropolisAirport.givePermissionToLand(new AirPlane() {2 public void land() {3 //do something that only UFOs can do...4 } //close land method5 } //close anonymous inner class6 ) //close argument to givePermissionToLand method7 ; //end statement started at line 1

Note – You might also have coded new Flier() on line 1. This launchesan anonymous inner class that implements the Flier interface. In thiscase, you must implement all of the methods of the Flier interface.

Anonymous inner classes are most useful under the followingcircumstances:

● When the declaration and usage of the class are adjacent

● When the class code is short

An anonymous class is:

● Always an inner class and implicitly final

● Never abstract and never static

9-18 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 239: Sl275 Sg

Nested Classes

Static Nested Classes

A static nested class is a static class defined in the namespace of a top-level class (or within the namespace of another static nested class). Staticnested class cannot refer directly to instance variables or methods definedin its enclosing class; this restriction is exactly the same as the access rulesfor static class methods. Nested classes can access only instance variablesor methods through a reference to an object instance. Code 9-13 shows asimplified example of a static nested class.

Code 9-13 Static Nested Class

public class Outer {...public static class StaticNested {

...}...

}

You can access a static nested class using a reference to the enclosing class:

Outer.StaticNested

For example, to create an instance of the static nested class, use thefollowing syntax:

Outer.StaticNested nestedObject = new Outer.StaticNested();

Inner Interfaces, EnumeratedTypes, and Annotations

Interfaces, enumerated types, and annotations types can also be declaredinternally. Because these types are implicitly static in the Java language,they have usage restrictions similar to those of static nested classes.

You can also use interfaces to create anonymous inner classes:

new interfaceName () { interfaceSpecification }

Declaring and Using Specialized Class Types 9-19Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 240: Sl275 Sg

Enumerated Types

Enumerated Types

In version 5.0 of the Java programming language, a new keyword, enum,was introduced to provide a reference type for a finite, type-safe, set ofvalues. Each of the values is individually listed, that is, enumerated, in thebody of the declaration.

The body of an enum type is a comma-separated list of enum constants.Enum constants are similar to static final fields, but the compiler enforcestheir use as references to a unique object type.

The following is an example of a simple enumerated type declaration:

public enum TrafficSignal { STOP, CAUTION, GO}

You can think of the TrafficSignal type as a class with a finite set ofunique values. Each value is given the symbolic name listed in the typedefinition. For example, TrafficSignal.STOP is of typeTrafficSignal. The names of the enum constants are typicallycapitalized, like other constant names in Java technology. Given theexample above, a variable of type TrafficSignal can be assigned onlythe following values or an error is generated.

● TrafficSignal.STOP

● TrafficSignal.CAUTION

● TrafficSignal.GO

● or null.

Switch Statements

Switch statements work well with enumerated types; however, there areseveral restrictions. For example, the enumerated class name must notprefix the enum constant in the case labels. In the following code sample,notice that none of the case labels include TrafficSignal.

public class Test {public enum TrafficSignal {STOP, CAUTION, GO};

public static void main(String [] args) {TrafficSignal theLight= TrafficSignal.GO;switch (theLight) {

9-20 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 241: Sl275 Sg

Enumerated Types

case STOP:System.out.print("red");break;

case CAUTION:System.out.print("yellow");break;

case GO:System.out.print("green");break;

}}

}

Note – Resulting output: green

For Loops

Enumerated types also work well with enhanced for loops. Below isprogram with a nested enum declaration that uses an enhanced for loopto iterate over the constants in the enum. The code sample below

public class Test{public enum TrafficSignal {STOP, CAUTION, GO};

public static void main(String[] args) {for( TrafficSignal t : TrafficSignal.values() ) {

System.out.println(t);}

}}

Note – values is a static method that returns an array containing all theconstants of the TrafficSignal enum class.

Note – Resulting output:STOPCAUTIONGO

Declaring and Using Specialized Class Types 9-21Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 242: Sl275 Sg

Enumerated Types

Enumerated Types With Fields, Methods, andConstructors

A declaration of an enumerated type can contain data fields, and methoddefinitions just like a class declaration. This class body is treated as ananonymous inner class declaration; the outer class is the enumdeclaration.

Constructors in the enum declaration are not normal constructors at all,because instantiation of an enum is prohibited (declaring a public enumconstructor actually causes a compilation error). Each enum constant canhave a parameter list. When the enum is initialized, the constructor iscalled for each constant to map the parameters to enum fields, as specifiedby the constructor body. Constructors can be overloaded to work withdifferent parameter lists.

The following is a program that declares an enumerated type,TrafficSignal, with three possible values (for example, STOP). Each ofthe values has an associated string representing its light color (forexample, red). The constructor automatically maps the supplied color (t)to the enum field (light) for each of the three values.

public class Test {public enum TrafficSignal {

STOP("red"), CAUTION("yellow"), GO("green");

private final String light;

private TrafficSignal(String t) { light = t; }

public String format(String message) {return message + " " + light;

}}

public static void main(String[] args) {System.out.println(TrafficSignal.GO.format("The light is"));System.out.println(TrafficSignal.STOP.format("The light is"));

}}

Note – Resulting output:The light is greenThe light is red

9-22 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 243: Sl275 Sg

Module 10

UsingGenericsand the CollectionsFramework

Objectives

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

● Describe the Collections

● Describe the general purpose implementations of the core interfacesin the Collections framework

● Examine the Map interface

● Examine the legacy collection classes

● Create natural and custom ordering by implementing theComparable and Comparator interfaces

● Use generic collections

● Examine the use of type parameters in generic classes

● Refactor existing non-generic code

● Write a program to iterate over a collection

● Examine the enhanced for loop

10-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 244: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following references provide additionalinformation on the topics described in this module:

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

10-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 245: Sl275 Sg

The Collections API

The Collections API

A collection is a single object managing a group of objects. The objects inthe collection are called elements. Typically, collections deal with manytypes of objects, all of which are of a particular kind (that is, they alldescend from a common parent type).

The Collections API contains interfaces that group objects as one of thefollowing:

● Collection – A group of objects known as elements;implementations determine whether there is specific ordering andwhether duplicates are permitted

● Set – An unordered collection; no duplicates are permitted

● List – An ordered collection; duplicates are permitted

Before the release of the Java SE 5.0 platform, collections maintainedreferences to objects of type Object. This enables any object to be storedin the collection. It also necessitates the use of correct casting before youcan use the object, after retrieving it from the collection. However, withthe Java SE 5.0 platform and onwards, you can use generic collectionfeatures to specify the object type to be stored in a collection. This avoidsthe need to cast the object on retrieval. Generic collections are discussed inmore detail in ‘‘Generics’’ on page 10-16.

Using Generics and the Collections Framework 10-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 246: Sl275 Sg

The Collections API

Figure 10-1 shows a UML diagram of the primary interfaces andimplementation classes of the Collections API.

Figure 10-1 The Collection Interface and Class Hierarchy

The HashSet is one example of a class that supplies an implementation ofthe Set interface. The SortedSet interface extends the Set interface. Theclasses that implement SortedSet impose total ordering on its elements.TreeSet implements the SortedSet interface.The ArrayList andLinkedList classes supply an implementation of the List interface.

Note – This discussion of the Collections API is a simplification of thecomplete API (which includes many more methods, more interfaces, andseveral intermediate abstract classes). For more information, readIntroduction to the Collections Framework at the following URL:http://developer.java.sun.com/developer/onlineTraining/collections/

Collection<<interface>>

Set<<interface>>

List<<interface>>

HashSet

ArrayList LinkedList

+add

+size+remove

+isEmpty+contains+iterator

+add

+get+remove

+set+indexOf+listIterator

TreeSet

<<interface >>

SortedSet

10-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 247: Sl275 Sg

Collection Implementations

Collection Implementations

There are several general purpose implementations of the core interfaces(Set, List, Map and Deque) in the Collections framework. Table 10-1shows some of the concrete implementations of these interfaces.

The following subsections show examples of the use of HashSet andArrayList.

A SetExample

In the following example shown in Code 10-1, the program declares avariable (set) of type Set that is initialized to a new HashSet object. Itthen adds a few elements and prints the set to standard output. Lines 10and 11 in Code 10-1 attempt to add duplicate values to set. Becauseduplicate values cannot be added to a Set, the add methods return false.

Code 10-1 SetExample Program

1 import java.util.*;2 public class SetExample {3 public static void main(String[] args) {4 Set set = new HashSet();5 set.add("one");6 set.add("second");7 set.add("3rd");8 set.add(new Integer(4));9 set.add(new Float(5.0F));10 set.add("second"); // duplicate, not added11 set.add(new Integer(4)); // duplicate, not added12 System.out.println(set);13 }14 }

Table 10-1 General Purpose Collection Implementations

HashTable

ResizableArray

BalancedTree Linked List Hash Table +

Linked List

Set HashSet TreeSet LinkedHashSet

List ArrayList LinkedList

Deque ArrayDeque LinkedList

Map HashMap TreeMap LinkedHashMap

Using Generics and the Collections Framework 10-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 248: Sl275 Sg

Collection Implementations

The output generated from this program might be:

[one, second, 5.0, 3rd, 4]

You should note that the order of the elements is not the same as the orderin which they were added.

Note – In Line 13, the program prints the set object to standard output.This works because the HashSet class overrides the inherited toStringmethod and creates a comma-separated sequence of the items delimitedby the open and close braces.

A ListExample

In the following example shown in Code 10-2, the program declares avariable (list) of type List that is assigned to a new ArrayList object. Itthen adds a few elements and prints the list to standard output. Becauselists allow duplicates, the add methods in lines 10 and 11 in Code 10-2return true.

Code 10-2 ListExample Program

1 import java.util.*;2 public class ListExample {3 public static void main(String[] args) {4 List list = new ArrayList();5 list.add("one");6 list.add("second");7 list.add("3rd");8 list.add(new Integer(4));9 list.add(new Float(5.0F));10 list.add("second"); // duplicate, is added11 list.add(new Integer(4)); // duplicate, is added12 System.out.println(list);13 }14 }

The output generated from this program is:

[one, second, 3rd, 4, 5.0, second, 4]

The order of the elements is the order in which they were added.

10-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 249: Sl275 Sg

Collection Implementations

Note – The Collections API contains many useful, concreteimplementations of the Collection, Set, and List interfaces. You areencouraged to check the API documentation and become familiar withthe implementations. Some even implement hybrid behavior, such as theLinkedHashMap, which uses hashing to implement fast searches, and alsomaintains a doubly linked list internally so that it can return objects froman iterator in a meaningful order.

Using Generics and the Collections Framework 10-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 250: Sl275 Sg

The Map Interface

The Map Interface

Maps are sometimes called associative arrays. A Map object describesmappings from keys to values. By definition, a Map object does not allowduplicate or null keys and a key can map to one value at most.

The Map interface provides three methods that allow map contents to beviewed as collections

● entrySet – Returns a Set that contains all the key value pairs.

● keySet – Returns a Set of all the keys in the map.

● values – Returns a Collection containing all the values containedin the map.

Figure 10-2 shows the API for the Map interface, its sub interfaces and afew of the more well known implementing classes.

Figure 10-2 The Map Interlace API

<<interface>>Map

Operations

<<interface>>SortedMap

TreeMap

Hashtable

Properties

HashMap

LinkedHashMap

+ get+ values+ entrySet+ keySet

10-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 251: Sl275 Sg

The Map Interface

The Map interface does not extend the Collection interface because itrepresents mappings and not a collection of objects. The SortedMapinterface extends the Map interface. Some of the classes that implement theMap interface are HashMap, TreeMap, IdentityHashMap, andWeakHashMap. The order presented by the iterators of these map collectionimplementations is specific to each iterator.

A Map example

In the example shown in Code 10-3, the program declares a variable mapof type Map, and assigns it to a new HashMap object. It then adds a fewelements to the map by using the put operation. To prove that duplicatekeys are not allowed in a map, the program attempts to add a new valueusing an existing key. This results in the previously added value for thekey being replaced by the new value. The program later uses thecollection view operations keySet, values, and entrySet for retrievingthe contents of the map.

Code 10-3 MapExample Program

1 import java.util.*;2 public class MapExample {3 public static void main(String args[]) {4 Map map = new HashMap();5 map.put("one","1st");6 map.put("second", new Integer(2));7 map.put("third","3rd");8 // Overwrites the previous assignment9 map.put("third","III");10 // Returns set view of keys11 Set set1 = map.keySet();12 // Returns Collection view of values13 Collection collection = map.values();14 // Returns set view of key value mappings15 Set set2 = map.entrySet();16 System.out.println(set1 + "\n" + collection + “\n” + set2);17 }18 }

The generated output from the program is:

[one, third, second][1st, III, 2][one=1st, three=III, second=2]

Using Generics and the Collections Framework 10-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 252: Sl275 Sg

Legacy Collection Classes

Legacy Collection Classes

The collection classes in the JDK version 1.0 and JDK version 1.1 still existin the current JDK with the same interface, but they have been retooled tointeract with the new Collections API.

● The Vector class implements the List interface.

● The Stack class is an extension of Vector that adds the typical stackoperations: push, pop, and peek.

● The Hashtable is an implementation of Map.

● The Properties class is an extension of Hashtable that only usesStrings for keys and values.

● Each of these collections has an elements method that returns anEnumeration object. The Enumeration is an interface similar to, butincompatible with, the Iterator interface. For example, hasNext isreplaced by hasMoreElements in the Enumeration interface.

10-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 253: Sl275 Sg

Ordering Collections

Ordering Collections

The Comparable and Comparator interfaces are useful for orderingcollections. The Comparable interface imparts natural ordering to classesthat implement it. The Comparator interface is used to specify orderrelation. It can also be used to override natural ordering. These interfacesare useful for sorting the elements in a collection.

The Comparable Interface

The Comparable interface is a member of the java.lang package. Whenyou declare a class, the JVM implementation has no means of determiningthe order you intend for objects of that class. You can, by implementingthe Comparable interface, provide order to the objects of any class. Youcan sort collections that contain objects of classes that implement theComparable interface.

Examples of some Java classes that implement the Comparable interface,are Byte, Long, String, Date, and Float. Of these, the numeric classesuse a numeric implementation; the String class uses an alphabeticimplementation and the Date class uses a chronological implementation.Passing an ArrayList containing String type elements to the static sortmethod of the Collections class returns a list sorted in alphabeticalorder. A list containing Date type elements sorts in chronological orderand a list containing Integer type elements sorts in numerical order.

To write custom Comparable types, you need to implement thecompareTo method of the Comparable interface. Code 10-4 shows how toimplement the Comparable interface. The Student class implements theComparable interface so that the objects of this class can be compared toeach other.

Code 10-4 Example Comparable Interface Implementation

1 import java.util.*;2 class Student implements Comparable {3 String firstName, lastName;4 int studentID=0;5 double GPA=0.0;6 public Student(String firstName, String lastName, int StudentID,7 double GPA) {8 if (firstName == null || lastName == null || StudentID == 09 || GPA == 0.0) {throw new IllegalArgumentException();}10 this.firstName = firstName;

Using Generics and the Collections Framework 10-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 254: Sl275 Sg

Ordering Collections

11 this.lastName = lastName;12 this.studentID = studentID;13 this.GPA = GPA;14 }15 public String firstName() { return firstName; }16 public String lastName() { return lastName; }17 public int studentID() { return studentID; }18 public double GPA() { return GPA; }19 // Implement compareTo method.20 public int compareTo(Object o) {21 double f = GPA-((Student)o).GPA;22 if (f == 0.0)23 return 0; // 0 signifies equals24 else if (f<0.0)25 return -1; // negative value signifies less than or before26 else27 return 1; // positive value signifies more than or after28 }29 }

The StudentList program in Code 10-5 tests the Comparable interfaceimplementation created in the Code 10-4 on page 10-11. The StudentListprogram creates four Student objects and prints them. Because theStudent objects are added to the TreeSet, which is a sorted set, theobjects are sorted.

Code 10-5 StudentList Program

1 import java.util.*;2 public class StudentList {3 public static void main(String[] args) {4 TreeSet studentSet = new TreeSet();5 studentSet.add(new Student("Mike", "Hauffmamn",101,4.0));6 studentSet.add(new Student("John", "Lynn",102,2.8 ));7 studentSet.add(new Student("Jim", "Max",103, 3.6));8 studentSet.add(new Student("Kelly", "Grant",104,2.3));9 Object[] studentArray = studentSet.toArray();10 Student s;11 for(Object obj : studentArray){12 s = (Student) obj;13 System.out.println("Name = %s %s ID = %d GPA =%f",14 s.firstName(), s.lastName(), s.studentID(), s.GPA());15 = "+s.studentID+" GPA = "+s.GPA);16 }17 }18 }

10-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 255: Sl275 Sg

Ordering Collections

The output generated by the StudentList program is

Name = Kelly Grant ID = 0 GPA = 2.3Name = John Lynn ID = 0 GPA = 2.8Name = Jim Max ID = 0 GPA = 3.6Name = Mike Hauffmamn ID = 0 GPA = 4.0

Observe that the students are compared based on the GPA. This happensbecause while ordering the elements in the TreeSet collection, theTreeSet looks if the objects have their natural order, and in this case, usesthe compareTo method to compare the objects.

Some collections, such as TreeSet, are sorted. The TreeSetimplementation needs to know how to order elements. If the elementshave a natural order, TreeSet uses the natural order. Otherwise, you haveto assist it. For example, the TreeSet class has the following constructorthat takes Comparator as a parameter.

TreeSet(Comparator comparator)

This constructor creates a new, empty tree set, sorted according to thespecified Comparator. The following section provides a detaileddiscussion of the use of the Comparator interface.

The Comparator Interface

The Comparator interface provides greater flexibility with ordering. Forexample, if you consider the Student class described previously, thesorting of students was restricted to sorting on GPAs. It was not possibleto sort the student based on first name or some other criteria. This sectiondemonstrates how sorting flexibility can be enhanced using theComparator interface.

The Comparator interface is a member of the java.util package. It isused to compare objects in the custom order instead of the natural order.For example, it can be used to sort objects in an order other than thenatural order. It is also used to sort objects that do not implement theComparable interface.

To write a custom Comparator, you need to provide an implementationfor the compare method in the interface:

int compare(Object o1, Object o2)

Using Generics and the Collections Framework 10-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 256: Sl275 Sg

Ordering Collections

This method compares two arguments for order and returns a negativeinteger if the first argument is less than second, returns zero if both areequal, and returns a positive integer if the first argument is greater thanthe second. Code 10-6 shows the version of the Student class.

Code 10-6 Student Class

1 class Student {2 String firstName, lastName;3 int studentID=0;4 double GPA=0.0;5 public Student(String firstName, String lastName,6 int StudentID, double GPA) {7 if (firstName == null || lastName == null || StudentID == 0 ||8 GPA == 0.0) throw new IllegalArgumentException();9 this.firstName = firstName;10 this.lastName = lastName;11 this.studentID = studentID;12 this.GPA = GPA;13 }14 public String firstName() { return firstName; }15 public String lastName() { return lastName; }16 public int studentID() { return studentID; }17 public double GPA() { return GPA; }18 }

Several classes can be created to compare the students based onfirstName, or lastName, or studentID, or GPA. The class NameComp inCode 10-7 implements the Comparator interface to compare studentsbased on firstName.

Code 10-7 Example Comparator Interface Implementation

1 import java.util.*;2 public class NameComp implements Comparator {3 public int compare(Object o1, Object o2) {4 return5 (((Student)o1).firstName.compareTo(((Student)o2).firstName));6 }7 }

The class GradeComp in Code 10-8 on page 10-15 implements theComparator interface to compare students based on their GPAs.

10-14 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 257: Sl275 Sg

Ordering Collections

Code 10-8 Another Example Comparator Interface Implementation.

1 import java.util.*;2 public class GradeComp implements Comparator {3 public int compare(Object o1, Object o2) {4 if (((Student)o1).GPA == ((Student)o2).GPA)5 return 0;6 else if (((Student)o1).GPA < ((Student)o2).GPA)7 return -1;8 else9 return 1;10 }11 }

The ComparatorTest class in Code 10-9 tests the NameComp comparator.In line 4 notice that the name comparator is passed as a parameter toTreeSet

Code 10-9 ComparatorTest Program.

1 import java.util.*;2 public class ComparatorTest {3 public static void main(String[] args) {4 Comparator c = new NameComp();5 TreeSet studentSet = new TreeSet(c);6 studentSet.add(new Student("Mike", "Hauffmamn",101,4.0));7 studentSet.add(new Student("John", "Lynn",102,2.8 ));8 studentSet.add(new Student("Jim", "Max",103, 3.6));9 studentSet.add(new Student("Kelly", "Grant",104,2.3));10 Object[] studentArray = studentSet.toArray();11 Student s;12 for(Object obj : studentArray){13 s = (Student) obj;14 System.out.println("Name = %s %s ID = %d GPA =%f",15 s.firstName(), s.lastName(), s.studentID(), s.GPA());16 = "+s.studentID+" GPA = "+s.GPA);17 }18 }19 }

The output generated by this program is:

Name = Jim Max ID = 0 GPA = 3.6Name = John Lynn ID = 0 GPA = 2.8Name = Kelly Grant ID = 0 GPA = 2.3Name = Mike Hauffmamn ID = 0 GPA = 4.0

If Code 10-9 was modified to use a GradeComp object, students would besorted based on the GPA.

Using Generics and the Collections Framework 10-15Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 258: Sl275 Sg

Generics

Generics

Collection classes use the Object type to permit different input andreturn types. You need to cast down explicitly to retrieve the object youneed. This is not type-safe.

Although the existing collections framework does support homogeneouscollections (that is collections of one type of object, for example Dateobjects), there was no mechanism to prevent other object types from beinginserted into the collection. Also a retrieval almost always required a cast.

The solution for this problem is to make use of generics functionality. Thiswas introduced in the Java SE 5.0 platform. It provides information for thecompiler about the type of collection used. Hence, type checking isresolved automatically at run time. This eliminates the explicit casting ofthe data types to be used in the collection. With the addition ofautoboxing of primitive types, you can use generics to write simpler andmore understandable code.

Before generics, code might look like the following in Code 10-10:

Code 10-10 Using Non-generic Collections

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

In Code 10-10, you need an Integer wrapper class for typecasting whileretrieving the integer value from the list. At runtime, the program needsthe type checking for the list.

With the application of generics, the ArrayList should be declared asArrayList<Integer>, to inform the compiler of the type of collection tobe used. When retrieving the value, there is no need for an Integerwrapper class. The use of generics for the original code in Code 10-10 isshown in Code 10-11:

Code 10-11 Using Generic Collections

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

10-16 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 259: Sl275 Sg

Generics

The autoboxing facility fits well with the Generics API. Using autoboxing,the code example could be written as shown in Code 10-12.

Code 10-12 Using Autoboxing With Collections

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

Code 10-12 uses the generic declaration and instantiation to declare andinstantiate an ArrayList instance of Integer objects. Consequently, theaddition of a non-Integer type to the array list generates a compilationerror.

Note – Generics are enabled by default since the Java SE 5.0 platform. Youcan disable generics by using the -source 1.4 option on the javaccommand.

Generic SetExample

In the following example, the program declares a variable (set) of typeSet<String> and assigns it to a new HashSet<String> object. It thenadds a few String elements and prints the set to standard output. Line 8causes a compilation error (because an Integer is not a String). Code 10-13shows the Set implementation using generics. This can be compared tothe non-generic Set implementation shown in Code 10-1 on page 10-5.

Code 10-13 Generic Set Example

1 import java.util.*;2 public class GenSetExample {3 public static void main(String[] args) {4 Set<String> set = new HashSet<String>();5 set.add("one");6 set.add("second");7 set.add("3rd");8 // This line generates compile error9 set.add(new Integer(4));10 // Duplicate, not added11 set.add("second");12 System.out.println(set);13 }14 }

Using Generics and the Collections Framework 10-17Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 260: Sl275 Sg

Generics

Generic Map Example

The MapAcctRepository class in Code 10-14 shows a more practical wayto use generic collections. The program creates a repository of accounts. Itdeclares a variable (accounts) of type HashMap<String, Account>. Itdefines two methods put() and get() to add the elements to the maprepository and to retrieve the elements from the map repositoryrespectively.

Code 10-14 Generic Map Implementation

1 public class MapAcctRepository {2 HashMap<String, Account> accounts;34 public MapAcctRepository() {5 accounts = new HashMap<String, Account> ();6 }78 public Account get(String locator) {9 Account acct = accounts.get(locator);10 return acct;11 }1213 public void put(Account account) {14 String locator = account.getCustomer();15 accounts.put(locator, account);16 }17 }

10-18 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 261: Sl275 Sg

Generics: Examining Type Parameters

Generics: Examining Type Parameters

This section examines the use of type parameters in (the class, constructorand method declarations of) generic classes. Table 10-2 compares the non-generic version (pre-Java SE 5.0 platform) and the generic version (sincethe Java SE 5.0 platform) of the ArrayList class.

The major difference is the introduction of the type parameter E. In thefollowing ArrayList declaration and instantiation, the String typesubstitutes the parametric type variable E.

ArrayList <String> a3 = new ArrayList <String> (10);

In the following ArrayList declaration and instantiation, the Date typesubstitutes the parametric type variable E.

ArrayList <Date> a3 = new ArrayList <Date> (10);

Table 10-2 Comparing the non Generic and Generic ArrayList Classes

Category Non Generic Class Generic Class

Classdeclaration

public class ArrayListextends AbstractListimplements List

public class ArrayList<E>extends AbstractList<E>implements List <E>

Constructordeclaration

public ArrayList(int capacity)

public ArrayList(int capacity)

Methoddeclaration

public void add(Object o)

public Object get(intindex)

public void add(E o)

public E get(int index)

Variabledeclarationexamples

ArrayList list1;

ArrayList list2;

ArrayList <String> a3;

ArrayList <Date> a4;

Instancedeclarationexamples

list1 = new ArrayList(10);

list2 = new ArrayList(10);

a3= new ArrayList<String> (10);

a4= new ArrayList<Date> (10);

Using Generics and the Collections Framework 10-19Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 262: Sl275 Sg

Generics: Examining Type Parameters

Figure 10-3 shows a UML diagram of the primary interfaces andimplementation classes of the generic Collections API.

Figure 10-3 Generic Collections API

Note – The type variable E in each interface declaration stands for thetype of the elements in the collection.

It is common practice to use upper case letters for type parameters. Javalibraries use:

● E for element type of collection

● K and V for key-value pairs

● T for all the other types

Collection<E><<interface>>

Set<E><<interface>>

List<E><<interface>>

HashSet<E>

ArrayList<E> LinkedList<E>

+add(element : E) : boolean

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

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

+add(index : int, element : E)

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

+set(index : int, element E) : E+indexOf(Object : o) : int+listIterator() : ListIterator<E>

TreeSet<E>

<<interface >>

SortedSet<E>

10-20 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 263: Sl275 Sg

Generics: Examining Type Parameters

Wild Card Type Parameters

The discussions contained in this section use the inheritance hierarchy ofthe Account class shown in Figure 10-4.

Figure 10-4 The Account Class and its Subclasses

This section introduces wildcard type parameters.

The Type-Safety Guarantee

Examine the code shown in Code 10-15.

Code 10-15 Type-Safety Discussion Code

List<CheckingAccount> lc = new ArrayList<CheckingAccount>();lc.add(new CheckingAccount("Fred")); // OKlc.add(new SavingsAccount("Fred")); // Compile error!// therefore...CheckingAccount ca = lc.get(0); // Safe, no cast required

If generic collections mean that inappropriate object types can never beadded, then the guarantee is that objects retrieved from the collection canbe directly and safely assigned to variables of the same type as the actualtype parameter.

Account

CheckingAccountSavingsAccount

Using Generics and the Collections Framework 10-21Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 264: Sl275 Sg

Generics: Examining Type Parameters

The Invariance Challenge

Consider the code contained in Code 10-16.

Code 10-16 Invariance of Assigning Collections of Different Types

List<Account> la;List<CheckingAccount> lc = new ArrayList<CheckingAccount>();List<SavingsAccount> ls = new ArrayList<SavingsAccount>();

//if the following were possible...la = lc;la.add(new CheckingAccount("Fred"));

//then the following must also be possible...la = ls;la.add(new CheckingAccount("Fred"));

//so...SavingsAccount sa = ls.get(0); //aarrgghh!!

In fact, la=lc; is illegal, so, even though a CheckingAccount is anAccount, an ArrayList<CheckingAccount> is not anArrayList<Account>.

For the type-safety guarantee always to be valid, it must be impossible toassign a collection of one type to a collection of a different type, even ifthe second type is a subclass of the first type.

This is at odds with traditional polymorphism and would appear at firstglance to make generic collections somewhat inflexible.

The Covariance Response

Consider the code shown in Code 10-17.

Code 10-17 Using Covarient Types

void printIds(List<? extends Account> lea) {for (Account a : lea) {

System.out.println(a.getAccountId());}

}

List<CheckingAccount> lc = new ArrayList<CheckingAccount>();List<SavingsAccount> ls = new ArrayList<SavingsAccount>();

printIds(lc);

10-22 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 265: Sl275 Sg

Generics: Examining Type Parameters

printIds(ls);

//but...List<? extends Object> leo = lc; //OKleo.add(new CheckingAccount("Fred"));//Compile error!

Wildcards allow a degree of flexibility when working with genericcollections. The printIds method is declared with an argument thatincludes a wildcard. The wildcard might be interpreted as "any kind oflist of unknown members of the Account family." The upper bound(Account) means that the elements in the collection can safely be assignedto an Account variable. Thus, the two collections of Account subtypes canboth be passed to the printIds method.

This covariance response is designed to be read from, rather than bewritten to. Because of the invariance principle, it is still illegal to add to acollection that uses a wildcard with the extends keyword.

Using Generics and the Collections Framework 10-23Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 266: Sl275 Sg

Generics: Refactoring Existing Non-Generic Code

Generics: Refactoring Existing Non-Generic Code

With generic collections, you can specify generic types without typearguments, which are called raw types. This feature is allowed to providecompatibility with the non-generic code.

At compile time, all the generic information from the generic code isremoved, leaving behind a raw type. This enables interoperability withthe legacy code as the class files generated by the generic code and thelegacy code would be the same. At runtime, ArrayList<String> andArrayList<Integer> get translated into ArrayList, which is a raw type.

Using the new Java SE 5.0 or later compiler on older, non-generic code,generates a warning. Code 10-18 illustrates a class that generates thecompile-time warning.

Code 10-18 A Class That Issues a Warning

1 import java.util.*;2 public class GenericsWarning {3 public static void main(String[] args) {4 List list = new ArrayList();5 list.add(0, new Integer(42));6 int total = ((Integer)list.get(0).intValue();7 }8 }

If you compile the GenericsWarning class using the following command:

javac GenericsWarning.java

you observe the following warning:

Note: GenericsWarning.java uses unchecked or unsafeoperations.Note: Recompile with -Xlint:unchecked for details.

Alternatively, if you compile the class using the following command:

javac -Xlint:unchecked GenericsWarning.java

you observe the warning:

GenericsWarning.java:5: warning: [unchecked] unchecked callto add(int,E) as a member of the raw type java.util.Listlist.add(0, new Integer(42));

10-24 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 267: Sl275 Sg

Generics: Refactoring Existing Non-Generic Code

^1 warning

Although the class compiles fine and the warnings can be ignored, youshould heed these warnings and modify your code to be generics-friendly.To resolve this warning in the GenericsWarning class, you need tochange line 4 to read:

List<Integer> list = new ArrayList<Integer>();

Using Generics and the Collections Framework 10-25Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 268: Sl275 Sg

Iterators

Iterators

You can scan (iterate over) a collection using an iterator. The basicIterator interface enables you to scan forward through any collection. Inthe case of an iteration over a set, the order is non-deterministic. Theorder of an iteration over a list moves forward through the list elements.A List object also supports a ListIterator, which permits you to scanthe list backwards and insert or modify list elements.

Note – The order of the set is deterministic if the set is an instance of someclass that guarantees the order. For example if the set is an instance ofTreeSet, which implements SortedSet, the order of the set isdeterministic.

Code 10-19 demonstrates the use of an iterator:

Code 10-19 Using Iterators

1 List list<Student> = new ArrayList<Student>();2 // add some elements3 Iterator<Student> elements = list.iterator();4 while (elements.hasNext()) {5 System.out.println(elements.next());6 }

10-26 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 269: Sl275 Sg

Iterators

Figure 10-5 shows a UML diagram of the generic Iterator interfaces forthe Collections API.

Figure 10-5 UML Diagram: Generic Iterator Interfaces

The remove method enables the code to remove the current item in theiteration (the item returned by the most recent next or previous method).If removal is not supported by the underlying collection, then anUnsupportedOperationException is thrown.

While using a ListIterator, it is common to move through the list inonly one direction: either forward using next or backward using previous.If you use previous immediately after next, then you receive the sameelement; likewise, for calling next after previous.

The set method changes the element of the collection currentlyreferenced by the iterator’s cursor. The add method inserts the newelement into the collection immediately before the iterator’s cursor.Therefore, if you call previous after an add, then it returns the newlyadded element. However, a call to next is not affected. If setting oradding is not supported by the underlying collection, then anUnsupportedOperationException is thrown.

Iterator<E>«interface»

ListIterator<E>«interface»

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

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

Using Generics and the Collections Framework 10-27Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 270: Sl275 Sg

The Enhanced forLoop

The Enhanced forLoop

Code 10-20 illustrates the use of an iterator in combination with atraditional for loop to iterate over a collection.

Code 10-20 Using an Iterator With Traditional for Loop

1 public void deleteAll(Collection<NameList> c) {2 for (Iterator<NameList> i=c.iterator(); i.hasNext();){3 NameList nl = i.next();4 nl.deleteItem();5 }6 }

In Code 10-20, the method deleteAll uses variable i three times in thefor loop. This provides opportunity for coding errors to be introduced.

Alternatively, you can iterate through a collection by using an enhancedfor loop. The enhanced for loop makes traversing through a collectionsimple, understandable, and safe. The enhanced for loop eliminates theusage of separate iterator methods and minimizes the number ofoccurrences of the iterator variable. Code 10-21 illustrates the methoddeleteAll with the enhanced for loop.

Code 10-21 Iterating Using the Enhanced for Loop in Collections

1 public void deleteAll(Collection<NameList> c) {2 for (NameList nl: c) {3 nl.deleteItem();4 }5 }

10-28 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 271: Sl275 Sg

The Enhanced forLoop

The functionality of the enhanced for loop, makes nested for loopstraversal simpler and easier to understand in comparison with thetraditional for loop. One reason for this is, using enhanced for loopsreduces the ambiguity of the variables used in the nested loops.Code 10-22 contains an example of nested enhanced for loops.

Code 10-22 Nesting Enhanced for Loops

1 List<Subject> subjects=...;2 List<Teacher> teachers=...;3 List<Course> courseList = new ArrayList<Course>();4 for (Subject subj: subjects) {5 for (Teacher tchr: teachers) {6 courseList.add(new Course(subj, tchr));7 }8 }

Using Generics and the Collections Framework 10-29Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 272: Sl275 Sg
Page 273: Sl275 Sg

Module 11

I/O Fundamentals

Objectives

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

● Write a program that uses command-line arguments and systemproperties

● Examine the Properties class

● Construct node and processing streams, and use them appropriately

● Serialize and deserialize objects

● Distinguish readers and writers from streams, and selectappropriately between them

11-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 274: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following references provide additionalinformation on the topics described in this module:

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

● Bates, Sierra. Head First Java, First Edition. O’Reilly Media. 2003.

11-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 275: Sl275 Sg

Command-Line Arguments

Command-Line Arguments

When a Java technology program is launched from a terminal window,you can provide the program with zero or more command-line arguments.These command-line arguments allow the user to specify theconfiguration information for the application. These arguments arestrings: either standalone tokens, such as arg1, or quoted strings, such as“another arg”.

The sequence of arguments follows the name of the program class and isstored in an array of String objects passed to the static main method;Code 11-1 shows an example:

Code 11-1 Testing the Command-Line Arguments

1 public class TestArgs {2 public static void main(String[] args) {3 for (int i = 0; i < args.length; i++) {4 System.out.println("args[" + i + "] is ’" + args[i] + "’");5 }6 }7 }

This program displays each command-line argument that is passed to theTestArgs program. For example:

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

Note – If an application requires command-line arguments other thantype String, for example numeric values, the application should convertthe String arguments to their respective types using the wrapper classes,such as Integer. parseInt method, which can be used to convert theString argument that represents the numeric integer to type int.

I/O Fundamentals 11-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 276: Sl275 Sg

System Properties

System Properties

System properties are another mechanism used to parameterize aprogram at runtime. A property is a mapping between a property nameand its value; both are strings. The Properties class represents this kindof mapping. The System.getProperties method returns the systemproperties object. The System.getProperty(String)method returns thestring value of the property named in the String parameter. There isanother method, System.getProperty(String, String), that enablesyou to supply a default string value (the second parameter), which isreturned if the named property does not exist.

Note – Every JVM implementation must supply a default set ofproperties. (Refer to the documentation for the System.getPropertiesmethod for details.) Moreover, a particular JVM implementation vendorcan supply others.

There are also static methods in the wrapper classes that performconversion of property values: Boolean.getBoolean(String),Integer.getInteger(String), and Long.getLong(String). The stringargument is the name of the property. If the property does not exist, thenfalse or null (respectively) is returned.

11-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 277: Sl275 Sg

The PropertiesClass

The PropertiesClass

An object of the Properties class contains a mapping between propertynames (String) and values (String). It has two main methods forretrieving a property value: getProperty(String) andgetProperty(String, String); the latter method provides thecapability of specifying a default value that is returned if the namedproperty does not exist.

You can iterate through the complete set of property names using thepropertyNames method. By calling getProperty on each name, you canretrieve all of the values.

Finally, property sets can be stored and retrieved from any I/O streamusing the store and load methods.

The Code 11-2 program lists the complete set of properties that exist whenthe program executes:

Code 11-2 Retrieving the System Properties

1 import java.util.Properties;23 public class TestProperties {4 public static void main(String[] args) {5 Properties props = System.getProperties();6 props.list(System.out);7 }8 }

Line 6 retrieves the set of system properties and Line 7 prints theproperties using the list method of the Properties class.

java -DmyProp=theValue TestProperties

The following is an excerpt of the output:

java.runtime.name=Java(TM) SE Runtime Environmentsun.boot.library.path=C:\jse\jdk1.6.0\jre\binjava.vm.version=1.6.0-b105java.vm.vendor=Sun Microsystems Inc.java.vm.name=Java HotSpot(TM) Client VMfile.encoding.pkg=sun.iouser.country=USmyProp=theValue

I/O Fundamentals 11-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 278: Sl275 Sg

I/O Stream Fundamentals

I/O Stream Fundamentals

A stream is a flow of data from a source to a sink. Typically, your programis one end of that stream, and some other node (for example, a file) is theother end.

Sources and sinks are also called input streams and output streams,respectively. You can read from an input stream, but you cannot write toit. Conversely, you can write to an output stream, but you cannot readfrom it.Table 11-1 shows the fundamental stream classes.

Data Within Streams

Java technology supports two types of data in streams: raw bytes orUnicode characters. Typically, the term stream refers to byte streams andthe terms reader and writer refer to character streams.

More specifically, character input streams are implemented by subclassesof the Reader class and character output streams are implemented bysubclasses of the Writer class. Byte input streams are implemented bysubclasses of the InputStream class and byte output streams areimplemented by subclasses of the OutputStream class.

Table 11-1 Fundamental Stream Classes

Stream Byte Streams Character Streams

Source streams InputStream Reader

Sink streams OutputStream Writer

11-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 279: Sl275 Sg

Byte Streams

Byte Streams

The following sections describe the fundamental byte streams.

The InputStreamMethods

The following three methods provide access to the data from the inputstream:

int read()int read(byte[] buffer)int read(byte[] buffer, int offset, int length)

The first method returns an int, which contains either a byte read fromthe stream, or a -1, which indicates the end of file condition. The othertwo methods read the stream into a byte array and return the number ofbytes read. The two int arguments in the third method indicate a subrange in the target array that needs to be filled.

Note – For efficiency, always read data in the largest practical block, oruse buffered streams.

void close()

When you have finished with a stream, close it. If you have a stack ofstreams, use filter streams to close the stream at the top of the stack. Thisoperation also closes the lower streams.

int available()

This method reports the number of bytes that are immediately available tobe read from the stream. An actual read operation following this callmight return more bytes.

long skip(long n)

This method discards the specified number of bytes from the stream.

boolean markSupported()void mark(int readlimit)void reset()

I/O Fundamentals 11-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 280: Sl275 Sg

Byte Streams

You can use these methods to perform push-back operations on a stream, ifsupported by that stream. The markSupported() method returns true ifthe mark() and reset() methods are operational for that particularstream. The mark(int) method indicates that the current point in thestream should be noted and a buffer big enough for at least the specifiedargument number of bytes should be allocated. The parameter of themark(int) method specifies the number of bytes that can be re-read bycalling reset(). After subsequent read() operations, calling the reset()method returns the input stream to the point you marked. If you read pastthe marked buffer, reset() has no meaning.

The OutputStreamMethods

The following methods write to the output stream:

void write(int)void write(byte[] buffer)void write(byte[] buffer, int offset, int length)

As with input, always try to write data in the largest practical block.

void close()

You should close output streams when you have finished with them.Again, if you have a stack and close the top one, this closes the rest of thestreams.

void flush()

Sometimes an output stream accumulates writes before committing them.The flush() method enables you to force writes.

11-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 281: Sl275 Sg

Character Streams

Character Streams

The following sections describe the fundamental character streams.

The ReaderMethods

The following three methods provide access to the character data from thereader:

int read()int read(char[] cbuf)int read(char[] cbuf, int offset, int length)

The first method returns an int, which contains either a Unicodecharacter read from the stream, or a -1, which indicates the end of filecondition. The other two methods read into a character array and returnthe number of bytes read. The two int arguments in the third methodindicate a sub range in the target array that needs to be filled.

Note – Use the largest practical block for efficiency.

void close()boolean ready()long skip(long n)boolean markSupported()void mark(int readAheadLimit)void reset()

These methods are analogous to the input stream versions.

I/O Fundamentals 11-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 282: Sl275 Sg

Character Streams

The WriterMethods

The following methods write to the writer:

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 length)

Similar to output streams, writers include the close and flush methods.

void close()void flush()

11-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 283: Sl275 Sg

Node Streams

Node Streams

In the Java JDK, there are three fundamental types of nodes (Table 11-2):

● Files

● Memory (such as arrays or String objects)

● Pipes (a channel from one process or thread [a light-weight process]to another; the output pipe stream of one thread is attached to theinput pipe stream of another thread)

It is possible to create new node stream classes, but it requires handlingnative function calls to a device driver, and this is non-portable. Table 11-2shows the node streams.

A Simple Example

Code 11-3 reads characters from a file named by the first command-lineargument and writes the character out to a file named by the secondcommand-line argument. Thus, it copies the file. This is how the programmight be invoked:

java TestNodeStreams file1 file2

Code 11-3 The TestNodeStreams Program

1 import java.io.*;23 public class TestNodeStreams {4 public static void main(String[] args) {

Table 11-2 Types of Node Streams

Type Character Streams Byte Streams

File FileReaderFileWriter

FileInputStreamFileOutputStream

Memory:array

CharArrayReaderCharArrayWriter

ByteArrayInputStreamByteArrayOutputStream

Memory:string

StringReaderStringWriter

N/A

Pipe PipedReaderPipedWriter

PipedInputStreamPipedOutputStream

I/O Fundamentals 11-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 284: Sl275 Sg

Node Streams

5 try {6 FileReader input = new FileReader(args[0]);7 try {8 FileWriter output = new FileWriter(args[1]);9 try {10 char[] buffer = new char[128];11 int charsRead;1213 // read the first buffer14 charsRead = input.read(buffer);15 while ( charsRead != -1 ) {16 // write buffer to the output file17 output.write(buffer, 0, charsRead);1819 // read the next buffer20 charsRead = input.read(buffer);21 }2223 } finally {24 output.close();}25 } finally {26 input.close();}27 } catch (IOException e) {28 e.printStackTrace();29 }30 }31 }

As easy as this was, handling the buffer is tedious and error-prone. Itturns out that there are classes that handle the buffering for you andpresent you with the capability to read a stream a line at a time. It is calleda BufferedReader and is a type of a stream called a processing stream.

11-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 285: Sl275 Sg

Buffered Streams

Buffered Streams

The Code 11-4 performs the same function as the program in Code 11-3 onpage 11-11 but uses BufferedReader and BufferedWriter.

Code 11-4 The TestBufferedStreams Program

1 import java.io.*;2 public class TestBufferedStreams {3 public static void main(String[] args) {4 try {5 FileReader input = new FileReader(args[0]);6 BufferedReader bufInput = new BufferedReader(input);7 try {8 FileWriter output = new FileWriter(args[1]);9 BufferedWriter bufOutput= new BufferedWriter(output);10 try {11 String line;12 // read the first line13 line = bufInput.readLine();14 while ( line != null ) {15 // write the line out to the output file16 bufOutput.write(line, 0, line.length());17 bufOutput.newLine();18 // read the next line19 line = bufInput.readLine();20 }21 } finally {22 bufOutput.close();23 }24 } finally {25 bufInput.close();26 }27 } catch (IOException e) {28 e.printStackTrace();29 }30 }31 }

The flow of this program is the same as before. Instead of reading a buffer,this program reads a line at a time using the line variable to hold theString returned by the readLine method (Lines 14 and 20), whichprovides greater efficiency. Line 7 chains the file reader object within abuffered reader stream. You manipulate the outer-most stream in thechain (bufInput), which manipulates the inner-most stream (input).

I/O Fundamentals 11-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 286: Sl275 Sg

I/O Stream Chaining

I/O Stream Chaining

A program rarely uses a single stream object. Instead, it chains a series ofstreams together to process the data. Figure 11-1 demonstrates an exampleinput stream; in this case, a file stream is buffered for efficiency and thenconverted into data (Java primitives) items.

Figure 11-1 An Input Stream Chain Example

Figure 11-2 demonstrates an example output stream; in this case, data iswritten, then buffered, and finally written to a file.

Figure 11-2 An Output Stream Chain Example

Data Source ProgramFileInputStream

BufferedInputStreamDataInputStream

Data SinkProgram

FileOutputStreamBufferedOutputStream

DataOutputStream

11-14 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 287: Sl275 Sg

Processing Streams

Processing Streams

A processing stream performs some sort of conversion on another stream.Processing streams are also known as filter streams. A filter input stream iscreated with a connection to an existing input stream. This is done so thatwhen you try to read from the filter input stream object, it supplies youwith characters that originally came from the other input stream object.This enables you to convert the raw data into a more usable form for yourapplication. Table 11-3 lists the built-in processing streams that areincluded in the java.io package.

Note – The FilterXyz streams are abstract classes and cannot be useddirectly. You can subclass them to implement your own processingstreams.

It is easy to create new processing streams. This is described in the nextsection.

Note – Performing object serialization is described later in this module.

Table 11-3 List of Processing Streams by Type

Type Character Streams Byte Streams

Buffering BufferedReaderBufferedWriter

BufferedInputStreamBufferedOutputStream

Filtering FilterReaderFilterWriter

FilterInputStreamFilterOutputStream

Converting betweenbytes and character

InputStreamReaderOutputStreamWriter

*Performing objectserialization

ObjectInputStreamObjectOutputStream

Performing dataconversion

DataInputStreamDataOutputStream

Counting LineNumberReader LineNumberInputStream

Peeking ahead PushbackReader PushbackInputStream

Printing PrintWriter PrintStream

I/O Fundamentals 11-15Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 288: Sl275 Sg

Basic Byte Stream Classes

Basic Byte Stream Classes

Figure 11-3 illustrates the hierarchy of input byte stream classes in thejava.io package. Some of the more common byte stream classes aredescribed in the following sections.

Figure 11-3 The InputStream Class Hierarchy

Figure 11-4 illustrates the hierarchy of the output byte stream classes inthe java.io package.

Figure 11-4 The OutputStream Class Hierarchy

InputStream

FileInputStream

ObjectInputStream

PipedInputStream

StringBufferInputStream

FilterInputStream

ByteArrayInputStream

DataInputStream

PushbackInputStream

BufferedInputStream

LineNumberInputStream

SequenceInputStream

OutputStream

FileOutputStream

ObjectOutputStream

FilterOutputStream

ByteArrayOutputStream

DataOutputStream

PrintStreamPrintStream

BufferedOutputStream

PipedOutputStream

11-16 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 289: Sl275 Sg

Basic Byte Stream Classes

The FileInputStream and FileOutputStreamClasses

The FileInputStream and FileOutputStream classes are node streamsand, as the name suggests, they use disk files. The constructors for theseclasses enable you to specify the path of the file to which they areconnected. To construct a FileInputStream, the associated file must existand be readable. If you construct a FileOutputStream, the output file isoverwritten if it already exists.

FileInputStream infile= new FileInputStream("myfile.dat");

FileOutputStream outfile= new FileOutputStream("results.dat");

The BufferedInputStream andBufferedOutputStreamClasses

Use the BufferedInputStream and BufferedOutputStream class filterstreams to increase the efficiency of I/O operations.

The PipedInputStream and PipedOutputStreamClasses

You use piped streams for communicating between threads. APipedInputStream object in one thread receives its input from acomplementary PipedOutputStream object in another thread. The pipedstreams must have both an input side and an output side to be useful.

The DataInputStream and DataOutputStreamClasses

The DataInputStream and DataOutputStream called filter streamsenable reading and writing of Java primitive types and some specialformats using streams. The following methods are provided for thedifferent primitives.

I/O Fundamentals 11-17Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 290: Sl275 Sg

Basic Byte Stream Classes

The DataInputStreamMethods

The DataInputStream methods are as follows:

byte readByte()long readLong()double readDouble()

The DataOutputStreamMethods

The DataOutputStream methods are as follows:

void writeByte(byte)void writeLong(long)void writeDouble(double)

The methods of DataInputStream are paired with the methods ofDataOutputStream.

These streams have methods for reading and writing strings but do notuse these methods. They have been deprecated and replaced by readersand writers that are described later.

The ObjectInputStream and ObjectOutputStreamClasses

The ObjectInputStream and ObjectOutputstream classes enablereading from and writing Java Objects to streams.

Writing an object to a stream primarily involves writing the values of allthe fields of the object. If the fields are objects themselves, these objectsshould also be written to the stream.

Note – If the fields are declared as transient or static, their values arenot written to the stream. This is discussed in the next section.

Reading an object from the stream involves, reading the object type,creating the blank object of that type and filling it with the data that waswritten.

Persistent storage of objects can be accomplished if files (or otherpersistent storages) are used as the stream.

11-18 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 291: Sl275 Sg

Basic Byte Stream Classes

The Java API provides a standard mechanism that completely automatesthe process of writing and reading objects from streams.

Note – If the stream is a network socket stream, the objects are serializedbefore sending and deserialized after receiving on another host or process.

Figure 11-5 provides an overview illustration of the possible input streamand reader classes you could chain together.

Figure 11-5 Input Chaining Combinations: A Review

System.in(InputStream)

FileInputStream

socket.getInputStream

ByteArrayInputStream

PipedInputStream

read():byteread(byte[])

FileReader

PipedInputStream

read():charread(char[])

ObjectInputStream

DataInputStream

byte byte

byte byte

readObject():object

readInt():intreadDouble():doublereadUTF():String

Object

int double String

InputStreamReader

BufferedReader

readLine():String

byte

char

char char

String

I/O Fundamentals 11-19Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 292: Sl275 Sg

Basic Byte Stream Classes

Figure 11-6 provides an overview illustration of the possible outputstream and writer classes you could chain together.

Figure 11-6 Output Chaining Combinations: A Review

FileOutputStream

socket.getOutputStream

ByteArrayOutputStream

PipedOutputStream

FileWriter

CharArrayWriter

write(byte)write(byte[])

PrintStreamSystem.out

ObjectOutputStream

byte byte

printIn(String)

writeObject(Object)

Object

String

OutputStreamWriter

BufferedWriter

write(String)

byte

char

char char

String

byte byte

DataOutputStream

writeInt(int)writeDouble(double)writeUTF(String)

byte byteUTF

double

int

11-20 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 293: Sl275 Sg

Serialization

Serialization

Saving an object to some type of permanent storage is called persistence.An object is said to be persistent-capable when you can store that object ona disk or tape or send it to another machine to be stored in memory or ondisk. The non-persisted object exists only as long as the Java VirtualMachine is running.

Serialization is a mechanism for saving the objects as a sequence of bytesand later, when needed, rebuilding the byte sequence back into a copy ofthe object.

For objects of a specific class to be serializable, the class must implementthe java.io.Serializable interface. The Serializable interface hasno methods and only serves as a marker that indicates that the class thatimplements the interface can be considered for serialization.

Serialization and Object Graphs

When an object is serialized, only the fields of the object are preserved;methods and constructors are not part of the serialized stream. When afield is a reference to an object, the fields of that referenced object are alsoserialized if that object’s class is serializable. The tree, or structure of anobject’s fields, including these sub-objects, constitutes the object graph.

Some object classes are not serializable because the data they representcontain references to transient operating system resources. For example,java.io.FileInputStream and java.lang.Thread classes. If aserializable object contains a reference to a non-serializable element, theentire serialization operation fails and a NotSerializableException isthrown.

If the object graph contains a non-serializable object reference, the objectcan still be serialized if the reference is marked with the transientkeyword.

Code 11-5 shows an example of a class that implements theSerializable interface.

Code 11-5 The Serializable Example

1 public class MyClass implements Serializable {2 public transient Thread myThread;

I/O Fundamentals 11-21Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 294: Sl275 Sg

Serialization

3 private String customerID;4 private int total;5 }

The field access modifier (public, protected, default, and private) hasno effect on the data field being serialized. Data is written to the stream inbyte format and with strings represented as file system safe universalcharacter set transformation format (UTF) characters. The transientkeyword prevents the data from being serialized.

1 public class MyClass implements Serializable {2 public transient Thread myThread;3 private transient String customerID;4 private int total;5 }

Note – The values stored in static fields are not serialized. When the objectis deserialized the values of the static fields are set to the values stored inthe corresponding class variables.

Writing and Reading an Object Stream

Writing and reading an object to a stream is a simple process. This sectionprovides examples of writing to and reading from an object stream.

Writing

The code fragment contained in Code 11-6 sends an instance of ajava.util.Date object to a file.

Code 11-6 The SerializeDate Class

1 import java.io.*;2 import java.util.Date;34 public class SerializeDate {56 SerializeDate() {7 Date d = new Date ();89 try {10 FileOutputStream f =11 new FileOutputStream ("date.ser");

11-22 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 295: Sl275 Sg

Serialization

12 ObjectOutputStream s =13 new ObjectOutputStream (f);14 s.writeObject (d);15 s.close ();16 } catch (IOException e) {17 e.printStackTrace ();18 }19 }2021 public static void main (String args[]) {22 new SerializeDate();23 }24 }

The serialization starts at Line 14 when writeObject() method isinvoked.

Reading

Reading the object is as simple as writing it, but with one caveat—thereadObject() method returns the stream as an Object type, and it mustbe cast to the appropriate class name before methods on that class can beexecuted. The Code 11-7 illustrates how to deserialize data from a stream.

Code 11-7 The DeSerializeDate Class

1 import java.io.*;2 import java.util.Date;34 public class DeSerializeDate {56 DeSerializeDate () {7 Date d = null;89 try {10 FileInputStream f =11 new FileInputStream ("date.ser");12 ObjectInputStream s =13 new ObjectInputStream (f);14 d = (Date) s.readObject ();15 s.close ();16 } catch (Exception e) {17 e.printStackTrace ();18 }19

I/O Fundamentals 11-23Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 296: Sl275 Sg

Serialization

20 System.out.println(21 "Deserialized Date object from date.ser");22 System.out.println("Date: "+d);23 }2425 public static void main (String args[]) {26 new DeSerializeDate();27 }28 }

The object deserialization occurs at Line 14, when the readObject()method is invoked.

11-24 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 297: Sl275 Sg

Basic Character Stream Classes

Basic Character Stream Classes

Figure 11-7 illustrates the hierarchy of Reader character stream classes inthe java.io package. Some of the more common character stream classesare described in the following sections.

Figure 11-7 The Reader Class Hierarchy

Figure 11-8 illustrates the hierarchy of the Writer character stream classesin the java.io package.

Figure 11-8 The Writer Class Hierarchy

Reader

BufferedReader

CharArrayReader

PipedReader

FilterReader

StringReader

FileReaderInputStreamReader

LineNumberReader

PushbackReader

Writer

BufferedWriter

CharArrayWriter

PrintWriter

PipedWriter

FilterWriter

StringWriter

FileWriterOutputStreamWriter

I/O Fundamentals 11-25Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 298: Sl275 Sg

Basic Character Stream Classes

The InputStreamReader and OutputStreamWriterMethods

The most important versions of readers and writers areInputStreamReader and OutputStreamWriter. These classes are used tointerface between byte streams and character readers and writers.

When you construct an InputStreamReader or OutputStreamWriter,conversion rules are defined to change between 16-bit Unicode and otherplatform-specific representations.

Byte and Character Conversions

By default, if you construct a reader or writer connected to a stream, theconversion rules change between bytes using the default platformcharacter encoding and Unicode. In English-speaking countries, the byteencoding used is International Organization for Standardization (ISO) 8859-1.

Specify an alternative byte encoding by using one of the supportedencoding forms. If you have the documentation installed, you can find alist of the supported encoding forms in the documentation found in thefollowing URL:http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html.

Using this conversion scheme, Java technology uses the full flexibility ofthe local platform character set while still retaining platformindependence through the internal use of Unicode.

Using Other Character Encoding

If you need to read input from a character encoding that is not your localone (for example, reading from a network connection with a different typeof machine), you can construct the InputStreamReader with an explicitcharacter encoding, such as:

InputStreamReader ir= new InputStreamReader(System.in, "ISO-8859-1");

11-26 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 299: Sl275 Sg

Basic Character Stream Classes

Note – If you are reading characters from a network connection, use thisform. If you do not, your program will always attempt to convert thecharacters it reads as if they were in the local representation, which isprobably not correct. ISO 8859-1 is the Latin-1 encoding scheme that mapsonto ASCII.

The FileReader and FileWriterClasses

The FileReader and FileWriter classes are node streams that are theUnicode character analogues of the FileInputStream andFileOutputStream classes.

The BufferedReader and BufferedWriterClasses

Use the BufferedReader and BufferedWriter class filter characterstreams to increase the efficiency of I/O operations.

The StringReader and StringWriterClasses

The StringReader and StringWriter classes are node character streamsthat read from or write to Java technology String objects.

Suppose that you wrote a set of report classes that contains methods thataccept a Writer parameter (the destination of the report text). Because themethod makes calls against a generic interface, the program can pass in aFileWriter object or a StringWriter object; the method code does notcare. You use the former object to write the report to a file. You might usethe latter object to write the report into memory within a String to bedisplayed within a GUI text area. In either case, the report writing coderemains the same.

The PipedReader and PipedWriterClasses

You use piped streams for communicating between threads. APipedReader object in one thread receives its input from acomplementary PipedWriter object in another thread. The piped streamsmust have both an input side and an output side to be useful.

I/O Fundamentals 11-27Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 300: Sl275 Sg
Page 301: Sl275 Sg

Module 12

Console I/O andFile I/O

Objectives

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

● Examine console I/O

● Describe files and file I/O

12-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 302: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following references provide additionalinformation on the topics described in this module:

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

● Bates, Sierra. Head First Java, First Edition. O’Reilly Media. 2003.

12-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 303: Sl275 Sg

Console I/O

Console I/O

Most applications must interact with the user. Such interaction issometimes accomplished with text input and output to the console (usingthe keyboard as the standard input and using the terminal window as thestandard output).

Java JDK supports console I/O with three public static variables on thejava.lang.System class:

● The variable System.out is a PrintStream object that refers(initially) to the terminal window that launched the Java technologyapplication.

● The variable System.in is an InputStream object that refers(initially) to the user’s keyboard.

● The variable System.err is a PrintStream object that refers(initially) to the terminal window that launched the Java technologyapplication.

It is possible to reroute these streams using the static methods:System.setOut, System.setIn, and System.setErr. For example, youcould reroute standard error to a file stream.

Writing to Standard Output

You can write to standard output through theSystem.out.println(String) method. This PrintStream methodprints the string argument to the console and adds a newline character atthe end. The following methods are also supported to print other types:primitives, a character buffer, and an arbitrary object. All of thesemethods add a newline character at the end of the output.

void println(boolean)void println(char)void println(double)void println(float)void println(int)void println(long)void println(char[])void println(Object)

There is also a corresponding set of overloaded methods, called print,that do not add the newline character.

Console I/ O and File I/O 12-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 304: Sl275 Sg

Console I/O

Reading From Standard Input

The example Code 12-1, shows a technique that you should use to readString information from the console standard input:

Code 12-1 KeyboardInput Program

1 import java.io.*;23 public class KeyboardInput {4 public static void main (String[] args) {5 String s;6 // Create a buffered reader to read7 // each line from the keyboard.8 InputStreamReader ir9 = new InputStreamReader(System.in);10 BufferedReader in = new BufferedReader(ir);11 System.out.println("Unix: Type ctrl-d to exit." +12 "\nWindows: Type ctrl-z to exit");13

Line 5 declares a String variable, s, that the program uses to hold eachline read from standard input. Lines 8–10 wrap System.in with twosupport objects that massage the stream of bytes coming from standardinput. The InputStreamReader (ir) reads characters and converts theraw bytes into Unicode characters. The BufferedReader (in) providesthe readLine method which enables the program to read from standardinput one line at a time.

Note – The Control-d character on the UNIX platform indicates the end offile condition. In the Microsoft Windows environment, use the keystrokesequence Control-z followed by pressing the Enter key to indicateend-of-file (EOF).

The code for KeyboardInput continues:

14 try {15 // Read each input line and echo it16 s = in.readLine();17 while ( s != null ) {18 System.out.println("Read: " + s);19 s = in.readLine();20 }

12-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 305: Sl275 Sg

Console I/O

Line 16 reads the first line of text from standard input. The while loop(Lines 17 – 20) iteratively prints out the current line and reads the nextline. This code could be rewritten more succinctly (but more cryptically)as:

while ( (s = in.readLine()) != null ) {System.out.println("Read: " + s);

}

Because the readLine method can throw an I/O exception, you mustwrap all of this code in a try-catch block.

2122 // Close the buffered reader.23 in.close();

Line 23 closes the outer most input stream to release any system resourcesrelated to creating these stream objects.

24 } catch (IOException e) { // Catch any exceptions.25 e.printStackTrace();26 }27 }28 }

Finally, the program handles any I/O exceptions that might occur.

Note – The call to the close method on Line 23 should really be performedin a finally clause. This is not done in this code example for reasons ofbrevity.

Console I/ O and File I/O 12-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 306: Sl275 Sg

Console I/O

Simple Formatted Output

The Java programming language version 1.5 provided C language-styleprintf functionality. It provides standard formatted output from theprogram. This enables programmers to migrate from legacy code.

You can use the printf as normal C and C++ syntax.

System.out.printf("%s %5d %f%n",name,id,salary);

This formatting functionality is also available in the String class in theformat method. The same output can also be generated as follows.

String s = String.format("%s %5d %f%n",name,id,salary);System.out.print(s);

Table 12-1 shows a few common formatting codes.

You can use %n for the newline character, instead of \n, for platformindependence.

Note – For more information about the functionality of printf and theformatting codes, read the API document for the classjava.util.Formatter.

Table 12-1 Common Formatting Codes

Code Description

%s Formats the argument as a string, usually by calling thetoString method on the object.

%d %o %x Formats an integer, as a decimal, octal, or hexadecimalvalue.

%f %g Formats a floating point number. The %g code usesscientific notation.

%n Inserts a newline character to the string or stream.

%% Inserts the % character to the string or stream.

12-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 307: Sl275 Sg

Console I/O

Simple Formatted Input

The Scanner class provides formatted input functionality. It is part of thejava.util package. It provides methods for getting primitive values andstrings will block as it waits for input from the user. An example is shownin Code 12-2.

Code 12-2 Example of the Scanner Class

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" + param);8 int value = s.nextInt();9 System.out.println("second param" + value);10 s.close();11 }12 }

In Code 12-2, Line 5 creates a Scanner reference by passing directly theconsole input. Line 6 retrieves the string value from the given input byusing the Scannermethod next. Line 8 gets the integer value of the giveninput by using the nextInt method. Line 10 closes the input from theuser.

Note – Scanner class can be used to break down the formatted input intodifferent tokens of primitive and String types. You can also use regularexpressions to scan streams. For more information, look at the followinglink:http://java.sun.com/docs/books/tutorial/essential/io/scanning.html

Console I/ O and File I/O 12-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 308: Sl275 Sg

Files and File I/O

Files and File I/O

Java technology includes a rich set of I/O streams which are described inthe previous chapter. This section examines several simple techniques forreading and writing to files with a focus on character data, including:

● Creating File objects

● Manipulating File objects

● Reading and writing to file streams

Creating a New FileObject

The File class provides several utilities for handling files and obtaininginformation about them. In Java technology, a directory is just another file.You can create a File object that represents a directory and then use it toidentify other files, as shown in the third bullet.

● File myFile;myFile = new File("myfile.txt");

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

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

The constructor that you use often depends on the other file objects thatyou can access. For example, if you use only one file in your application,use the first constructor. However, if you use several files from a commondirectory, using the second or third constructors might be easier.

The class File defines platform-independent methods for manipulating afile maintained by a native file system. However, it does not permit you toaccess the contents of the file.

Note – You can use a File object as the constructor argument forFileReader and FileWriter objects in place of a string. This gives youindependence from the local file system conventions and isrecommended, in general.

12-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 309: Sl275 Sg

Files and File I/O

The FileTests and Utilities

After you create a File object, you can use any methods in the followingsections to gather information about the file.

File Names

The following methods return file names:

● String getName()

● String getPath()

● String getAbsolutePath()

● String getParent()

● boolean renameTo(File newName)

Directory Utilities

The following methods provide directory utilities:

● boolean mkdir()

● String[] list()

General File Information and Utilities

The following methods return general file information:

● long lastModified()

● long length()

● boolean delete()

File Tests

The following methods return information about file attributes:

● boolean exists()

● boolean canWrite()

● boolean canRead()

● boolean isFile()

● boolean isDirectory()

Console I/ O and File I/O 12-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 310: Sl275 Sg

Files and File I/O

● boolean isAbsolute()

● boolean isHidden()

File Stream I/O

The Java SE Development Kit supports file input in two forms:

● Use the FileReader class to read characters

● Use the BufferedReader class to use the readLine method

The Java SE Development Kit supports file output in two forms:

● Use the FileWriter class to write characters

● Use the PrintWriter class to use the print and println methods

File Input Example

Code 12-3 reads a text file and echoes each line to standard output, whichprints the file.

Code 12-3 Reading From a File

1 import java.io.*;2 public class ReadFile {3 public static void main (String [] args) {4 // Create file5 File file = new File(args[0]);67 try {8 // Create a buffered reader9 // to read each line from a file.10 BufferedReader in11 = new BufferedReader(new FileReader(file));12 String s;13

Line 5 creates a new File object based on the first command-lineargument to the program. Lines 10 and 11 creates a buffered reader thatwraps around a file reader. This code throws a FileNotFoundExceptionif the file does not exist.

12-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 311: Sl275 Sg

Files and File I/O

Code 12-4 reads a text file and echoes each line to standard output, thusprinting the file.

Code 12-4 Printing a File

14 try {15 // Read each line from the file16 s = in.readLine();17 while (s != null) {18 System.out.println("Read: " + s);19 s = in.readLine();20 }21 } finally {22 // Close the buffered reader23 in.close();24 }2526 } catch (FileNotFoundException e1) {27 // If this file does not exist28 System.err.println("File not found: " + file);2930 } catch (IOException e2) {31 // Catch any other IO exceptions.32 e2.printStackTrace();33 }3435 }36 }

In Code 12-4, the while loop in Lines 17–20 is exactly the same as in theKeyboardInput program (Code 12-1 on page 12-4); it reads each text linein the buffered reader and echoes it to standard output.

Line 23 closes the buffered reader, which in turn closes the file reader thatthe buffered reader object decorates.

The exception handling code in Lines 26–28 catches theFileNotFoundException that might be thrown by the FileReaderconstructor. Lines 30–33 handle any other I/O-based exception that mightbe thrown (by the readLine and close methods).

Console I/ O and File I/O 12-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 312: Sl275 Sg

Files and File I/O

File Output Example

Code 12-5 reads input lines from the keyboard and echoes each line to afile.

Code 12-5 File Output Example

1 import java.io.*;23 public class WriteFile {4 public static void main (String[] args) {5 // Create file6 File file = new File(args[0]);78 try {9 // Create a buffered reader10 InputStreamReader isr11 = new InputStreamReader(System.in);12 BufferedReader in13 = new BufferedReader(isr);14 // Create a print writer on this file.15 PrintWriter out16 = new PrintWriter(new FileWriter(file));17 String s;

Just as in Code 12-4 on page 12-11, Line 6 of Code 12-5 creates a Fileobject based on the first command-line argument. Lines 10–11 create acharacter reader stream from the binary stream (System.in). Lines 12–13create a buffered reader for the standard input. Lines 15–16 create a printwriter that decorates a file writer for the file created in Line 6.

18 System.out.print("Enter file text. ");19 System.out.println("[Type ctrl-d to stop.]");2021 // Read each input line22 while ((s = in.readLine()) != null) {23 out.println(s);24 }25

Lines 18–19 prompt the user to enter lines of text to be placed in the fileand to type Control-d to stop. Lines 22–24 read from the input stream andprints to the file, one line at a time.

12-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 313: Sl275 Sg

Files and File I/O

Note – The Control-d character (which represents end-of-file) must be usedin this example and not Control-c, because Control-c terminates the JVMmachine before the program closes the file stream properly.

26 // Close the buffered reader27 in.close();28 out.close();2930 } catch (IOException e) {31 // Catch any IO exceptions.32 e.printStackTrace();33 }34 }35 }

Lines 27 and 28 close the input and output streams. Lines 30–33 handleany I/O exceptions that might be thrown.

Console I/ O and File I/O 12-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 314: Sl275 Sg
Page 315: Sl275 Sg

Module 13

ImplementingMulti-TierApplicationsUsingNetworking

Objectives

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

● Develop code to set up the network connection

● Use ServerSocket and Socket classes for implementation ofTCP/IP clients and server

● Describe and use the URL class

13-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 316: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following references provide additionalinformation on the topics described in this module:

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

● Bates, Sierra. Head First Java, Second Edition. O’Reilly Media. 2005.

13-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 317: Sl275 Sg

Networking

Networking

The following section describes the concept of networking by usingsockets.

Sockets

Socket is the name given, in one particular programming model, to theendpoints of a communication link between processes. Because of thepopularity of that particular programming model, the term socket hasbeen reused in other programming models, including Java technology.

When processes communicate over a network, Java technology uses thestreams model. A socket can hold two streams: one input stream and oneoutput stream. A process sends data to another process through thenetwork by writing to the output stream associated with the socket. Aprocess reads data written by another process by reading from the inputstream associated with the socket.

After the network connection is set up, using the streams associated withthat connection is similar to using any other stream.

Setting Up the Connection

To set up the connection, one machine must run a program that is waitingfor a connection, and a second machine must try to reach the first. This issimilar to a telephone system, in which one party must make the call,while the other party is waiting by the telephone when that call is made.

Implementing Multi-Tier Applications Using Networking 13-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 318: Sl275 Sg

Networking

A description of the TCP/IP network connections is presented in thismodule. An example network connection is shown in Figure 13-1.

Figure 13-1 Diagram of Example Network Connections

The same port on the server is reused by multiple client connections. Aconnection is identified by four numbers: client IP address, client portnumber, server IP address, and server port number. Consequently, thisscheme enables the server to remain in place and handle multipleconnections from the same client, because the client will allocate differentport numbers for each connection that it initiates. This client-port numberallocation is handled by the OS. The programmer does not specify theclient port, but specifies only the server port. The analogy with thetelephone system works well in this situation. The caller (client) mustknow both the phone number and the extension of the party that thecaller wishes to speak with, but the client’s own phone number (IPaddress) and extension (port) are not important to the person on thephone (although the underlying system uses this information).

client.bar.com

client.baz.com

server.foo.com

18000

18002

3000

13-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 319: Sl275 Sg

Networking

Networking With Java Technology

This section describes the concept of networking by using Javatechnology.

Addressing the Connection

When you make a telephone call, you need to know the telephonenumber to dial. When you make a network connection, you need to knowthe address or the name of the remote machine. In addition, a networkconnection requires a port number, which you can think of as a telephoneextension number. After you connect to the proper computer, you mustidentify a particular purpose for the connection. So, in the same way thatyou can use a particular telephone extension number to talk to theaccounts department, you can use a particular port number tocommunicate with the accounting program.

Port Numbers

Port numbers in TCP/IP systems are 16-bit numbers and the values rangefrom 0–65535. In practice, port numbers below 1024 are reserved forpredefined services, and you should not use them unless communicatingwith one of those services (such as telnet, Simple Mail TransportProtocol [SMTP] mail, ftp, and so on). Client port numbers are allocatedby the host OS to something not in use, while server port numbers arespecified by the programmer, and are used to identify a particular service.

Both client and server must agree in advance on which port to use. If theport numbers used by the two parts of the system do not agree,communication does not occur.

Note – The port number that the client uses to connect to the servershould be the same as the port number that the server offerscommunication on. However, if the server offers service on port 2000, theclient’s port number in this scenario might be different from 2000, but theclient should connect to the server using the port 2000. This is also whythere are two methods getPort() (which returns the remote port towhich this socket is connected) and getLocalPort() (which returns thelocal port to which this socket is bound) on a Socket object.

Implementing Multi-Tier Applications Using Networking 13-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 320: Sl275 Sg

Networking

Java Networking Model

In the Java programming language, TCP/IP socket connections areimplemented with classes in the java.net package. Figure 13-2 illustrateswhat occurs on the server side and the client side.

Figure 13-2 TCP/IP Socket Connections

In Figure 13-2:

● The server assigns a port number. When the client requests aconnection, the server opens the socket connection with theaccept() method.

● The client establishes a connection with host on port port#.

● Both the client and server communicate by using an InputStreamand an OutputStream.

Server

ServerSocket (port #)

OutputStream

InputStream

Socket.close()

Client

Socket (host, port#)

OutputStream

InputStream

Socket.close()

Register withthis service

Wait for aconnection

(Attempt to connect)Socket()

ServerSocket.accept()

13-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 321: Sl275 Sg

Minimal TCP/IP Server

Minimal TCP/IP Server

TCP/IP server applications rely on the ServerSocket and Socketnetworking classes provided by the Java programming language. TheServerSocket class takes most of the work out of establishing a serverconnection.

1 import java.net.*;2 import java.io.*;34 public class SimpleServer {5 public static void main(String args[]) {6 ServerSocket s = null;78 // Register your service on port 54329 try {10 s = new ServerSocket(5432);11 } catch (IOException e) {12 e.printStackTrace();13 }1415 // Run the listen/accept loop forever16 while (true) {17 try {18 // Wait here and listen for a connection19 Socket s1 = s.accept();2021 // Get output stream associated with the socket22 OutputStream s1out = s1.getOutputStream();23 BufferedWriter bw = new BufferedWriter(24 new OutputStreamWriter(s1out));2526 // Send your string!27 bw.write(“Hello Net World!\n”);2829 // Close the connection, but not the serversocket30 bw.close();31 s1.close();32 } catch (IOException e) {33 e.printStackTrace();34 } // end of try-catch35 } // end of while(true)36 } // end of main method37 } //end of SimpleServer program

Implementing Multi-Tier Applications Using Networking 13-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 322: Sl275 Sg

Minimal TCP/IP Client

Minimal TCP/IP Client

The client side of a TCP/IP application relies on the Socket class. Again,much of the work involved in establishing connections is performed bythe Socket class. The client attaches to the server, as presented in‘‘Minimal TCP/IP Server’’ on page 13-7, and then prints everything sentby the server to the console.

1 import java.net.*;2 import java.io.*;34 public class SimpleClient {5 public static void main(String args[]) {6 try {7 // Open your connection to a server, at port 54328 // localhost used here9 Socket s1 = new Socket(“127.0.0.1”, 5432);1011 // Get an input stream from the socket12 InputStream is = s1.getInputStream();13 InputStreamReader irs = new InputStreamReader(is);14 BufferedReader br = new BufferedReader(isr);15 // Read the input and print it to the screen16 System.out.println(br.readLine());1718 // When done, close the steam and connection19 br.close();20 s1.close();21 } catch (ConnectException connExc) {22 System.err.println(“Could not connect.”);23 } catch (IOException e) {24 // ignore25 } //end of try-catch26 } // end of main method27 } // end of SimpleClient program

13-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 323: Sl275 Sg

Minimal TCP/IP Client

The URLClass

Java programs can use the URL class to connect to a URL address to accesscontent pointed to by the URL. This class is part of the java.net package.The URL class provides several features to connect and retrieveinformation on the Internet.

The URL class can be used to create and parse a URL address, open aconnection pointed by the URL address, and read and write to theconnection.

Accessing Information From a URL

The following steps are usually associated with connecting to a URLtarget and accessing the URL target data.

● Create a URL object

● Parse the URL

● Connect to the URL target

● Read or write content to the URL connection

● Close the URL connection

The following sections provide more details about these steps.

Creating a URL

The URL class provides several constructors for creating the URL.Depending on the information available, any of these constructors can beused to create URLs.

The simplest option is to use an absolute URL address in the form of astring. For example,

URL sunAddress = new URL(“http://www.sun.com/products/index.jsp”);

The alternative to this is to specify the relative path rather than theabsolute path.

URL baseAddress = new URL(“http://www.sun.com/”);

URL sunAddress = new URL(baseAddress,”products/index.jsp”);

Implementing Multi-Tier Applications Using Networking 13-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 324: Sl275 Sg

Minimal TCP/IP Client

The advantage with this mechanism is that the same baseAddress can beused to access other pages in that baseAddress. For example

URL sunAddress = new URL(baseAddress,”software/index.jsp”);

The other forms of creating a URL object are useful when the protocol, hostname, and the required file name are known. If the port number for theprotocol is different from the default port number, another form of URLconstructor that takes the port number as the parameter can be used.

Parsing the URL

The URL class can be used to retrieve information about the URL. Forexample, Table 13-1 lists some of the methods of the URL class and thevalues returned when these methods are applied to the following URL:

http://onesearch.sun.com/search/onesearch/index.jsp?qt=JAVA&charset=UTF-8

Table 13-1 Example of Parsing a URL

Method Returns

String getProtocol() http

String getAuthority() onesearch.sun.com

String getHost() onesearch.sun.com

int getPort() -1

int getDefaultPort() 80

String getPath() /search/onesearch/index.jsp

String getQuery() qt=JAVA&charset=UTF-8

String getFile() /search/onesearch/index.jsp?qt=JAVA&charset=UTF-8

String getRef() null

Object getContent() sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@addbf1

String getUserInfo() null

13-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 325: Sl275 Sg

Minimal TCP/IP Client

Note – A URL need not have all the components described in Table 13-1.In such cases, the methods would return null values as shown inTable 13-1.

The getPort() method returned -1, because no port was defined in theURL. In this situation, the default port of 80 for the HTTP protocol wasreturned.

Note – Parsing a URL is an optional step you use to retrieve URLcomponent information from a specific URL.

Connecting to the URL Address

After the URL is created, the openConnection() method in the URL classcan be used to create the connection to the URL address.

URLConnection openConnection();

The openConnection method creates an instance of URLConnection thatrepresents the communication link to the URL.

The URLConnection class can be used to retrieve and manipulate severalconnection setup parameters such as connection time out, content lengthand type, time of access, protocol header fields, permissions, and usercaches.

After the connection is created using the openConnection method, theconnect() method in URLConnection is used to initiate the connection.

Reading and Writing Content to the Connection

You can use the getInputStream method and getOutputStreammethods in the URLConnection to read and write to the connection.Alternatively, use the openStream method in the URL class to open theconnection and return the stream.

After the stream is created, reading and writing to the stream is similar toreading and writing from any other streams such as files, memory, andpipes.

Implementing Multi-Tier Applications Using Networking 13-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 326: Sl275 Sg

Minimal TCP/IP Client

The following example uses the openStream method to open theconnection stream and read from the stream. Code 13-1 shows an exampleof establishing the connection and reading the content.

Code 13-1 URLExample Class

1 import java.net.*;2 import java.io.*;34 public class URLExample {5 public static void main(String[] args) throws Exception {6 String oneLine;7 URL url_address = new URL("http://www.sun.com/");8 BufferedReader br= new BufferedReader(9 new InputStreamReader(url_address.openStream()));10 while ((oneLine = br.readLine()) != null) {11 System.out.println(oneLine);12 }13 br.close();14 }15 }

The readLine() method reads each line from the opened stream andstores in the local variable oneLine. The println statement on line 11prints each line of the HTML code.

The sample output below shows only the first few lines that are printed tothe screen

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">

<!-- BEGIN A0 COMPONENT V.2 --><html lang="en-US"><head><meta http-equiv="content-type" content="text/html; charset=UTF-8"><title> Sun Microsystems </title><meta name="keywords" content="sun microsystems, sun, java, java

computing, solaris, sparc, unix, jini, computer systems, server, missioncritical, RAS, high availability, cluster, workgroup server, desktop,workstation, storage, backup solutions, network computer, networkcomputing, hardware, software, service, consulting, support, training,compiler, jdk, technical computing, scientific computing, highperformance, enterprise computing, staroffice, starportal, sun ray">

<meta name="description" content="Sun Microsystems, Inc. The NetworkIs The Computer[tm].">

<meta http-equiv="content-language" content="en-US">

13-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 327: Sl275 Sg

Minimal TCP/IP Client

<meta name="date" content="2006-03-14"><link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">

Note – Refer to the following URLhttp://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html for an example of writing to a URLConnection object.

Close the Connection

Similar to any other streams, the opened connection streams should beclosed immediately after reading from or writing to the streams.

Implementing Multi-Tier Applications Using Networking 13-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 328: Sl275 Sg
Page 329: Sl275 Sg

Module 14

ImplementingMultithreaded Applications

Objectives

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

● Define a thread

● Create separate threads in a Java technology program, controllingthe code and data that are used by that thread

● Control the execution of a thread and write platform-independentcode with threads

● Examine alternative ways to create threads

● Use synchronized to protect data from corruption

● Examine thread interaction

● Use wait and notify to communicate between threads

14-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 330: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following references provide additionalinformation on the topics described in this module:

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

● Bates, Sierra. Head First Java, Second Edition. O’Reilly Media. 2005.

● Goetz, Peierls, Bloch, Bowbeer, Holmes, Lea. Java Concurrency inPractice, First Edition. Addison-Wesley Professional. 2006.

14-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 331: Sl275 Sg

Threads

Threads

A simplistic view of a computer is that it has a CPU that performscomputations, memory that contains the program that the CPU executes,and memory that holds the data on which the program operates. In thisview, there is only one job performed. A more complete view of mostmodern computer systems provides for the possibility of performingmore than one job at the same time.

You do not need to be concerned with how multiple-job performance isachieved, just consider the implications from a programming point ofview. Performing more than one job is similar to having more than onecomputer. In this module, a thread, or execution context, is considered to bethe encapsulation of a virtual CPU with its own program code and data.The class java.lang.Thread enables you to create and control threads.

Note – This module uses the term Thread when referring to the classjava.lang.Thread and thread when referring to an execution context.

A thread, or execution context, is composed of three main parts (asillustrated in Figure 14-1):

● A virtual CPU

● The code that the CPU executes

● The data on which the code works

Figure 14-1 A Thread

Code can be shared by multiple threads, independent of data. Twothreads share the same code when they execute code from instances of thesame class.

Likewise, data can be shared by multiple threads, independent of code.Two threads share the same data when they share access to a commonobject.

CPU

Code Data

A thread orexecution context

Implementing Multithreaded Applications 14-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 332: Sl275 Sg

Threads

In Java programming, the virtual CPU is encapsulated in an instance ofthe java.lang.Thread class. When a thread is constructed, the code andthe data that define its context are specified by the object passed to itsconstructor.

Creating the Thread

This section examines how you create a thread, and how you useconstructor arguments to supply the code and data for a thread when itruns.

A Thread constructor takes an argument that is an instance of Runnable.An instance of Runnable is made from a class that implements theRunnable interface (that is, it provides a public void run() method).

For example:

1 public class ThreadTester {2 public static void main(String args[]) {3 HelloRunner r = new HelloRunner();4 Thread t = new Thread(r);5 t.start();6 }7 }89 class HelloRunner implements Runnable {10 public void run() {11 int i = 0;12 while (true) {13 System.out.println(“Hello “ + i++);14 if ( i == 50 ) {15 break;16 }17 }18 }19 }

First, the main method constructs an instance, r, of class HelloRunner.Instance r has its own data, in this case the integer i. Because theinstance, r, is passed to the Thread class constructor, r’s integer i is thedata with which the thread works when it runs. The thread always beginsexecuting at the run method of its loaded Runnable instance (r in thisexample).

14-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 333: Sl275 Sg

Threads

A multithreaded programming environment enables you to createmultiple threads based on the same Runnable instance. You can do this asfollows:

Thread t1 = new Thread(r);Thread t2 = new Thread(r);

In this case, both threads share the same data and code.

To summarize, a thread is referred to through an instance of a Threadobject. The thread begins execution at the start of a loaded Runnableinstance’s run method. The data that the thread works on is taken fromthe specific instance of Runnable, which is passed to that Threadconstructor (Figure 14-2).

Figure 14-2 Thread Creation

Starting the Thread

A newly created thread does not start running automatically. You mustcall its startmethod. For example, you can issue the following commandas on Line 5 of the previous example:

t.start();

Calling start places the virtual CPU embodied in the thread into arunnable state, meaning that it becomes viable for scheduling forexecution by the JVM. This does not necessarily mean that the thread runsimmediately.

CPU

Code DataHelloRunner Instance “r”

Thread t}New Thread

Class of HelloRunner

Implementing Multithreaded Applications 14-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 334: Sl275 Sg

Threads

Thread Scheduling

Usually, in Java technology threads are preemptive, but not necessarilytime-sliced (the process of giving each thread an equal amount of CPUtime). It is a common mistake to believe that preemptive is another wordfor does time-slicing.

The model of a preemptive scheduler is that many threads might berunnable, but only one thread is running. This thread continues to rununtil it ceases to be runnable or until another thread of higher prioritybecomes runnable. In the latter case, the lower priority thread is preemptedby the thread of higher priority, which gets a chance to run instead.

A thread might cease to be runnable (that is, become blocked) for a varietyof reasons. The thread’s code can execute a Thread.sleep() call, askingthe thread to pause deliberately for a fixed period of time. The threadmight have to wait to access a resource and cannot continue until thatresource becomes available.

All threads that are runnable are kept in pools according to priority. Whena blocked thread becomes runnable, it is placed back into the appropriaterunnable pool. Threads from the highest priority non-empty pool aregiven CPU time.

A Thread object can exist in several different states throughout its lifetimeas shown in Figure 14-3.

Figure 14-3 Fundamental Thread State Diagram

Although the thread becomes runnable, it does not always start runningimmediately. Only one action at a time is performed on a machine withone CPU. The following paragraphs describe how the CPU is allocatedwhen more than one thread is runnable.

Runnable

New Dead

RunningScheduler

Blocked

Unblocked Event Blocked

run() Completesstart()

14-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 335: Sl275 Sg

Threads

Given that Java technology threads are not necessarily time-sliced, youmust ensure that the code for your threads gives other threads a chance toexecute from time to time. This can be achieved by issuing the sleep callat various intervals, as shown in Code 14-1.

Code 14-1 Thread Scheduling Example

1 public class Runner implements Runnable {2 public void run() {3 while (true) {4 // do lots of interesting stuff5 // ...6 // Give other threads a chance7 try {8 Thread.sleep(10);9 } catch (InterruptedException e) {10 // This thread’s sleep was interrupted11 // by another thread12 }13 }14 }15 }

Code 14-1 shows how the try and catch block is used. TheThread.sleep() and other methods that can pause a thread for periodsof time are interruptible. Threads can call another thread’s interruptmethod, which signals the paused thread with anInterruptedException.

The sleep is a static method in the Thread class, because it operates onthe current thread and is referred to as Thread.sleep(x). The sleepmethod’s argument specifies the minimum number of milliseconds forwhich the thread must be made inactive. Alternatively, an overloadedversion of the sleep method allows you to specify the time in nanosecond accuracy. (However, the accuracy provided by these methodsdepends on the system timers and schedulers). The execution of thethread does not resume until after this period unless it is interrupted, inwhich case execution is resumed earlier.

Terminating theThread

When a thread completes execution and terminates, it cannot run again.

Implementing Multithreaded Applications 14-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 336: Sl275 Sg

Threads

You can stop a thread by using a flag that indicates that the run methodshould exit.

1 public class Runner implements Runnable {2 private boolean timeToQuit=false;34 public void run() {5 while ( ! timeToQuit ) {6 // do work until we are told to quit7 }8 // clean up before run() ends9 }1011 public void stopRunning() {12 timeToQuit=true;13 }14 }

1 public class ThreadController {2 private Runner r = new Runner();3 private Thread t = new Thread(r);45 public void startThread() {6 t.start();7 }89 public void stopThread() {10 // use specific instance of Runner11 r.stopRunning();12 }13 }

Within a particular piece of code, you can obtain a reference to the currentthread using the static currentThreadmethod in the java.lang.Threadclass. For example:

1 public class NameRunner implements Runnable {2 public void run() {3 while (true) {4 // lots of interesting stuff5 }6 // Print name of the current thread7 System.out.println("Thread "+Thread.currentThread().getName()+ " completed");8 }9 }

14-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 337: Sl275 Sg

Basic Control of Threads

Basic Control of Threads

This section describes how to control threads.

Testing Threads

A thread can be in an unknown state. Use the method isAlive todetermine if a thread is still viable. The term Alive does not imply that thethread is running; it returns true for a thread that has been started buthas not completed its task.

Accessing Thread Priority

Use the getPriority method to determine the current priority of thethread. Use the setPrioritymethod to set the priority of the thread. Thepriority is an integer value. The Thread class includes the followingconstants:

Thread.MIN_PRIORITY = 1Thread.NORM_PRIORITY = 5Thread.MAX_PRIORITY = 10

The default priority is NORM_PRIORITY.

Putting Threads on Hold

Mechanisms exist that can temporarily block the execution of a thread.You can resume execution as if nothing happened. The thread appears tohave executed an instruction very slowly.

The Thread.sleep() Method

The sleep method is one way to halt a thread for a period of time. Recallthat the thread does not necessarily resume its execution at the instantthat the sleep period expires. This is because some other thread could beexecuting at that instant and might not be unscheduled unless one of thefollowing occurs:

● The thread waking up is of a higher priority.

● The running thread blocks for some other reason.

Implementing Multithreaded Applications 14-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 338: Sl275 Sg

Basic Control of Threads

The joinMethod

The join method causes the current thread to wait until the thread onwhich the join method is called terminates. For example:

1 public static void main(String[] args) {2 Thread t = new Thread(new Runner());3 t.start();4 ...5 // Do stuff in parallel with the other thread for a while6 ...7 // Wait here for the timer thread to finish8 try {9 t.join();10 } catch (InterruptedException e) {11 // t came back early12 }13 ...14 // Now continue in this thread15 ...16 }

Overloaded versions of the join method are available. These versionswhich allow you to specify the minimum time that the thread shouldwait. You can call the join method with a time-out value in milliseconds.For example:

void join(long millisec);

For this example, the join method either suspends the current thread fortimeout milliseconds or until the termination of the thread for which it iswaiting.

You can also call the join method with a time-out value in nanosecondsprecision. For example:

void join(long millisec, int nanosec);

Note – Although similar to the sleepmethods, the time accuracy of thesejoin methods also depends on the operating system timers andschedulers.

Similar to sleep, join also responds to an interrupt, and exits with anInterruptedException.

14-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 339: Sl275 Sg

Basic Control of Threads

The Thread.yield()Method

Use the method Thread.yield() to give other runnable threads a chanceto execute. If other threads are runnable, yield places the calling threadinto the runnable pool and allows another runnable thread to run. If noother threads are runnable, yield does nothing.

A sleep call gives threads of lower priority a chance to execute. Theyield method gives other runnable threads a chance to execute.

Implementing Multithreaded Applications 14-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 340: Sl275 Sg

Alternative Way to Create Threads

Alternative Way to Create Threads

So far, you have seen how you can create thread contexts with a separateclass that implements Runnable. In fact, this is not the only possibleapproach. The Thread class implements the Runnable interface itself, soyou can create a thread by creating a class that extends Thread rather thanimplements Runnable.

1 public class MyThread extends Thread {2 public void run() {3 while ( true ) {4 // do lots of interesting stuff5 try {6 Thread.sleep(100);7 } catch (InterruptedException e) {8 // sleep interrupted9 }10 }11 }1213 public static void main(String args[]) {14 Thread t = new MyThread();15 t.start();16 }17 }

14-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 341: Sl275 Sg

Alternative Way to Create Threads

Selecting a Way to Create Threads

Given a choice of approaches to creating a thread, how can you decidebetween them? Each approach has its advantages, which are described inthis section.

The following describes the advantages of implementing Runnable:

● From an object-oriented design point of view, the Thread class isstrictly an encapsulation of a virtual CPU and, as such, it should beextended only when you change or extend the behavior of that CPUmodel. Because of this and the value of making the distinctionbetween the CPU, code, and data parts of a running thread, thiscourse module has used this approach.

● Because Java technology permits single inheritance only, you cannotextend any other class, such as Applet, if you extended Threadalready. In some situations, this forces you to take the approach ofimplementing Runnable.

● Because there are times when you are obliged to implementRunnable, you might prefer to be consistent and always do it thisway.

The advantage of extending Thread is that the code tends to be simpler.

Note – While both techniques are possible, you should consider verycarefully why you would extend Thread. Do so only when you change orextend the behavior of a thread, not when you implement a run method.

Implementing Multithreaded Applications 14-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 342: Sl275 Sg

Using the synchronizedKeyword

Using the synchronizedKeyword

When multiple threads access shared data, there is a possibility for thedata to be corrupted. for example, one thread might update the shareddata, and before it is complete the other thread might read the same data,which is inconsistent. A synchronization mechanism is used to preventthese kinds of errors. The next subsection explains the problem in moredetail.

This section describes the use of the synchronized keyword. It providesthe Java programming language with a mechanism that enables aprogrammer to control threads that are sharing data.

The Problem

Imagine a class that represents a stack. This class might appear first as:

1 public class MyStack {2 int idx = 0;3 char [] data = new char[6];45 public void push(char c) {6 data[idx] = c;7 idx++;8 }910 public char pop() {11 idx--;12 return data[idx];13 }14 }

The class makes no effort to handle the overflow or underflow of thestack, and the stack capacity is limited. However, these aspects are notrelevant to this discussion.

The behavior of this model requires that the index value contains thearray subscript of the next empty cell in the stack. The predecrement,postincrement approach generates this information.

Imagine now that two threads have a reference to a single instance of thisclass. One thread is pushing data onto the stack and the other, more orless independently, is popping data off of the stack. In principle, the datais added and removed successfully. However, there is a potential problem.

14-14 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 343: Sl275 Sg

Using the synchronizedKeyword

Suppose thread a is adding characters and thread b is removingcharacters. Thread a has just deposited a character, but has not yetincremented the index counter. For some reason, this thread is nowpreempted. At this point, the data model represented in the object isinconsistent.

buffer |p|q|r| | | |idx = 2 ^

Specifically, consistency requires either idx = 3 or that the character hasnot yet been added.

If thread a resumes execution, there might be no damage, but supposethread b was waiting to remove a character. While thread a is waiting foranother chance to run, thread b gets its chance to remove a character.

There is an inconsistent data situation on entry to the pop method, yet thepop method proceeds to decrement the index value.

buffer |p|q|r| | | |idx = 1 ^

This effectively serves to ignore the character r. After this, it then returnsthe character q. So far, the behavior has been as if the letter r had not beenpushed, so it is difficult to say that there is a problem. But look at whathappens when the original thread, a, continues to run.

Thread a picks up where it left off, in the push method, and it proceeds toincrement the index value. Now you have the following:

buffer |p|q|r| | | |idx = 2 ^

This configuration implies that the q is valid and the cell containing r isthe next empty cell. In other words, q is read as having been placed intothe stack twice, and the letter r never appears.

This is a simple example of a general problem that arises when multiplethreads are accessing shared data. You need a mechanism to ensure thatshared data is in a consistent state before any thread starts to use it for aparticular task.

One approach would be to prevent thread a from being switched out untilit completes the critical section of code. This approach is common inlow-level machine programming but is generally inappropriate inmultiuser systems.

Implementing Multithreaded Applications 14-15Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 344: Sl275 Sg

Using the synchronizedKeyword

Another approach, and the one on which Java technology works, is toprovide a mechanism to treat the data delicately. This approach provides athread atomic with access to data regardless of whether that thread getsswitched out in the middle of performing that access.

The Object Lock Flag

In Java technology, every object has a flag associated with it. You canthink of this flag as a lock flag. The keyword synchronized enablesinteraction with this flag, and provides exclusive access to code thataffects shared data. The following is the modified code fragment:

public class MyStack {...public void push(char c) {synchronized(this) {data[idx] = c;idx++;

}}...

}

When the thread reaches the synchronized statement, it examines theobject passed as the argument, and tries to obtain the lock flag from thatobject before continuing (see Figure 14-4).

Figure 14-4 Using the synchronized Statement Before a Thread

Object this

public void push(char c) {synchronized (this) {data[idx] = c;idx++;

}}

Thread before synchronized(this)

Code orBehavior

Data orState

14-16 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 345: Sl275 Sg

Using the synchronizedKeyword

An example of using the synchronized statement after a thread is shownin Figure 14-5.

Figure 14-5 Using the synchronized Statement After a Thread

You should realize that this does not protect the data. If the popmethod ofthe shared data object is not protected by synchronized, and pop isinvoked by another thread, there is still a risk of damaging the consistency ofthe data. All methods accessing shared data must synchronize on the samelock if the lock is to be effective.

Figure 14-6 illustrates what happens if pop is protected by synchronizedand another thread tries to execute an object’s pop method while theoriginal thread holds the synchronized object’s lock flag.

Figure 14-6 Thread Trying to Execute synchronized

When the thread tries to execute the synchronized(this) statement, ittries to take the lock flag from the object this. Because the flag is notpresent, the thread cannot continue execution. The thread then joins apool of waiting threads that are associated with that object‘s lock flag.When the flag is returned to the object, a thread that was waiting for theflag is given it, and the thread continues to run.

Object this

public void push(char c) {synchronized (this) {data[idx] = c;idx++;

}}

Thread after synchronized(this)

Code orBehavior

Data orState

Object this

public char pop() {synchronized (this) {idx--;return data[idx];

}}

Another thread, trying to

Waiting for

Lock flag missing

object lock

Code orBehavior

Data orState

execute synchronized(this)

Implementing Multithreaded Applications 14-17Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 346: Sl275 Sg

Using the synchronizedKeyword

Releasing the Lock Flag

A thread waiting for the lock flag of an object cannot resume runninguntil the flag is available. Therefore, it is important for the holding threadto return the flag when it is no longer needed.

The lock flag is given back to its object automatically. When the threadthat holds the lock passes the end of the synchronized code block forwhich the lock was obtained, the lock is released. Java technology ensuresthat the lock is always returned automatically, even if an encounteredexception, a break statement, or a return statement transfers codeexecution out of a synchronized block. Also, if a thread executes nestedblocks of code that are synchronized on the same object, that object’s flagis released correctly on exit from the outermost block and the innermostblock is ignored.

These rules make using synchronized blocks much simpler to managethan equivalent facilities in some other systems.

14-18 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 347: Sl275 Sg

Using the synchronizedKeyword

Using the synchronizedMechanism

The synchronized mechanism works only if all access to delicate dataoccurs within the synchronized blocks.

You should mark delicate data protected by synchronized blocks asprivate. If you do not do this the delicate data can be accessed from codeoutside the class definition; such a situation would enable otherprogrammers to bypass your protection and cause data corruption atruntime.

A method consisting entirely of code belonging in a block synchronized tothis instance might put the synchronized keyword in its header. Thefollowing two code fragments are equivalent:

public void push(char c) { synchronized(this) { // The push method code }}

public synchronized void push(char c) {// The push method code

}

Why use one technique instead of the other?

If you use synchronized as a method modifier, the whole methodbecomes a synchronized block. That can result in the lock flag being heldlonger than necessary.

However, marking the method in this way permits users of the method toknow, from javadoc utility-generated documentation, thatsynchronization is taking place. This can be important when designingagainst deadlock (which is described in the following section). Thejavadoc documentation generator propagates the synchronizedmodifier into documentation files, but it cannot do the same forsynchronized(this), which is found inside the method’s block.

Implementing Multithreaded Applications 14-19Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 348: Sl275 Sg

Using the synchronizedKeyword

Thread States

Synchronization is a special thread state. Figure 14-7 illustrates the newstate transition diagram for a thread.

Figure 14-7 Thread State Diagram With Synchronization

Deadlock

In programs where multiple threads are competing for access to multipleresources, a condition known as deadlock can occur. This occurs when onethread is waiting for a lock held by another thread, but the other thread iswaiting for a lock already held by the first thread. In this condition,neither thread can proceed until after the other has passed the end of itssynchronized block. Because neither thread is able to proceed, neithercan pass the end of its block.

Java technology neither detects nor attempts to avoid this condition. It isthe responsibility of the programmer to ensure that a deadlock cannotarise. A general rule of thumb for avoiding a deadlock is: If you havemultiple objects that you want to have synchronized access to, make aglobal decision about the order in which you will obtain those locks, andadhere to that order throughout the program. Release the locks in thereverse order that you obtained them.

Blocked inObject’s

Lock Pool

Runnable

New Dead

RunningScheduler

Blocked

Unblocked Event Blocked

run() Completes

Lock Acquired Synchronized

start()

14-20 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 349: Sl275 Sg

Thread Interaction

Thread Interaction

Different threads are created specifically to perform unrelated tasks.However, sometimes the jobs they perform are related in some way and itmight be necessary to program some interactions between them.

Scenario

Consider yourself and a cab driver as two threads. You need a cab to takeyou to a destination and the cab driver wants to take on a passenger tomake a fare. So, each of you has a task.

The Problem

You expect to get into a cab and rest comfortably until the cab drivernotifies you that you have arrived at your destination. It would beannoying, for both you and the cab driver, to ask every 2 seconds, “Arewe there yet?” Between fares, the cab driver wants to sleep in the cab untila passenger needs to be driven somewhere. The cab driver does not wantto have to wake up from this nap every 5 minutes to see if a passenger hasarrived at the cab stand. So, both threads would prefer to get their jobsdone in as relaxed a manner as possible.

The Solution

You and the cab driver require some way of communicating your needs toeach other. While you are busy walking down the street toward the cabstand, the cab driver is sleeping peacefully in the cab. When you notifythe cab driver that you want a ride, the driver wakes up and beginsdriving, and you get to relax. After you arrive at your destination, the cabdriver notifies you to get out of the cab and go to work. The cab drivernow gets to wait and nap again until the next fare comes along.

The wait and notifyMethods

The java.lang.Object class provides two methods, wait and notify,for thread communication. If a thread issues a wait call on a rendezvousobject x, that thread pauses its execution until another thread issues anotify call on the same rendezvous object x.

Implementing Multithreaded Applications 14-21Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 350: Sl275 Sg

Thread Interaction

In the previous scenario, the cab driver waiting in the cab translates to thecab driver thread executing a cab.wait call, and your need to use the cabtranslates to the you thread executing a cab.notify() call.

For a thread to call either wait or notify on an object, the thread musthave the lock for that particular object. In other words, wait and notifyare called only from within a synchronized block on the instance onwhich they are being called. For this example, you require a block startingwith synchronized(cab) to permit either the cab.wait or thecab.notify() call.

The Pool Story

When a thread executes synchronized code that contains a wait call on aparticular object, that thread is placed in the wait pool for that object.Additionally, the thread that calls wait releases that object’s lock flagautomatically. You can invoke different wait methods.

wait()wait(long timeout)wait(long timeout, int nanos)

When a notify call is executed on a particular object, an arbitrary threadis moved from that object’s wait pool to a lock pool, where threads stayuntil the object’s lock flag becomes available. The notifyAll methodmoves all threads waiting on that object out of the wait pool and into thelock pool. Only from the lock pool can a thread obtain that object’s lockflag, which enables the thread to continue running where it left off whenit called wait.

In many systems that implement the wait-notify mechanism, the threadthat wakes up is the one that has waited the longest. However, Javatechnology does not guarantee this.

You can issue a notify call without regard to whether any threads arewaiting. If the notify method is called on an object when no threads areblocked in the wait pool for that object’s lock flag, the call has no effect.Calls to notify are not stored.

14-22 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 351: Sl275 Sg

Thread Interaction

Thread States

The wait pool is also a special thread state. Figure 14-8 illustrates the finalstate transition diagram for a thread.

Figure 14-8 Thread States Diagram With wait and notify

Blocked inObject’s

Wait Poolnotify() or

Blocked inObject’s

Lock Pool

Runnable

New Dead

RunningScheduler

Blocked

Unblocked Event Blocked

run() Completes

Lock Acquired Synchronized

interrupt()

wait()[Must have lock]/Releases lock

start()

Implementing Multithreaded Applications 14-23Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 352: Sl275 Sg

Thread Interaction

Monitor Model for Synchronization

Coordination between two threads needing access to common data can getcomplex. You must ensure that no thread leaves shared data in aninconsistent state when there is the possibility that any other thread canaccess that data. You also must ensure that your program does notdeadlock, because threads cannot release the appropriate lock when otherthreads are waiting for that lock.

In the cab example, the code relied on one rendezvous object, the cab, onwhich wait and notify were executed. If someone was expecting a bus,you would need a separate bus object on which to apply notify.Remember that all threads in the same wait pool must be satisfied bynotification from that wait pool’s controlling object. Never design codethat puts threads expecting to be notified for different conditions in thesame wait pool.

14-24 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 353: Sl275 Sg

Putting It Together

Putting It Together

The code in this section is an example of thread interaction thatdemonstrates the use of wait and notify methods to solve a classicproducer-consumer problem.

Start by looking at the outline of the stack object and the details of thethreads that access it. Then look at the details of the stack and themechanisms used to protect the stack’s data and to implement the threadcommunication based on the stack’s state.

The example stack class, called SyncStack to distinguish it from the coreclass java.util.Stack, offers the following public API:

public synchronized void push(char c);public synchronized char pop();

Implementing Multithreaded Applications 14-25Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 354: Sl275 Sg

Putting It Together

The ProducerThread

The producer thread generates new characters to be placed on the stack.Code 14-2 shows the Producer class.

Code 14-2 The Producer Class

1 package mod14;2 public class Producer implements Runnable {3 private SyncStack theStack;4 private int num;5 private static int counter = 1;67 public Producer (SyncStack s) {8 theStack = s;9 num = counter++;10 }1112 public void run() {13 char c;14 for (int i = 0; i < 200; i++) {15 c = (char)(Math.random() * 26 +’A’);16 theStack.push(c);17 System.out.println(“Producer” + num + “: “ + c);18 try {19 Thread.sleep((int)(Math.random() * 300));20 } catch (InterruptedException e) {21 // ignore it22 }23 }24 } // END run method25 } // END Producer class

This example generates 200 random uppercase characters and pushesthem onto the stack with a random delay of 0–300 milliseconds betweeneach push. Each pushed character is reported on the console, along withan identifier for which producer thread is executing.

The ConsumerThread

The consumer thread removes characters from the stack.

14-26 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 355: Sl275 Sg

Putting It Together

Code 14-3 shows the Consumer class.

Code 14-3 The Consumer Class

1 package mod14;23 public class Consumer implements Runnable {4 private SyncStack theStack;5 private int num;6 private static int counter = 1;78 public Consumer (SyncStack s) {9 theStack = s;10 num = counter++;11 }1213 public void run() {14 char c;15 for (int i = 0; i < 200; i++) {16 c = theStack.pop();17 System.out.println(“Consumer” + num + “: “ + c);18 try {19 Thread.sleep((int)(Math.random() * 300));20 } catch (InterruptedException e) {21 // ignore it22 }23 }24 } // END run method2526 } // END Consumer class

This example collects 200 characters from the stack, with a random delayof 0–300 milliseconds between each attempt. Each popped character isreported on the console, along with an identifier to identify the consumerthread that is executing.

Now consider construction of the stack class. You are going to create astack that has a seemingly limitless size, using the ArrayList class. Withthis design, your threads have only to communicate based on whether thestack is empty.

Implementing Multithreaded Applications 14-27Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 356: Sl275 Sg

Putting It Together

The SyncStackClass

A newly constructed SyncStack object’s buffer should be empty. You canuse the following code to build your class:

public class SyncStack {

private List<Character> buffer= new ArrayList<Character>(400);

public synchronized char pop() {// pop code here

}

public synchronized void push(char c) {// push code here

}}

There are no constructors. It is considered good style to include aconstructor, but it has been omitted here for brevity.

The popMethod

Now consider the push and popmethods. They must be synchronized toprotect the shared buffer. In addition, if the stack is empty in the popmethod, the executing thread must wait. When the stack in the pushmethod is no longer empty, waiting threads are notified. Code 14-4 showsthe pop method.

Code 14-4 The pop Method

1 public synchronized char pop() {2 char c;3 while (buffer.size() == 0) {4 try {5 this.wait();6 } catch (InterruptedException e) {7 // ignore it...8 }9 }10 c = buffer.remove(buffer.size()-1);11 return c;12 }

14-28 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 357: Sl275 Sg

Putting It Together

The wait call is made with respect to the stack object that shows how therendezvous is being made with a particular object. Nothing can be poppedfrom the stack when it is empty, so a thread trying to pop data from thestack must wait until the stack is no longer empty.

The wait call is placed in a try-catch block because an interrupt callcan terminate the thread’s waiting period. The waitmust also be within aloop for this example. If for some reason (such as an interrupt) the threadwakes up and discovers that the stack is still empty, then the thread mustre-enter the waiting condition.

The pop method for the stack is synchronized for two reasons. First,popping a character off of the stack affects the shared data buffer.Second, the call to this.wait() must be within a block that issynchronized on the stack object, which is represented by this.

The push method uses this.notify() to release a thread from the stackobject’s wait pool. After a thread is released, it can obtain the lock on thestack and continue executing the pop method, which removes a characterfrom the stack’s buffer.

Note – In pop, the wait method is called before any character is removedfrom the stack. This is because the removal cannot proceed until somecharacter is available.

You should also consider error checking. You might notice that there is noexplicit code to prevent a stack underflow. This is not necessary becausethe only way to remove characters from the stack is through the popmethod, and this method causes the executing thread to enter the waitstate if no character is available. Therefore, error checking is unnecessary.

The pushMethod

The push method is similar to the pop method. It affects the shared bufferand must also be synchronized. In addition, because the push methodadds a character to the buffer, it is responsible for notifying threads thatare waiting for a non-empty stack. This notification is done with respect tothe stack object.

Implementing Multithreaded Applications 14-29Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 358: Sl275 Sg

Putting It Together

Code 14-5 shows the push method.

Code 14-5 The push Method

1 public synchronized void push(char c) {2 this.notify();3 buffer.add(c);4 }5 }6

The call to this.notify() serves to release a single thread that calledwait because the stack is empty. Calling notify before the shared data ischanged is of no consequence. The stack object’s lock is released onlyupon exit from the synchronized block, so threads waiting for that lockcan obtain it while the stack data are being changed by the pop method.

Putting all of the pieces together, Code 14-6 shows the completeSyncStack class.

Code 14-6 The SyncStack Class

1 package mod13;23 import java.util.*;45 public class SyncStack {6 private List<Character> buffer7 = new ArrayList<Character>(400);89 public synchronized char pop() {10 char c;11 while (buffer.size() == 0) {12 try {13 this.wait();14 } catch (InterruptedException e) {15 // ignore it...16 }17 }18 c = buffer.remove(buffer.size()-1);19 return c;20 }2122 public synchronized void push(char c) {23 this.notify();24 buffer.add(c);25 }26 }

14-30 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 359: Sl275 Sg

Putting It Together

The SyncTestExample

You must assemble the producer, consumer, and stack code into completeclasses. A test harness is required to bring these pieces together. Payparticular attention to how SyncTest creates only one stack object that isshared by all threads. Code 14-7 shows the SyncTest class.

Code 14-7 The SyncTest Class

1 package mod14;23 public class SyncTest {4 public static void main(String[] args) {5 SyncStack stack = new SyncStack();6 Producer p1 = new Producer(stack);7 Thread prodT1 = new Thread (p1);8 prodT1.start();9 Producer p2 = new Producer(stack);10 Thread prodT2 = new Thread (p2);11 prodT2.start();12 Consumer c1 = new Consumer(stack);13 Thread consT1 = new Thread (c1);14 consT1.start();15 Consumer c2 = new Consumer(stack);16 Thread consT2 = new Thread (c2);17 consT2.start();18 }19 }

The following is an example of the output from java mod14.SyncTest.Every time this thread code is run, the results vary.

Producer2: FConsumer1: FProducer2: KConsumer2: KProducer2: TProducer1: NProducer1: VConsumer2: VConsumer1: NProducer2: VProducer2: UConsumer2: UConsumer2: VProducer1: F

Implementing Multithreaded Applications 14-31Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 360: Sl275 Sg

Putting It Together

Consumer1: FProducer2: MConsumer2: MConsumer2: T

14-32 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 361: Sl275 Sg

Module 15

BuildingJavaGUIs Using the SwingAPI

Objectives

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

● Describe the JFC Swing technology

● Define Swing

● Identify the Swing packages

● Describe the GUI building blocks: containers, components, andlayout managers

● Examine top-level, general-purpose, and special-purpose propertiesof container

● Examine components

● Examine layout managers

● Describe the Swing single-threaded model

● Build a GUI using Swing components

15-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 362: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following references provide additionalinformation on the topics described in this module:

Using all the functionality of JFC/Swing technology requires a lot morepractice and study. Some references for further study of JFC/Swingtechnology are:

● JFC/Swing technology tutorial in the free Java tutorials, located atthe following URL:

http://java.sun.com/docs/books/tutorial/

● The code of the SwingSet demo

● The API documentation

Start by studying the javax.swing package, and let that study leadyou as necessary to the sub-packages.

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

● Bates, Sierra. Head First Java, Second Edition. O’Reilly Media. 2005.

15-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 363: Sl275 Sg

Additional Resources

What Are the Java Foundation Classes (JFC)?

JFC, or Java Foundation Classes, is a set of Graphical User Interface (GUI)support packages that are available as part of the Java SE Platform andwhich became core application program interfaces (APIs) in JDK. As aresult of this, some of the boundaries between JFC and core JDK havebecome blurred, but for the purposes of this course, JFC includes thefollowing features:

● The Swing component set – Swing is an enhanced component set thatprovides replacement components for those in the original AWT anda number of more advanced components. These components enableyou to create user interfaces with the type of functionality that hasbecome expected in modern applications. Such components includetrees, tables, advanced text editors, and tear-off toolbars.

● 2D graphics – Using the Java 2D API, you can perform advanceddrawing, complex color manipulations, shape and transformation(rotate, shear, stretch, and so forth) handling, and treat text as shapesthat can be manipulated. 2D graphics are not discussed in thiscourse.

● Pluggable look-and-feel. This feature provides Swing components achoice of look-and-feel. The same program can be rendered inMicrosoft Windows, Motif, and Metal look-and-feel formats.

● Accessibility – National governments are increasingly mandatingthat computer programs used in their departments are accessible tothose with disabilities. The Swing component set facilitates suchprogramming by means of the accessibility APIs. It providesinterfaces for associative technologies, such as screen readers, screenmagnifiers, audible text readers (speech processing), and so on.

Building Java GUIs Using the Swing API 15-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 364: Sl275 Sg

Additional Resources

● Drag-and-drop – GUI-based data transfer, both between elements ofone program and between different programs, has been a feature ofmodern GUI systems for a number of years. This type of transferfalls into two forms from the user’s point of view. These are cut-and-paste and drag-and-drop. The Java JDK releases include support forboth these communications media.

● Internationalization – The JFC classes support different character setssuch as Japanese, Chinese, and Korean. This allows developers tobuild applications that can interact with users worldwide in theirown languages.

15-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 365: Sl275 Sg

Additional Resources

What Is Swing?

Swing is an enhanced component set that provides replacementcomponents for those in the original AWT and a number of moreadvanced components. These components enable you to create userinterfaces with the type of functionality that has become expected inmodern applications. Such components include trees, tables, advancedtext editors, and tear-off toolbars.

Swing also has special features. For example, using Swing, you can writea program that adopts either the look-and-feel of the host platform or thatuses a common look-and-feel written especially for the Java programminglanguage (Metal). In fact, you can create your own look-and-feel fromscratch, or modify an existing one and plug it in to your program, eitherhard-coded or by the user or system administrator selecting a look-and-feel at runtime.

Note – The term look-and-feel occurs frequently in this module. Lookrefers to appearance of components, while feel refers to the way they reactto user actions, such as mouse clicks. Writing a look-and-feel refers towriting the necessary classes to define new appearance and inputbehavior. Writing a look-and-feel is outside the scope of this module.

Pluggable Look-and-Feel

Pluggable look-and-feel enables developers to build applications thatexecute on any platform as if they were developed for that specificplatform. A program executed in the Microsoft Windows environmentappears as if it was developed for this environment; and the sameprogram executed on the UNIX platform appears as if it was developed for theUNIX environment.

Developers can create their own custom Swing components, with anykind of look-and-feel that they choose to design. This increases theconsistency of applications and applets deployed across platforms. Anentire application’s GUI can switch from one look-and-feel to a differentone at runtime.

Pluggable look-and-feel provided by the Swing components is facilitatedby their underlying architecture. The next section describes the Swingarchitecture and explains how it facilitates the pluggable look-and-feel.

Building Java GUIs Using the Swing API 15-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 366: Sl275 Sg

Additional Resources

Swing Architecture

Swing components are designed based on the Model-View-Controller(MVC) architecture. The Swing architecture is not strictly based on theMVC architecture but has its roots in the MVC.

Model-View-Controller Architecture

According to the MVC architecture, a component can be modeled as threeseparate parts. Figure 15-1 shows the MVC architecture.

● Model – The model stores the data used to define the component.

● View – The view represents the visual display of the component.This display is governed by the data in the model.

● Controller – The controller deals with the behavior of thecomponents when a user interacts with it. This behavior can includeany updates to the model or view.

Figure 15-1 Model-View-Controller Architecture

Theoretically, these three types of architecture (Model, View, Controller)should be represented by different class types. But, practically, this turnsout to be very difficult because of the dependencies between the view andthe controller. The role of the controller is heavily dependent on theimplementation of the view, because the user interacts with the view. Inother words, it is difficult to write a generic controller, independent of theimplementation of the view. This issue is addressed by the separablemodel architecture.

Separable Model Architecture

The Swing components follow a separable model architecture. In thisarchitecture the view and the controller are merged as a single compositeobject, because of their tight dependency on each other. The model objectis treated as a separate object just like in MVC architecture. Figure 15-2 onpage 15-7 shows the separable model architecture.

M V

C

15-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 367: Sl275 Sg

Additional Resources

Figure 15-2 Separable Model Architecture

The UI Object in Figure 15-2 is referred to as UI delegate. With thisarchitecture it is possible to delegate a few responsibilities of thecomponent to an independent UI Object. This explains how the pluggablelook-and-feel is facilitated by the Swing components. The componentsmake the visual appearance of the components the responsibility of theindependent UI Object. So the UI Object of the installed look-and-feel isresponsible for the components look-and-feel.

Component

UIObject

UIManagerM

Building Java GUIs Using the Swing API 15-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 368: Sl275 Sg

Swing Packages

Swing Packages

The Swing API has a rich and convenient set of packages that makes itpowerful and flexible. Table 15-1 lists each package name and the purposeof each package.

Table 15-1 Swing Packages

Package Name Purpose

javax.swing Provides a set of light-weightcomponents such as, JButton,JFrame, JCheckBox, and muchmore

javax.swing.border Provides classes and interfaces fordrawing specialized borders suchas, bevel, etched, line, matte, andmore

javax.swing.event Provides support for events firedby Swing components

javax.swing.undo Allows developers to providesupport for undo/redo inapplications such as text editors

javax.swing.colorchooser Contains classes and interfacesused by the JColorChoosercomponent

javax.swing.filechooser Contains classes and interfacesused by the JFileChoosercomponent

javax.swing.table Provides classes and interfaces forhandling JTable

javax.swing.tree Provides classes and interfaces forhandling JTree

javax.swing.plaf Provides one interface and manyabstract classes that Swing uses toprovide its pluggable look-and-feelcapabilities

javax.swing.plaf.basic Provides user interface objectsbuilt according to the Basic look-and-feel

15-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 369: Sl275 Sg

Swing Packages

javax.swing.plaf.metal Provides user interface objectsbuilt according to the Java look-and-feel

javax.swing.plaf.multi Provides user interface objects thatcombine two or more look-and-feels

javax.swing.plaf.synth Provides user interface objects fora skinnable look-and-feel in whichall painting is delegated

javax.swing.text Provides classes and interfaces thatdeal with editable and non-editable text components

javax.swing.text.html Provides the class HTMLEditorKitand supporting classes for creatingHTML text editors

javax.swing.text.html.parser Provides the default HTML parser,along with support classes

Table 15-1 Swing Packages (Continued)

Package Name Purpose

Building Java GUIs Using the Swing API 15-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 370: Sl275 Sg

Examining the Composition of a Java Technology GUI

Examining the Composition of a Java Technology GUI

A Swing API-based GUI is composed of the following elements.

● Containers

Containers are on top of the GUI containment hierarchy. All thecomponents in the GUI are added to these containers. JFrame,JDialog, JWindow, and JApplet are the top-level containers.

● Components

All the GUI components are derived from the JComponent class, forexample, JComboBox, JAbstractButton, and JTextComponent.

● Layout Managers

Layout managers are responsible for laying out components in acontainer. BorderLayout, FlowLayout, GridLayout are a fewexamples of the layout managers. There are more sophisticated andcomplex layout managers that give more control over the GUI.

15-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 371: Sl275 Sg

Examining the Composition of a Java Technology GUI

Figure 15-3 shows the use of components, containers, and layoutmanagers in the composition of the sample Swing user interface.

Figure 15-3 GUI Composition

ContainerComponents

Layout Managers

Building Java GUIs Using the Swing API 15-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 372: Sl275 Sg

Swing Containers

Swing Containers

Swing containers can be classified into three main categories

● Top-level containers

● General-purpose containers

● Special-purpose containers

Top-level Containers

Top-level containers are at the top of the Swing containment hierarchy.There are three top-level Swing containers: JFrame, JWindow, andJDialog. There is also a special class, JApplet, which, while not strictly atop-level container, is worth mentioning here because it should be used asthe top-level of any applet that uses Swing components. Figure 15-4shows the inheritance hierarchy of the top-level containers.

Figure 15-4 Top-Level Container Hierarchy

JApplet, JFrame, JDialog, and JWindow classes are directly derived fromApplet, Frame, Dialog, and Window classes, respectively. It is importantto note this because all the other Swing containers and components arederived from JComponents.

15-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 373: Sl275 Sg

Swing Containers

Table 15-2 contains a brief description of each top-level container.

Table 15-2 Top-level Containers

Container User Interface

A Frame is the basic window used inmost GUI applications. It has a borderand a title. Other components can beadded to the frame. You can also drawin the window. There is a provision toadd menus to the frame. Thejavax.swing.JFrame class is used tocreate frames.

JDialog is used to create a dialogwindow. The API provides severaldifferent versions of constructors fordefining dialogs. Dialogs aredependent on the frames. Dialogs canbe used to take input from the userand confirm any critical actions.Dialogs can be used to displaywarnings, errors, questions, andinformation to the user.

The JWindow container is similar toJFrame but it does not have a borderor title bar. There are no windowmanagement services.

The JApplet container is used tocreate a UI that is run in a webbrowser. Usually, JApplets areembedded in a web page and can beused to run animations. Othercomponents and menus can be addedto this container. You can also draw inan applet.

Building Java GUIs Using the Swing API 15-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 374: Sl275 Sg

Swing Containers

General-purpose Containers

General-purpose containers are intermediate containers, handy in severalcircumstances, for example: JPanel, JScrollPane, JToolBar,JSplitPane, and JTabbedPane. All of these components extendJComponent. Table 15-3 contains a brief description of each general-purpose container.

Table 15-3 General-purpose Containers

Container User interface

Panels are containers intowhich several componentscan be added. They alsoprovide a surface to drawon. Unlike JFrame, they arenot top-level containers.Panels should be containedin top-level containers. Thejavax.swing.JPanel classis used to create panels. Itextends JComponentand notjava.awt.Panel.

Scrollpanes are very handywhen the amount of space islimited. They are used todisplay large components orimages. Scrollpanes havetwo scrollbars, a row header,and a column header. Thejavax.swing.JScrollpaneclass is used to createscrollpanes.

Toolbars are a group ofbuttons with icons for easilyaccessing the frequentlyused functions. They can beconsidered as shortcuts tothe actions in menus. Thejavax.swing.JToolbarclass is used to createtoolbars.

15-14 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 375: Sl275 Sg

Swing Containers

Special-purpose Containers

JInternalFrame and JLayeredPane are examples of special-purposecontainers. They play specific roles in a user interface. Internal frames aredesigned to work within desktop panes. They are not top-level such asJFrame. The JLayeredPane container helps to specify the depth of thecomponent, which is helpful for rendering the GUI when componentsoverlap.

Splitpanes display two ormore components separatedby a divider. Componentscan be displayed side by sideor one over the other. Bydragging the divider theamount of space for eachcomponent can be adjusted.Thejavax.swing.JSplitPaneclass is used to createsplitpanes.

TabbedPanes are also usefulwhen the space is limited.Several tabs share the samespace. At any one time onlyone tab is visible. To bedisplayed, a tab needs to beselected by the user. Thejavax.swing.JTabbedPaneclass is used to createtabbedpanes.

Table 15-3 General-purpose Containers (Continued)

Container User interface

Building Java GUIs Using the Swing API 15-15Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 376: Sl275 Sg

Swing Containers

Table 15-4 contains a brief description of the special-purpose containers.

When using container classes, you should keep the following rules inmind:

● GUI components will only be displayed when they are in acontainment hierarchy. A containment hierarchy is a tree ofcomponents that has a top-level container as its root.

● A GUI component object instance can appear only once in acontainment tree. If a component in one container is added toanother container, the component will be moved to the lattercontainer and removed from the former.

Table 15-4 Special-purpose Containers

Containers User Interface

Internal frames are non top-levelcontainers. They contain featuressimilar to JFrames such asdragging, resizing, iconifying, andmaximizing. Internal frames arecreated using thejavax.swing.JInternalFrameclass, which is added toJDesktopPane and is, in turn,added to a JFrame. As with regularframes, components can be addedto a JInternalFrame.

Layered panes allow the additionof components at required depths.The depth is specified as an integervalue. Thejavax.swing.JLayeredPane classis used to create layered panes. Forconvenience, you can use thestandard layers defined by thisclass: DEFAULT_LAYER, thebottommost layer,PALETTE_LAYER,MODAL_LAYER,POPUP_LAYER,DRAG_LAYER the topmost layer.

15-16 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 377: Sl275 Sg

Swing Containers

● Each top-level container has a content pane that, generally speaking,contains (directly or indirectly) the visible components in that top-level container's GUI.

● You can optionally add a menu bar to a top-level container. Themenu bar is, by convention, positioned within the top-levelcontainer, but outside the content pane. Some look-and-feels, such asthe Mac look-and-feel, give you the option of placing the menu barin another place more appropriate for the look-and-feel, such as atthe top of the screen.

Each of these four containers (including JApplet) implements a specialinterface called RootPaneContainer. An in-depth examination of theRootPaneContainer is outside the scope of this module.

JFrameContainer Essentials

The JFrame container is the most commonly used top-level Swingcontainer. The JFrame container permits you to set one of four reactionsfor the Close Window menu button. These reactions are:

● DO_NOTHING_ON_CLOSE

● HIDE_ON_CLOSE

● DISPOSE_ON_CLOSE

● EXIT_ON_CLOSE

You set the option by invoking the setDefaultCloseOperationmethod on the JFrame instance.

Building Java GUIs Using the Swing API 15-17Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 378: Sl275 Sg

Swing Components

Swing Components

Swing GUIs use two kinds of classes: GUI classes and non-GUI supportclasses. The GUI classes are visual and descendants of JComponent, andare called J classes. The non-GUI classes provide services and performvital functions for GUI classes; however, they do not produce any visualoutput

Swing components primarily provide components for text handling,buttons, labels, lists, panes, combo boxes, scroll bars, scroll panes, menus,tables, and trees. Swing components can be broadly classified as follows:

● Buttons

● Text components

● Uneditable information display components

● Menus

● Formatted display components

● Other basic controls

15-18 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 379: Sl275 Sg

Swing Components

The Swing Component Hierarchy

Figure 15-5 illustrates the hierarchy relationships of the swingcomponents.

Figure 15-5 Swing Component Hierarchy

Note – The Swing components’ event handling classes are examples ofnon-GUI classes.

Building Java GUIs Using the Swing API 15-19Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 380: Sl275 Sg

Swing Components

Buttons

Regular buttons, checkboxes, and radio buttons are all considered to be inthe button category. Creating graphical buttons is straightforward if youuse an Icon object that defines the graphic you want displayed. TheJCheckBox class provides support for check box buttons. TheJRadioButton class behaves in such a way that turning on a radiobutton in a radio button group causes all the other radio buttons in thatgroup to be turned off. Table 15-5 describes each of these components andshows their user interface.

Table 15-5 Buttons

Component User Interface

JButton objects can be created with a simpleString argument to the constructor, in which casethey display that text as their label. Clicking on aJButton generates an ActionEvent. You mightwant to set the action command property of yourbutton so that the ActionEvent carries aparticular command string. If you create aJButton with text, the label text is used bydefault as the action command string. However, ifyou create a graphics-only button or if the defaultaction command string (which is the text label ofthe button) is not what you need, you can definethe action command explicitly using thesetActionCommand method.

Check boxes are similar to JButtons in that theycan be initialized with a simple String argumentto the constructor, in which case they display thattext as their label. But their selection model isdifferent, by convention. A check box has aboolean state value that can be in either on (true)or off (false). Clicking the check box toggles itsstate from on to off, or from off to on. Thejavax.swing.JCheckBox class is used to createcheck boxes.

15-20 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 381: Sl275 Sg

Swing Components

Text Components

Swing text components can be broadly divided into three categories.

● Text controls – JTextField, JPasswordField (for user input)

● Plain text areas – JTextArea (displays text in plain text, also formulti-line user input

● Styled text areas – JEditorPane, JTextPane (displays formattedtext)

Table 15-6 describes each of these components and shows their userinterface.

Individually, a JRadioButton simply toggles onand off each time it is selected, just like aJCheckBox. To obtain the mutual exclusionbehavior of a radio button, add the buttons to aButtonGroup instance. A button group is amanager that ensures that only one button isselected at one time. Use the ButtonGroup class tocreate a button group.

Table 15-5 Buttons (Continued)

Component User Interface

Table 15-6 Text Components

Component User Interface

Text areas are commonly used tocollect more than one line ofinformation from the user. Thejavax.swing.JTextArea class isused to create text areas. Whencreating a text area, you can specifythe number of rows, columns, andinitial content. Text areas displayplain text only.

Building Java GUIs Using the Swing API 15-21Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 382: Sl275 Sg

Swing Components

Text fields are also used to collectinput from the user. These aresimilar to text areas but they arerestricted to accept only one line oftext. Thejavax.swing.JTextField class isused to create text fields.

Editor panes are styled textcomponents. In addition to plaintext, editor panes can display andedit text in RTF and HTML format.Editor panes are commonly used todisplay help in HTML format. Thejavax.swing.JEditorPane class isused to create editor panes.

The javax.swing.JTextPane classinherits fromjavax.swing.JEditorPane. Inaddition to providing all thefeatures of the JEditorPane, theJTextPane class also allows forembedding components.

javax.swing.JPasswordField is atext input field specialized forpassword entry. For security, apassword field displays a charactersuch as an asterisk '*'. A passwordfield’s value is stored as an array ofcharacters, instead of a string. Likeany other text field object, apassword field sends an actionevent when you press the Enter key.

Table 15-6 Text Components (Continued)

Component User Interface

15-22 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 383: Sl275 Sg

Swing Components

Uneditable Information Display Components

Uneditable information display components are used to display moreinformation about the components. These components can be used onlyas display components. Table 15-7 describes some of these components.

Table 15-7 Uneditable Display Components

Component User Interface

Labels are used to display text onthe screen. They are uneditablecomponents. Thejavax.swing.JLabel class isused to create labels. Labels canalso be used to display images.

The javax.swing.JToolTipclass is helpful to displayinformation about thecomponents. JComponentprovides a method called thesetToolTipText, which can beused by all the components to setthe string that should bedisplayed.

Thejavax.swing.JProgressBarclass is very helpful in indicatingthe progress of any long-runningtasks.

Building Java GUIs Using the Swing API 15-23Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 384: Sl275 Sg

Swing Components

Menus

Menus behave similar to lists except, by convention, a menu typically isdisplayed either in a menu bar or as a popup menu. A menu bar cancontain one or more menus (called pull-down menus) and has anoperating system-dependent location, typically, at the top of eachwindow. A popup menu is displayed when the user triggers a platform-specific mouse button or keyboard sequence, for example, pressing theright mouse button, or rolling the mouse cursor over a popup-enabledcomponent. Table 15-8 describes each of these components and showstheir user interface.

Table 15-8 Menu Components

Component User interface

A menu bar contains the names ofone or more pull down menus.Clicking these names opens menuitems and submenus. Thejavax.swing.JMenu,javax.swing.JMenuItemclasses areused to create menus. Menu itemscan be selected by using keyboardmnemonics and accelerators. Menuitems could be of type checkboxesand radio buttons.

A popup menu is a menu that is notattached to the menu bar. Thesemenus are some times referred to ascontext menus. Thejavax.swing.JPopupMenu class isused to create popup menus.

15-24 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 385: Sl275 Sg

Swing Components

Formatted Display Components

Formatted display components are among the most complex componentsfound in Swing. Tables, trees, color chooser, and file chooser are a fewexamples in this category. Table 15-9 describes these components andshows their user interface.

Table 15-9 Formatted Display Component

Component User Interface

Tables are used to display and editinformation in the form of a grid.The javax.swing.JTable class isused to create tables. JTabledoes notstore the data, but only displays thedata from the table model.

JTree is used to display hierarchicalinformation. The data forconstructing the display is providedthrough a TreeModel instance. Thedata can also be provided as acollection of elements such as aHashtable or a Vector. A JTree doesnot actually store the data, but ratherpresents the data in the TreeModelinstance.

The JFileChooser class allows usersto navigate to the file system andchoose a file. The file choosercontains filter methods you can use tofilter the types of files displayed andmethods you can use to customizethe view presented by the filechooser.

Building Java GUIs Using the Swing API 15-25Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 386: Sl275 Sg

Swing Components

Other Basic Controls

This section describes other Swing components, such as combo boxes,lists, sliders, and spinners that are often used in GUIs. A JComboBox letsthe user choose one of several choices. The JComboBox class has aconvenient constructor that takes an array of objects to use as the initialchoices. You can add and remove choices using the addItem andremoveItem methods, respectively. A JList presents items in one ormore columns. You choose one or more items from the display by clickingor navigating with keyboard commands. With JSlider, you use a mouseclick and drag to enter a numeric value. A spinner is a possible alternativeto a slider when screen space is limited.

JColorChooser allows the user tomanipulate and select a color. A colorcan be selected in three differentways. Swatches, Hue, Saturation, andBrightness (HSB) or Red, Green, andBlue (RGB). The JColorChooserclass provides several constructorsfor creating the color-chooser pane.The default constructor creates apane with initial color as white.Another constructor takes the initialcolor as a parameter. You can alsospecify the color selection model inthe constructor.

Table 15-9 Formatted Display Component (Continued)

Component User Interface

15-26 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 387: Sl275 Sg

Swing Components

Table 15-10 describes each of these components and shows their userinterface.

Table 15-10Other Basic Controls

Component User Interface

JComboBoxhas two forms: Editableand UnEditable. The default form,uneditable, shows a button and adrop-down list of values. Theeditable form presents a text editfield with a selection button. Youcan type a value in the text field oruse the button to display a drop-down list of choices.

Lists can feature scrollbars if thenumber of items is too large todisplay in the allotted screen area.Lists can also be made resizable.The JList class is simple to use insimple circumstances, and cancreate its own ListModel ifneeded. To do this, you put thedata items into either a Vector oran array of Objects and invokethe JList constructor using thedata as an argument.

Spinners also allow you to type ina value. JSpinner has threesubcomponents: an up arrow, adown arrow, and an editor. Theeditor can be any JComponent,but, by default, it is implementedas a panel with formatted text field

Slider values have a finite range,that is, a minimum and maximumvalue. If the ability to specifyprecise numbers is important, aslider can be coupled with aformatted text field.

Building Java GUIs Using the Swing API 15-27Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 388: Sl275 Sg

Swing Components Properties

Swing Components Properties

This section describes properties of Swing components.

Common Component Properties

All the Swing components share some common properties because theyall extend the JComponent class. Table 15-11 shows a subset of thecommon properties that all Swing components inherit from JComponent.

Note – Some properties, such as preferred size, are hints to the layoutmanager. Although a component can provide the layout manager withhints, the layout manager can ignore these hints and use otherinformation to rendering the component.

Table 15-11Common Component Properties

Property Methods

Border Border getBorder()void setBorder(Border b)

Background and foregroundcolor

void setBackground(Color bg)void setForeground(Color bg)

Font void setFont(Font f)

Opaque void setOpaque(boolean isOpaque)

Maximum andminimum size

void setMaximumSize(Dimension d)void setMinimumSize(Dimension d)

Alignment void setAlignmentX(float ax)void setAlignmentY(float ay)

Preferred size void setPreferredSize(Dimensionps)

15-28 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 389: Sl275 Sg

Swing Components Properties

Component-Specific Properties

This section discusses component properties specifically takingJComboBox as an example. JComboBox inherits all the properties inJComponent and defines more specific properties. Table 15-12 describessome properties specific to JComboBox.

Table 15-12 Component Specific Properties

Properties Methods

Maximum row count void setMaximumRowCount(int count)

Model void setModal(ComboBoxModel cbm)

Selected index int getSelectedIndex()

Selected Item Object getSelectedItem()

Item count int getItemCount()

Renderer void setRenderer(ListCellRenderer ar)

Editable void setEditable(boolean flag)

Building Java GUIs Using the Swing API 15-29Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 390: Sl275 Sg

Layout Managers

Layout Managers

A layout manager determines the size and position of the componentswithin a container. The alternative to using layout managers is absolutepositioning by pixel coordinates. Absolute positioning is achievedthrough setting a container's layout property to null. Absolute positioningis not platform-portable. Issues such as the sizes of fonts and screensensure that a layout that is correct based on coordinates can potentially beunusable on other platforms.

Unlike absolute positioning, layout managers have mechanisms to copewith the following situations:

● The resizing of the GUI by the user

● Different fonts and font sizes used by different operating systems orby user customization

● The text layout requirements of different international locales (left-right, right-left, vertical)

To cope with these situations, layout managers lay out componentsaccording to a predetermined policy. For example, the policy of theGridLayout is to position child components in equal-sized cells, startingat the top left and working left to right, top to bottom until the grid is full.The following sections describe some of the layout managers that you canuse. Each section highlights the policy used by the layout manager underdiscussion.

The BorderLayout Layout Manager

BorderLayout arranges the components in five different regions.CENTER, NORTH, SOUTH, EAST, and WEST. The border layoutmanager limits the number of components added to each region to one.

The position of the component should be specified. If no position isspecified, by default the component is added to the CENTER. All theextra space left is used by the component in the CENTER.

BorderLayout is the default layout for JFrame, JDialog, and JApplet.Figure 15-6 on page 15-31 shows a display using a border layout. Thedisplay shows five JButtons added to a JFrame.

15-30 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 391: Sl275 Sg

Layout Managers

Figure 15-6 The BorderLayout Demo

The FlowLayout Layout Manager

FlowLayout arranges the components in a row. By default, it arranges thecomponents from LEFT_TO_RIGHT. This orientation can be changed usingthe ComponentOrientation property RIGHT_TO_LEFT. The vertical andhorizontal spacing between the components can be specified. If not, thedefault vertical and horizontal gap of five units is used. Figure 15-7 showsthe flow layout demo. Similar to the border layout demo, five JButtonsare added to the JFrame.

Figure 15-7 The FlowLayout Demo

The code below shows a demo of FlowLayout. It adds five buttons to theJFrame.

1 import javax.swing.*;2 import java.awt.*;34 public class LayoutExample {5 private JFrame f;6 private JButton b1;7 private JButton b2;8 private JButton b3;9 private JButton b4;10 private JButton b5;1112 public LayoutExample() {

Building Java GUIs Using the Swing API 15-31Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 392: Sl275 Sg

Layout Managers

13 f = new JFrame("GUI example");14 b1 = new JButton("Button 1");15 b2 = new JButton("Button 2");16 b3 = new JButton("Button 3");17 b4 = new JButton("Button 4");18 b5 = new JButton("Button 5");19 }2021 public void launchFrame() {22 f.setLayout(new FlowLayout());23 f.add(b1);24 f.add(b2);25 f.add(b3);26 f.add(b4);27 f.add(b5);28 f.pack();29 f.setVisible(true);30 }3132 public static void main(String args[]) {33 LayoutExample guiWindow = new LayoutExample();34 guiWindow.launchFrame();35 }3637 } // end of LayoutExample class

The BoxLayout Layout Manager

BoxLayout arranges the components either vertically or horizontally.

The BoxLayout constructor takes a parameter called axis, where thedirection to align the components should be specified. This parameter cantake any of the following values

● X_AXIS – Components are arranged horizontally from left to right.

● Y_AXIS – Components are arranged vertically from top to bottom.

● LINE_AXIS – Components are laid in the same direction as words ina line.

● PAGE_AXIS – Components are arranged in the same direction as thelines in a page.

15-32 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 393: Sl275 Sg

Layout Managers

Figure 15-8 shows a box layout demo. Similar to the border layout demo,five JButtons are added to the JFrame. The parameter used in thisexample for aligning the components was set to Y-AXIS.

Figure 15-8 The BoxLayout Demo

The CardLayout Layout Manager

CardLayout arranges the components as a stack of cards. Each cardaccepts a single component for display. By making this single componenta container, you can display multiple components in a card. Only one cardis visible at a time. Figure 15-9 illustrates the use of the card layoutmanager.

Figure 15-9 The CardLayout Demo

In the example shown in Figure 15-9, Button1, Button2, and Button3 arearranged on Card1 and Button4 and Button5 are arranged on Card2. Acombo box is used to select the card to be displayed.

Building Java GUIs Using the Swing API 15-33Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 394: Sl275 Sg

Layout Managers

The GridLayout Layout Manager

GridLayout arranges the components in rows and columns. Eachcomponent occupies the same amount of space in the container. Whencreating the grid layout, the number of rows and columns should bespecified. If not specified, by default, the layout manager creates one rowand one column. The vertical gap and the horizontal gap between thecomponents can also be specified. Figure 15-10 illustrates the use of theGridLayout. Similar to the border layout shown in Figure 15-6 onpage 15-31, five JButtons are added to the JFrame.

Figure 15-10 The GridLayout Demo

The GridBagLayout Layout Manager

GridBagLayout arranges the components in rows and columns, similar togrid layout, but provides a wide variety of flexibility options for resizingand positioning the components. This layout is used to design complexGUIs. The constraints on the components are specified using theGridBagConstraints class. Some of the constants in this class aregridwidth, gridheight, gridx, gridy, weightx, and weighty.Figure 15-11 illustrates the use of GridBagLayout. Five JButtons areadded to the JFrame. You can notice that the components are of differentsize and are positioned at very specific locations.

Figure 15-11 The GridBagLayout Demo

15-34 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 395: Sl275 Sg

Layout Managers

The GroupLayout Layout Manager

In addition to these layout managers, GroupLayout was added to Java SEversion 6. This layout manager was added for use by toolmakers. It is thelayout manager used in the NetBeans IDE GUI builder tool.

Building Java GUIs Using the Swing API 15-35Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 396: Sl275 Sg

GUI Construction

GUI Construction

A Java technology GUI can be created using either of the followingtechniques:

● Programmatic construction

This technique uses code to create the GUI. This technique is usefulfor learning GUI construction. However, it is very laborious for usein production environments.

● Construction using a GUI builder tool

This technique uses a GUI builder tool to create the GUI. The GUIdeveloper uses a visual approach to drag-and-drop containers andcomponents to a work area. The tool permits the positioning andresizing of containers and components using a pointer device such asa computer mouse. With each step, the tool automatically generatesthe Java technology classes required to reproduce the GUI.

Programmatic Construction

This sections describes creating a simple GUI that prints Hello World. Thecode shown in Code 15-1 creates a container JFrame with a titleHelloWorldSwing. It later adds a JLabel with the Accessible Nameproperty set to Hello World.

Code 15-1 The HelloWorldSwing Application

1 import javax.swing.*;2 public class HelloWorldSwing {3 private static void createAndShowGUI() {4 JFrame frame = new JFrame("HelloWorldSwing");5 //Set up the window.6 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);7 JLabel label = new JLabel("Hello World");8 // Add Label9 frame.add(label);10 frame.pack();11 // Display Window12 frame.setVisible(true);}1314 public static void main(String[] args) {15 javax.swing.SwingUtilities.invokeLater(new Runnable() {16 //Schedule for the event-dispatching thread:17 //creating,showing this app's GUI.

15-36 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 397: Sl275 Sg

GUI Construction

18 public void run() {createAndShowGUI();}19 });20 }21 }

Figure 15-12 shows the GUI interface that is generated by the code. Thedefault layout for JFrame is BorderLayout. So, by default, the componentJLabel is added to the center position of the container. Also note that thelabel occupies the entire frame, as the center component occupies all theremaining space in the container in the BorderLayout.

Figure 15-12 The HelloWorldString Output

Key Methods

This section explains the key methods used in Code 15-1 on page 15-36.The methods can be divided into two different categories.

1. Methods for setting up the frame and adding a label.

a. setDefaultLookAndFeelDecorated(true): This methodprovides a hint whether the created JFrames should havewindows decoration like borders, widgets, options to minimize,close, and enlarge windows.

b. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Thismethod defines the behavior of the JFrame when a closeoperation is initiated. There are four possible ways of handlingthis.

1. DO_NOTHING_ON_CLOSE: Does nothing when the closeoperation is initiated. This constant is defined inWindowsConstants.

JFrame

JLabel BorderLayoutFrameTitle

Building Java GUIs Using the Swing API 15-37Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 398: Sl275 Sg

GUI Construction

2. HIDE_ON_CLOSE: Invokes any WindowListener objects andhides the frame. This constant is defined inWindowConstants.

3. DISPOSE_ON_CLOSE: Invokes any WindowListener objectsand hides and disposes the frame. This constant is definedin WindowConstants.

4. EXIT_ON_CLOSE: Exits the application. This constant isdefined in the JFrame class.

c. pack(): JFrame inherits this method from java.awt.Window.This method helps to resize the window, so that all thecomponents’ layout and their preferred sizes are preserved.

d. setVisible(true): When the JFrame is first created, it createsan invisible frame. To make the frame visible, the parameter forthe setVisible should be set to true. JFrame inherits thismethod from java.awt.Component.

e. add(Component c): This method adds the components to thecontainer. JFrame inherits this method fromjava.awt.Component class. Five different overloaded methodsare defined in the java.awt.Component.

2. Methods for making the GUI thread-safe and efficient.

Several tasks are involved in displaying the GUI efficiently. Thesetasks can be broadly defined as:

a. Executing the application code.

This task involves starting the GUI application and executingthe code for rendering the GUI

b. Handling the events raised from the GUI:

Several events can be raised by the components in the GUI. Forexample, when a button is pressed an event is generated. Eventlisteners should be defined to handle this event. This taskdispatches the event to the appropriate listeners that handle theevent.

15-38 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 399: Sl275 Sg

GUI Construction

c. Handle some time-consuming processes:

Several activities might be time-consuming and they can be runin the background so that the GUI would be efficient andresponsive. These kinds of activities are handled by this task.

To handle these tasks efficiently, the Swing framework uses threadsthat are light-weight processes. The tasks described above can behandled by these threads separately and concurrently. Theprogrammer should utilize these threads. The Swing frameworkprovides a collection of utility methods in the SwingUtilities class.

● SwingUtilites.invokeLater(new Runnable()):

In the Java programming language, threads are created usingthe Runnable interface. This interface defines a method runthat should be implemented by all the classes using thisinterface. The invokeLatermethod schedules the GUI creationtask to execute the run method asynchronously by the event-handling thread after all the pending events are completed.

Building Java GUIs Using the Swing API 15-39Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 400: Sl275 Sg
Page 401: Sl275 Sg

Module 16

HandlingGUI-GeneratedEvents

Objectives

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

● Define events and event handling

● Examine the Java SE event model

● Describe GUI behavior

● Determine the user action that originated an event

● Develop event listeners

● Describe concurrency in Swing-based GUIs and describe the featuresof the SwingWorker class

16-1Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 402: Sl275 Sg

Additional Resources

Additional Resources

Additional resources – The following references provide additionalinformation on the topics described in this module:

● Arnold, Gosling, Holmes. The Java Programming Language, FourthEdition. Prentice-Hall. 2005.

● Zakhour, Hommel, Royal, Rabinovitch, Risser, Hoeber. The JavaTutorial: A Short Course on the Basics, Fourth Edition. Prentice-Hall.2006.

● Bates, Sierra. Head First Java, Second Edition. O’Reilly Media. 2005.

16-2 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 403: Sl275 Sg

What Is an Event?

What Is an Event?

When the user performs an action at the user interface level (clicks amouse or presses a key), this causes an event to be issued. Events areobjects that describe what has happened. A number of different types ofevent classes exist to describe different categories of user action.

Figure 16-1 shows an abstract view of the delegation event model. When auser clicks a GUI button, an event object is created by the JVM and thebutton sends this event to the event handler for that button by calling theactionPerformed method.

Figure 16-1 A User Action Triggers an Event

Event Sources

An event source is the generator of an event. For example, a mouse click ona JButton component generates an ActionEvent instance with thebutton as the source. The ActionEvent instance is an object that containsinformation about the events that just took place. The ActionEventcontains:

● getActionCommand, which returns the command name associatedwith the action

● getModifiers, which returns any modifiers held during the action

● getWhen, which returns the timestamp when the event occurred

● paramString, which returns a string identifying action and theassociated command

Event Handlers

An event handler is a method that receives an event object, deciphers it,and processes the user’s interaction.

JFrame

JPanel

JButton

The user clicks on the button

Some Event HandleractionPerformed(ActionEvent e) { ...}

ActionEvent

Handling GUI-Generated Events 16-3Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 404: Sl275 Sg

Java SE Event Model

Java SE Event Model

This section describes the delegation event model.

Delegation Model

The delegation event model came into existence with JDK version 1.1.With this model, events are sent to the component from which the eventoriginated, but it is up to each component to propagate the event to one ormore registered classes, called listeners. Listeners contain event handlersthat receive and process the event. In this way, the event handler can be inan object separate from the component. Listeners are classes thatimplement the EventListener interface. Figure 16-2 shows the eventdelegation model.

Figure 16-2 Delegation Event Model With Multiple Listeners

Events are objects that are reported only to registered listeners. Everyevent has a corresponding listener interface that mandates which methodsmust be defined in a class suited to receiving that type of event. The classthat implements the interface defines those methods, and can beregistered as a listener.

Events from components that have no registered listeners are notpropagated.

JFrame

JPanel

JButton

User clicks on button

Another Event Handler

One Event Handler

actionPerformed(ActionEvent e) { ...}

actionPerformed(ActionEvent e) { ...}ActionEvent

16-4 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 405: Sl275 Sg

Java SE Event Model

A Listener Example

For example, Code 16-1 shows the code for a simple JFrame with a singleJButton on it.

Code 16-1 The TestButton Example

1 import javax.swing.*;2 import java.awt.*;34 public class TestButton {5 private JFrame f;6 private JButton b;78 public TestButton() {9 f = new JFrame("Test");10 b = new JButton("Press Me!");11 b.setActionCommand("ButtonPressed");12 }1314 public void launchFrame() {15 b.addActionListener(new ButtonHandler());16 f.add(b,BorderLayout.CENTER);17 f.pack();18 f.setVisible(true);19 }2021 public static void main(String args[]) {22 TestButton guiApp = new TestButton();23 guiApp.launchFrame();24 }25 }

The ButtonHandler class, shown in Code 16-2, is the handler class towhich the event is delegated.

Code 16-2 The ButtonHandler Example

1 import java.awt.event.*;23 public class ButtonHandler implements ActionListener {4 public void actionPerformed(ActionEvent e) {5 System.out.println("Action occurred");6 System.out.println("Button’s command is: "7 + e.getActionCommand());8 }9 }

Handling GUI-Generated Events 16-5Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 406: Sl275 Sg

Java SE Event Model

Code 16-2 on page 16-5 has the following characteristics:

● The JButton class inherits theaddActionListener(ActionListener) method fromjavax.swing.AbstractButton which is the superclass of JButton.

● The ActionListener interface defines a single method,actionPerformed, which receives an ActionEvent.

● After it is created, a JButton object can have an object registered as alistener for ActionEvents through the addActionListener()method. The registered listener is instantiated from a class thatimplements the ActionListener interface.

● When the JButton object is clicked, an ActionEvent is sent. TheActionEvent is received through the actionPerformed()method of any ActionListener that is registered on the buttonthrough its addActionListener() method.

● The method, getActionCommand(), of the ActionEvent classreturns the command name associated with this action. On Line 11,the action command for this button is set to ButtonPressed.

Note – There are other ways to determine why an event has beenreceived. In particular, the method getSource(), documented in thejava.util.EventObject base class, is often useful because it enablesyou to obtain the reference to the object that sent the event.

Events are not handled accidentally. The objects that are scheduled tolisten to particular events on a particular GUI component registerthemselves with that component.

● When an event occurs, only the objects that were registered receive amessage that the event occurred.

● The delegation model is good for the distribution of work amongobjects.

Events do not have to be related to Swing components. This event modelprovides support for the JavaBeans architecture.

16-6 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 407: Sl275 Sg

GUI Behavior

GUI Behavior

This section describes the event categories.

Event Categories

The general mechanism for receiving events from components has beendescribed in the context of a single type of event. Many of the eventclasses reside in the java.awt.event package, but others existelsewhere in the API. Figure 16-3 shows a UML class hierarchy of GUIevent classes.

Figure 16-3 Class Hierarchy of GUI Events

For each category of events, an interface has to be implemented by theclass of objects that wants to receive the events. That interface demandsthat one or more methods be defined as well. Those methods are calledwhen particular events arise. Table 16-1 lists these categories andinterfaces.

java.util.EventObject

java.awt.AWTEvent ActionEvent

AdjustmentEvent

ComponentEvent

TextEvent

ContainerEvent

FocusEvent

InputEvent

WindowEvent

KeyEvent

MouseEvent

java.awt.event

ItemEvent

Table 16-1 Method Categories and Interfaces

Category Interface Name Methods

Action ActionListener actionPerformed(ActionEvent)

Item ItemListener itemStateChanged(ItemEvent)

Handling GUI-Generated Events 16-7Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 408: Sl275 Sg

GUI Behavior

Mouse MouseListener mousePressed(MouseEvent)mouseReleased(MouseEvent)mouseEntered(MouseEvent)mouseExited(MouseEvent)mouseClicked(MouseEvent)

Mousemotion

MouseMotionListener mouseDragged(MouseEvent)mouseMoved(MouseEvent)

Key KeyListener keyPressed(KeyEvent)keyReleased(KeyEvent)keyTyped(KeyEvent)

Focus FocusListener focusGained(FocusEvent)focusLost(FocusEvent)

Adjustment AdjustmentListener adjustmentValueChanged(AdjustmentEvent)

Component ComponentListener componentMoved(ComponentEvent)componentHidden(ComponentEvent)componentResized(ComponentEvent)componentShown(ComponentEvent)

Window WindowListener windowClosing(WindowEvent)windowOpened(WindowEvent)windowIconified(WindowEvent)windowDeiconified(WindowEvent)windowClosed(WindowEvent)windowActivated(WindowEvent)windowDeactivated(WindowEvent)

Container ContainerListener componentAdded(ContainerEvent)componentRemoved(ContainerEvent)

Windowstate

WindowStateListener windowStateChanged(WindowEvent e)

Windowfocus

WindowFocusListener windowGainedFocus(WindowEvent e)windowLostFocus(WindowEvent e)

Mousewheel

MouseWheelListener mouseWheelMoved(MouseWheelEvent e)

Table 16-1 Method Categories and Interfaces (Continued)

Category Interface Name Methods

16-8 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 409: Sl275 Sg

GUI Behavior

Complex Example

This section examines a more complex Java code software example. Ittracks the movement of the mouse when the mouse button is pressed(mouse dragging). It also detects mouse movement even when the buttonsare not pressed (mouse moving).

The events caused by moving the mouse with or without a button pressedcan be picked up by objects of a class that implements theMouseMotionListener interface. This interface requires two methods,mouseDragged() and mouseMoved(). Even if you are interested onlyin the drag movement, you must provide both methods. However, thebody of the mouseMoved() method can be empty.

To pick up other mouse events, including mouse clicking, you mustimplement the MouseListener interface. This interface includes severalevents, including mouseEntered, mouseExited, mousePressed,mouseReleased, and mouseClicked.

When mouse or keyboard events occur, information about the position ofthe mouse or the key that was pressed is available in the event that itgenerated. In Code 16-2 on page 16-5 on event handling, there was aseparate class named ButtonHandler that handled events. In Code 16-3,events are handled within the class named TwoListener.

Code 16-3 The TwoListener Example

1 import javax.swing.*;

Inputmethods

InputMethodListener caretPositionChanged(InputMethodEvent e)inputMethodTextChnaged(InputMethodEvent e)

Hierarchy HierarchyListener hierarchyChanged(HierarchyEvent e)

Hierarchybounds

HierarchyBoundsListener

ancestorMoved(HierarchyEvent e)ancestorResized(HierarchyEvent e)

AWT AWTEventListener eventDispatched(AWTEvent e)

Text TextListener textValueChanged(TextEvent)

Table 16-1 Method Categories and Interfaces (Continued)

Category Interface Name Methods

Handling GUI-Generated Events 16-9Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 410: Sl275 Sg

GUI Behavior

2 import java.awt.event.*;3 import java.awt.*;45 public class TwoListener6 implements MouseMotionListener, MouseListener {7 private JFrame f;8 private JTextField tf;910 public TwoListener() {11 f = new JFrame("Two listeners example");12 tf = new JTextField(30);13 }1415 public void launchFrame() {16 JLabel label = new JLabel("Click and drag the mouse");17 // Add components to the frame18 f.add(label, BorderLayout.NORTH);19 f.add(tf, BorderLayout.SOUTH);20 // Add this object as a listener21 f.addMouseMotionListener(this);22 f.addMouseListener(this);23 // Size the frame and make it visible24 f.setSize(300, 200);25 f.setVisible(true);26 }2728 // These are MouseMotionListener events29 public void mouseDragged(MouseEvent e) {30 String s = "Mouse dragging: X = " + e.getX()31 + " Y = " + e.getY();32 tf.setText(s);33 }3435 public void mouseEntered(MouseEvent e) {36 String s = "The mouse entered";37 tf.setText(s);38 }3940 public void mouseExited(MouseEvent e) {41 String s = "The mouse has left the building";42 tf.setText(s);43 }4445 // Unused MouseMotionListener method.46 // All methods of a listener must be present in the47 // class even if they are not used.

16-10 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 411: Sl275 Sg

GUI Behavior

48 public void mouseMoved(MouseEvent e) { }4950 // Unused MouseListener methods.51 public void mousePressed(MouseEvent e) { }52 public void mouseClicked(MouseEvent e) { }53 public void mouseReleased(MouseEvent e) { }5455 public static void main(String args[]) {56 TwoListener two = new TwoListener();57 two.launchFrame();58 }59 }

A number of points shown in Code 16-3 on page 16-9 are described in thefollowing paragraphs.

Implementing Multiple Interfaces

The class is declared in Lines 5 and 6 using the following:

implements MouseMotionListener, MouseListener

You can declare multiple interfaces by using comma separation.

Listening to Multiple Sources

If you issue the following method calls in Lines 20 and 21

f.addMouseListener(this);f.addMouseMotionListener(this);

both types of events cause methods to be called in the TwoListener class.An object can listen to as many event sources as required. The object’sclass needs to implement only the required interfaces.

Obtaining Details About the Event

The event arguments with which handler methods, such asmouseDragged(), are called contain potentially important informationabout the original event. To determine the details of what information isavailable for each category of event, check the appropriate classdocumentation in the java.awt.event package.

Handling GUI-Generated Events 16-11Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 412: Sl275 Sg

GUI Behavior

Multiple Listeners

The AWT event listening framework permits the attachment of multiplelisteners to the same component. In general, if you choose to write aprogram that performs multiple actions based on a single event, includecode for that behavior in your handler method. However, sometimes aprogram’s design requires multiple, unrelated parts of the same programto react to the same event. This might happen if, for example, a context-sensitive help system is added to an existing program.

The listener mechanism enables you to call an addXxxListener()method as many times as needed, and you can specify as many differentlisteners as your design requires. All registered listeners have theirhandler methods called when the event occurs.

Note – The order in which the handler methods are called is undefined.Generally, if the order of invocation matters, then the handlers are notunrelated. In this case, register only the first listener and have that listenercall others directly.

16-12 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 413: Sl275 Sg

Developing Event Listeners

Developing Event Listeners

In this section, you will learn about the design and implementationchoices for implementing event listeners.

Event Adapters

It is a lot of work to implement all of the methods in each of the listenerinterfaces, particularly the MouseListener interface andWindowListener interface.

For example, the MouseListener interface declares the followingmethods:

public void mouseClicked(MouseEvent event)public void mouseEntered(MouseEvent event)public void mouseExited(MouseEvent event)public void mousePressed(MouseEvent event)public void mouseReleased(MouseEvent event)

As a convenience, the Java programming language provides adapterclasses that implement each interface containing more than one method.The methods in these adapter classes are empty.

You can extend an adapter class and override only those methods thatyou need, as shown in Code 16-4.

Code 16-4 The MouseClickHandler Example

1 import java.awt.*;2 import java.awt.event.*;3 import javax.swing.*;45 public class MouseClickHandler extends MouseAdapter {67 // We just need the mouseClick handler, so we use8 // an adapter to avoid having to write all the9 // event handler methods1011 public void mouseClicked(MouseEvent e) {12 // Do stuff with the mouse click...13 }14 }

Handling GUI-Generated Events 16-13Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 414: Sl275 Sg

Developing Event Listeners

Event Handling Using Inner Classes

Lines 26 and 12–18 in Code 16-5 show how to create event handlers asinner classes. Using inner classes for event handlers gives you access tothe private data of the outer class (Line 16).

Code 16-5 The TestInner Example

1 import java.awt.*;2 import java.awt.event.*;3 import javax.swing.*;4 public class TestInner {5 private JFrame f;6 private JTextField tf;78 public TestInner() {9 f = new JFrame("Inner classes example");10 tf = new JTextField(30);11 }1213 class MyMouseMotionListener extends MouseMotionAdapter {14 public void mouseDragged(MouseEvent e) {15 String s = "Mouse dragging: X = "+ e.getX()16 + " Y = " + e.getY();17 tf.setText(s);18 }19 }2021 public void launchFrame() {22 JLabel label = new JLabel("Click and drag the mouse");23 // Add components to the frame24 f.add(label, BorderLayout.NORTH);25 f.add(tf, BorderLayout.SOUTH);26 // Add a listener that uses an Inner class27 f.addMouseMotionListener(new MyMouseMotionListener());28 f.addMouseListener(new MouseClickHandler());29 // Size the frame and make it visible30 f.setSize(300, 200);31 f.setVisible(true);32 }3334 public static void main(String args[]) {35 TestInner obj = new TestInner();36 obj.launchFrame();37 }38 }

16-14 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 415: Sl275 Sg

Developing Event Listeners

Event Handling Using Anonymous Classes

You can include an entire class definition within the scope of anexpression. This approach defines what is called an anonymous inner classand creates the instance all at one time. Anonymous inner classes areoften used in event handling, Code 16-6 shows an example.

Code 16-6 The TestAnonymous Example

1 import java.awt.*;2 import java.awt.event.*;3 import javax.swing.*;45 public class TestAnonymous {6 private JFrame f;7 private JTextField tf;89 public TestAnonymous() {10 f = new JFrame("Anonymous classes example");11 tf = new JTextField(30);12 }1314 public void launchFrame() {15 JLabel label = new JLabel("Click and drag the mouse");16 // Add components to the frame17 f.add(label, BorderLayout.NORTH);18 f.add(tf, BorderLayout.SOUTH);19 // Add a listener that uses an anonymous class20 f.addMouseMotionListener(new MouseMotionAdapter() {21 public void mouseDragged(MouseEvent e) {22 String s = "Mouse dragging: X = "+ e.getX()23 + " Y = " + e.getY();24 tf.setText(s);25 }26 }); // <- note the closing parenthesis27 f.addMouseListener(new MouseClickHandler()); // Not shown28 // Size the frame and make it visible29 f.setSize(300, 200);30 f.setVisible(true);31 }3233 public static void main(String args[]) {34 TestAnonymous obj = new TestAnonymous();35 obj.launchFrame();36 }37 }

Handling GUI-Generated Events 16-15Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 416: Sl275 Sg

Developing Event Listeners

Note – The compilation of an anonymous class generates a file, such asTestAnonymous$1.class.

16-16 Java™ Programming LanguageCopyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 417: Sl275 Sg

Concurrency in Swing

Concurrency in Swing

Applications that contain a GUI require several threads for handling theGUI efficiently.

● Threads responsible for executing the application code are calledcurrent threads.

● Threads responsible for handling the events generated by variouscomponents are called event dispatch threads.

● Threads responsible for executing lengthy tasks are called workerthreads. Some examples of these lengthy tasks include waiting forsome shared resource, waiting for user input, blocking for networkor disk I/O, performing either CPU or memory-intensivecalculations. These tasks can be executed in the background withoutaffecting the performance of the GUI.

You can use instances of the SwingWorker class to represent these workerthreads. The SwingWorker class extends the Object class and implementsthe RunnableFuture interface.

The SwingWorker class provides the following utility methods:

● For communication and coordination between worker thread tasksand tasks on other threads, the SwingWorker class providesproperties such as progress and state to support inter-threadcommunication.

● To execute simple background tasks, the doInBackground methodcan be used for running the tasks background.

● To execute tasks that have intermediate results, the results arepublished in a GUI using the publish and process methods.

● To cancel the background threads, they can be canceled using thecancel method.

Note – A full description of the use of the SwingWorker class is outsidethe scope of this module. For more information, see the following URL:http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html.

Handling GUI-Generated Events 16-17Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

Page 418: Sl275 Sg