java programming fundamentals: learning center student · pdf filejava programming...

386
Java Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4 • version 6.07 • rd021209

Upload: trinhtuyen

Post on 31-Jan-2018

269 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Java Programming Fundamentals:

Learning Center Student Guide CIW Java Programming Series

CCL05-CEJPRF-PR-203� • CIWv4 • version 6.07 • rd021209

Page 2: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

THIS INVISIBLE WRITING (WHITE FONT COLOR) MUST BE LEFT IN THE

Blank Text For The Docutech!

Page 3: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

CIW Certification –

An NWCET-Sponsored

Program The CIW Internet skills certification program, sponsored by the National Workforce Center for Emerging Technologies (NWCET), is aimed at professionals who design, develop, administer, secure and support Internet- or intranet-related services. It offers a unique opportunity to learn, demonstrate and prove competence on Web-related technologies. CIW certifications are endorsed by the International Webmasters Association (IWA) and the Association of Internet Professionals (AIP).

Benefits of Certification

CIW Internet skills certification offers industry-wide recognition of an individual's Internet and Web knowledge and skills. It also provides tangible evidence of a person's competency as an Internet professional and is frequently a factor in hiring and assignment decisions. Individuals holding CIW certification can demonstrate to potential employers and clients that they have passed rigorous training and examination requirements, setting them apart from non-certified competitors. The CIW logo identifies individuals as Internet professionals who have been certified by one of the most prestigious programs in the industry.

Certification Testing CIW certification exams are administered by Prometric, Inc. through Authorized Prometric Testing Centers (APTCs) and by Virtual University Enterprises (VUE) testing centers worldwide. The exams measure technical proficiency and establish a level of core competency required to become CIW certified. To register for a CIW exam online, visit Prometric at www.2test.com or VUE at www.vue.com. For more information about CIW exams, visit www.CIWcertified.com and select the Exams link.

We encourage you to speak with the CIW training partner of your choice to find out more about the vendor-neutral CIW Internet Skills program. To locate a CIW training partner, visit www.CIWcertified.com, select the Training Locator link and select the training partner of your choice, either by location, partner or course.

www.CIWcertified.com www.CIWcertified.com www.CIWcertified.com

Page 4: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

CIW Certifications and Paths

The first step toward CIW certification is the CIW Foundations series. After passing the Foundations exam, students become a CIW Associate and can choose from four Master CIW certification tracks. CIW Associates who pass a CIW job role series become a CIW Professional. CIW Professionals who pass all the certification exams in a specific master track earn Master CIW designation as a Master CIW Web Site Manager, Master CIW Administrator, Master CIW Designer, or Master CIW Enterprise Developer.

Foundations 30-hour series

CIW Exam 1D0-410

Web Languages 30-hour series

JavaScript Exam 1D0-435 CIW PERL Exam 1D0 -437

CIW Exams: 1D0-410, 1D0-450, 1D0-460 and

1D0-470

Server Administrator

30-hour series CIW Exam 1D0-450

E-Commerce Designer

30-hour series CIW Exam 1D0-425

Site Designer

30-hour series CIW Exam 1D0-420

Internetworking Professional

30-hour series CIW Exam 1D0-460

Security Professional

30-hour series CIW Exam 1D0-470

CIW Exams 1D0-410, 1D0-420 and 1D0-425

Application Developer 30-hour series

CIW Exam 1D0-430

Java Programming 30-hour series

jCert Level 1/Sun Exam 310-025

Object-Oriented Analysis and Design 30-hour series

jCert Level 2A/CIW Exam 1D0-438

CIW Exams: 1D0-410, 1D0-435, 1D0-437, 1D0-430, Sun Certification

Exam 310-025, 1D0-438, 1D0-441 and 1D0-442.

Enterprise Specialist 30-hour series

CIW Exam 1D0-442

Database Specialist 30-hour series

CIW Exam 1D0-441

CIW Associate

CIW Professional (Industry-recognized job role)

Language/Theory Training

Master CIW Certification

CIW Associate Certification

FastTrack for MCSEs and CNEs

CIW Exam 1D0-475

CIW Exams: 1D0-410, 1D0-450, 1D0-435, 1D0-437

and 1D0-420

Master CIW Web Site Manager: Our newest Master CIW track, composed of two professional Internet job role series exams (Site Designer and Server Administrator) and two additional language exams (JavaScript and Perl Fundamentals from our Web Languages series).

Master CIW Administrator : Composed of three professional series, each representing an Internet job role with its own exam (Server Administrator, Internetworking Professional, and Security Professional series).

Master CIW Enterprise Developer: Our most comprehensive program, composed of three professional Internet job role series (Application Developer, Database Specialist, and Enterprise Specialist) and three additional language/theory series (Web Languages, Java Programming, and Object-Oriented Analysis).

Master CIW Designer: Composed of two professional series, each representing an Internet job role with its own exam (Site Designer and E-Commerce Designer series).

www.CIWcertified.com

Page 5: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Master CIW Enterprise Developer/jCert Level 1

and the Java Programming Series

The Java Programming series is not a CIW job role, but it is a language/theory requirement for Master CIW Enterprise Developer and jCert Level 1 certification. Competency in Java programming is necessary before students may take CIW Object-Oriented Analysis and Design (also required for jCert), CIW Database and Enterprise Specialist series, and the jCert Solution Developer certification exams.

www.CIWcertified.com

Foundations

30-hour series CIW Exam 1D0-410

Web Languages 30-hour series

JavaScript Exam 1D0-435 Perl Exam 1D0-437

Java Programming 30-hour series

jCert/Sun Exam 310-025

Certificate awarded after

passing all exams in this track: 1D0-410, 1D0-435, 1D0-437, 1D0-430, Sun 310-025, 1D0-

438, 1D0-441 and 1D0-442.

Application Developer 30-hour series

CIW Exam 1D0-430

Object-Oriented Analysis and Design

30-hour series jCert/CIW Exam 1D0-438

Database Specialist 30-hour series

CIW Exam 1D0-441

Enterprise Specialist 30-hour series

CIW Exam 1D0-442

jCert Level 1

Target Audience Database developers and administrators, Internet application developers, middleware programmers, Java developers, and client/server developers.

Wclient/server developers.

Job

Responsibilities

Develop n-tier database and legacy connectivity solutions for Web applications using Java, Java APIs, Java Database Connectivity solutions, middleware tools, and distributed object models.

Create interactive Web pages using clientapplications; access relational database systems from Web applications; implement applications using compoand create parameters for environment variables.

Prerequisites Students must have:

CIW Foundations series certification (exam 1D0-410),

Web Languages certification (exams 1D0-435 and 1D0-437), and

CIW Application Developer series certification (exam 1D0-430),

or equivalent experience for those students not seeking Master CIW Enterprise Developer certification.

Students must have:

orCIW Enterprise Developer certification.

Training/

Experience

Students should take the following course, or have equivalent experience, before taking the 310-025 jCert/Sun Certified Programmer for the Java Platform exam:

Java Programming Fundamentals (30 hours)

Note: It is recommend, but not required, that students take the Sun Certified Java Programmer Exam Preparation Guide course (18 hours) prior to taking the 310-025 exam.

Certification

Awards

To become Master CIW Enterprise Developer certified, students must pass the Foundations 1D0-410, Web Languages 1D0-435 and 1D0-437, Application Developer 1D0-430, Sun Programmer exam 310-025, OO Analysis and Design 1D0-438, Database Specialist 1D0-441, and Enterprise Specialist 1D0-442 exams administered by Prometric or VUE.

By passing the 310-025 Sun Programmer exam, students fulfill the requirements for Master CIW Enterprise Developer and jCert Level 1. See the following page for more information on the jCert Initiative or visit www.jcert.org.

Tmust pass the Foundations 1D0Developer 1D0Specialist 1byexams that are released in 2000, but cannot earn the full credential until all exams are released in 2001.

To earn CIW Professional desiFoundations 1D0

Page 6: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

The jCert Initiative, Inc., established in November 1999, is a non-profit organization sponsored by leading industry software, training and certification companies IBM, Oracle, Sun Microsystems, Hewlett-Packard/Bluestone, BEA Systems, Sybase, ProsoftTraining.com and Wave Thomson Learning. jCert, a certification and career path program for Enterprise Developers using JavaTM, provides a fast track for Java technology developers to move within

the expanding e-commerce employment market. In fact, more than 50,000 candidates around the world have passed jCert-recognized exams to join the professional workforce using Java and Java-based products. In addition to the jCert sponsors, top leading training and services companies, including AvantSoft, SmartForce, Learning Voyage, Global Knowledge, Computer Generated Solutions and WebGain, actively participate in the jCert Initiative to promote jCert certification and jCert standards.

Mission Statement

The jCert mission is to reduce the number of certification exams required by the majority of companies who require Java-based technology validation. The mission statement, "Certified Once, Recognized Everywhere" defines this goal. By joining jCert, sponsor and participant members have agreed to reduce exam redundancy and support a powerful multi-vendor Java certification standard. The growing number of companies joining the Initiative demonstrates how jCert can be "Recognized Everywhere."

Road Map

The jCert road map illustrates three certification exams that validate generic Java skills (1, 2A and 3A) and the vendor-specific options (2B and 3B) for each certification level award (Solution Developer and Enterprise Developer). After passing the first two generic exams (1, 2A), candidates can acquire Solutions Developer status (developed and awarded by the Hewlett-Packard/Bluestone, IBM, or Oracle at the 2B Level). Certified Solution Developers can advance to Level 3 where their choices broaden again. After passing the generic Java skills 3A exam, candidates can select any vendor for 3B. jCert portability between vendors allows candidates to move from one vendor at Level 2B to a different vendor at Level 3B (and within levels at both Solution Developer and Enterprise Developer levels).

jCert Road Map

Page 7: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

jCert Value

jCert is a collective group of organizations. jCert does not own exams or curriculum. jCert is a certification standard composed of industry-tested exams and curriculum for generic Java skills and vendor tools validation that benefit individuals, training organizations and corporations.

Individual developers gain leverage, portability and flexibility with the jCert road map. They only need to take one set of exams to qualify at a given certification level and can use that qualification to gain entry into another vendor's program at the next level. With jCert, Java developers rapidly develop Java skills, earn multi-vendor and industry validation of skills, and qualify for career and/or compensation advancement.

jCert provides job task definition and skills standards for companies to meet recruitment needs. jCert also provides industry-recognized objectives and standards necessary for training organizations to develop comprehensive Java technology instructor-led, self-study, and e-learning curriculum.

jCert and CIW

CIW and jCert share the same vendor-neutral, or generic, Java objectives and exam requirements at jCert Level 1 and 2A. Because of this consistency CIW and jCert, students who pass these exams receive credit in both programs. The two tables below illustrate how students can prepare for one exam, but achieve certification status in multiple Java programs.

jCert Level 1: Sun Certified Programmer for the Java 2 Platform

���� Step 1 – Training : CIW Java Programming Fundamentals (30 hours – required) and CIW Java Programmer Exam Preparation Guide (18 hours – recommended).

���� Step 2 – Exam: Sun Certified Programmer for the Java Platform Exam 310-025.

���� Step 3 – Certification Awards: By passing one exam (Sun Certified Programmer for the Java Platform), candidates earn Java Programmer designation in three different certification programs: CIW, jCert Level 1, and Sun Microsystems.

jCert Level 2A: Object-Oriented Analysis and Design

���� Prerequisites: Candidates must have Sun Certified Programmer for Java Platform status.

���� Step 1 – Training: CIW Object-Oriented Analysis and Design (30 hours – required).

���� Step 2 – Exam: CIW Object-Oriented Analysis and Design 1D0-438.

���� Step 3 – Certification Awards: By passing one exam (CIW Object-Oriented Analysis and Design exam), candidates earn OO Analysis designation in two different certification programs: CIW and jCert Level 2A.

Additional information about CIW and preparing for

jCert Levels 1 and 2A can be found at www.ciwcertified.com.

Information about training and jCert certification at Levels 2B, 3A and 3B is located at www.jcert.org.

Page 8: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

CIW and NWCET…

Setting IT Skills Standards for the

Knowledge Economy The National Workforce Center for Emerging Technologies (NWCET) is the official sponsor of the CIW job-role certification program and leader of the CIW Certification Council. NWCET’s involvement ensures the promotion of the CIW credential as a practical way to implement skill standards and assures that the CIW program continues to validate the skills required to succeed in the competitive technology-enabled workforce.

NWCET developed the only nationally recognized and validated IT skills standards, funded in part by the National Science Foundation, which comprehensively describe the skills, knowledge and attributes required of professionals in the knowledge economy.

NWCET's leadership role in CIW is part of its ongoing mission to lead education, business and government in developing skilled information technology (IT) workers.

Please visit www.nwcet.org for more information regarding NWCET, CIW or the CIW Certification Council.

CIW and IWA… Promoting a Worldwide Standard for

Web Certification! IWA, the non-profit association for Web professionals, is the industry's recognized leader in providing educational and certification standards. IWA initiatives support more than 100 official chapters with 14,000 individual members in 106 countries.

IWA has integrated industry-leading CIW Internet skills training into its Certified Web Professional program to offer a single worldwide standard in Web certification. To be eligible for IWA Certified Web Professional status, a candidate must pass CIW Foundations and a CIW job role series exam, demonstrate a minimum of two years' related experience, and complete a job role series every three years by completing thirty hours of continuing education.

IWA Certified Web Professional (CWP) status provides Web certification based on an individual's proven experience, professionalism and knowledge. Please visit us at www.iwanet.org for more information about applying your CIW credential for CWP status.

Page 9: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Java Programming

Fundamentals: Learning Center Student Guide

Page 10: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

prosofttraining

TM

Chairman and Chief Executive Officer Jerrell M. Baird

Chief Financial Officer and Executive Vice President

Robert Gwin

Corporate Office ProsoftTraining 3001 Bee Caves Road Austin, TX 78746 Main: (512) 328-6140 Fax: (512) 328-5237

Vice President, Research and Development Judson Slusser

Director of Courseware Patrick T. Lane

Project Managers David De Ponte, Todd Hopkins, Sheila Ramirez

Editing Manager Jill McKenna

Senior Editor Susan M. Lane

Editors Tom Graves, David Oberman, Denise Siino

Publishing Manager Joseph A. Servia

Publishers Scott Evanskey, Joseph Flannery

Courseware Office ProsoftTraining 2333 North Broadway Santa Ana, CA 92706 Main: (714) 953-1200 Fax: (714) 953-1212

Copyright © 2009, All rights reserved.

Page 11: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Java Programming Fundamentals

Developers

Ken Cohen and Gregg Frosti

Contributors

James E. Roos and James Stanger, Ph.D.

Editors

Susan M. Lane and David Oberman

Publishers

Scott Evanskey and Joseph A. Servia

Project Managers

David De Ponte, Todd Hopkins and Sheila Ramirez

Trademarks Prosoft is a trademark of ProsoftTraining. All product names and services identified throughout this book are trademarks or registered trademarks of their respective companies. They are used throughout this book in editorial fashion only. No such use, or the use of any trade name, is intended to convey endorsement or other affiliation with the book. Copyrights of any screen captures in this book are the property of the software’s manufacturer.

Disclaimer ProsoftTraining makes a genuine attempt to ensure the accuracy and quality of the content described herein; however, ProsoftTraining, makes no warranty, express or implied, with respect to the quality, reliability, accuracy, or freedom from error of this document or the products it describes. ProsoftTraining makes no representation or warranty with respect to the contents hereof and specifically disclaims any implied warranties of fitness for any particular purpose. ProsoftTraining disclaims all liability for any direct, indirect, incidental or consequential, special or exemplary damages resulting from the use of the information in this document or from the use of any products described in this document. Mention of any product or organization does not constitute an endorsement by ProsoftTraining of that product or corporation. Data used in examples and labs is intended to be fictional even if actual data is used or accessed. Any resemblance to, or use of real persons or organizations should be treated as entirely coincidental. ProsoftTraining makes every effort to ensure the accuracy of URLs referenced in all its material, but cannot guarantee that all URLs will be available throughout the life of a course. When this course/disk was published, all URLs were checked for accuracy and completeness. However, due to the ever-changing nature of the Internet, some URLs may no longer be available or may have been re-directed.

Copyright Information This training manual is copyrighted and all rights are reserved by ProsoftTraining. No part of this publication may be reproduced, transmitted, stored in a retrieval system, modified, or translated into any language or computer language, in any form or by any means, electronic, mechanical, magnetic, optical, chemical, manual or otherwise without written permission of ProsoftTraining, 3001 Bee Caves Road, Austin, TX 78746.

Copyright © 2000 - 2009 by ProsoftTraining All Rights Reserved

ISBN: 1-58143-664-5

Page 12: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

iv

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 13: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

v

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Table of Contents Course Description...................................................................................................................... xii ProsoftTraining Courseware .................................................................................................... xiv Course Objectives ...................................................................................................................... xvi Classroom Setup........................................................................................................................ xvii System Requirements ............................................................................................................... xvii Conventions and Graphics Used in This Book ........................................................................ xix

Lesson 1: Java Runtime Environment ..................................................................................... 1-1 Pre-Assessment Questions ........................................................................................................ 1-2 The Java Virtual Machine......................................................................................................... 1-3 The Java 2 Software Development Kit ..................................................................................... 1-4 Java Comments ......................................................................................................................... 1-5 Lesson 1 Review ....................................................................................................................... 1-8

Lesson 2: Data Types, Variables and Operators..................................................................... 2-1 Pre-Assessment Questions ........................................................................................................ 2-2 Data Types ................................................................................................................................ 2-3 Declaring Variables .................................................................................................................. 2-4 Variable Scope .......................................................................................................................... 2-4 Casting ...................................................................................................................................... 2-6 Operators .................................................................................................................................. 2-7 Automatic Casting .................................................................................................................. 2-10 Lesson 2 Review ..................................................................................................................... 2-14

Lesson 3: Control Statements ................................................................................................... 3-1 Pre-Assessment Questions ........................................................................................................ 3-2 Code Blocks .............................................................................................................................. 3-3 Conditional Statements ............................................................................................................. 3-4 Iterative Statements (Loops) ..................................................................................................... 3-6 Lesson 3 Review ..................................................................................................................... 3-11

Lesson 4: Methods...................................................................................................................... 4-1 Pre-Assessment Questions ........................................................................................................ 4-2 Java Methods ............................................................................................................................ 4-4 Return Statements ..................................................................................................................... 4-4 Calling a Method ...................................................................................................................... 4-5 Parameters ................................................................................................................................ 4-5 Pass by Value ........................................................................................................................... 4-6 Overloading .............................................................................................................................. 4-7 Lesson 4 Review ..................................................................................................................... 4-10

Lesson 5: Arrays ........................................................................................................................ 5-1 Pre-Assessment Questions ........................................................................................................ 5-2 What Is an Array? ..................................................................................................................... 5-3 Initializing an Array.................................................................................................................. 5-3 Objects ...................................................................................................................................... 5-4 Using an Array ......................................................................................................................... 5-5

Page 14: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

vi

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Passing an Array to a Method .................................................................................................. 5-5 Garbage Collection ................................................................................................................... 5-6 Command Line Parameters ...................................................................................................... 5-7 Lesson 5 Review ..................................................................................................................... 5-10

Lesson 6: Classes and Objects .................................................................................................. 6-1 Pre-Assessment Questions ........................................................................................................ 6-2 Object-Oriented Programming ................................................................................................. 6-4 What Is an Object? ................................................................................................................... 6-4 Instance and Class Members .................................................................................................... 6-5 Abstraction ............................................................................................................................... 6-9 Object References ................................................................................................................... 6-10 Lesson 6 Review ..................................................................................................................... 6-13

Lesson 7: Inheritance ................................................................................................................. 7-1 Pre-Assessment Questions ........................................................................................................ 7-2 What Is Inheritance? ................................................................................................................. 7-4 Overriding Methods .................................................................................................................. 7-5 Overridden Methods and Variables .......................................................................................... 7-7 Lesson 7 Review ..................................................................................................................... 7-10

Lesson 8: Constructors .............................................................................................................. 8-1 Pre-Assessment Questions ........................................................................................................ 8-2 What Is a Constructor? ............................................................................................................. 8-4 Using Constructors ................................................................................................................... 8-4 The Keyword this ..................................................................................................................... 8-6 Constructor Process .................................................................................................................. 8-8 Constructors and Callbacks ...................................................................................................... 8-9 String and StringBuffer ........................................................................................................... 8-10 Lesson 8 Review ..................................................................................................................... 8-16

Lesson 9: Interfaces and Abstract Classes............................................................................... 9-1 Pre-Assessment Questions ........................................................................................................ 9-2 What Is an Interface? ................................................................................................................ 9-4 Polymorphism ........................................................................................................................... 9-6 What Is an Abstract Class? ....................................................................................................... 9-9 Lesson 9 Review ..................................................................................................................... 9-13

Lesson 10: Packages and Access Modifiers ........................................................................... 10-1 Pre-Assessment Questions ...................................................................................................... 10-2 Introduction to Packages and Access Modifiers..................................................................... 10-4 Packages ................................................................................................................................. 10-4 Access Modifiers .................................................................................................................... 10-5 Java 2 Application Programming Interface ............................................................................ 10-6 Encapsulation ......................................................................................................................... 10-6 Lesson 10 Review ................................................................................................................. 10-11

Lesson 11: Swing Components ............................................................................................... 11-1 Pre-Assessment Questions ...................................................................................................... 11-2 What Is the AWT? .................................................................................................................. 11-3

Page 15: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

vii

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

What Is Swing? ....................................................................................................................... 11-4 Basic Swing Components ....................................................................................................... 11-5 Swing Containers .................................................................................................................. 11-20 JavaBeans ............................................................................................................................. 11-25 Lesson 11 Review ................................................................................................................. 11-27

Lesson 12: Layout Managers .................................................................................................. 12-1 Pre-Assessment Questions ...................................................................................................... 12-2 What Is a Layout Manager?.................................................................................................... 12-5 FlowLayout ............................................................................................................................. 12-6 GridLayout ............................................................................................................................. 12-7 BorderLayout .......................................................................................................................... 12-8 BoxLayout ............................................................................................................................. 12-10 Combining Layouts .............................................................................................................. 12-13 Lesson 12 Review ................................................................................................................. 12-18

Lesson 13: Graphics in Java ................................................................................................... 13-1 Pre-Assessment Questions ...................................................................................................... 13-2 Graphics Class ........................................................................................................................ 13-3 Color Class ............................................................................................................................. 13-9 Font Class ............................................................................................................................. 13-10 Lesson 13 Review ................................................................................................................. 13-15

Lesson 14: The Event Delegation Model ................................................................................ 14-1 Pre-Assessment Questions ...................................................................................................... 14-2 What Is an Event? ................................................................................................................... 14-3 JDK 1.0 Event Handling ......................................................................................................... 14-3 SDK 1.2 Event Handling ........................................................................................................ 14-4 Lesson 14 Review ................................................................................................................. 14-16

Lesson 15: Inner Classes ......................................................................................................... 15-1 Pre-Assessment Questions ...................................................................................................... 15-2 What Is an Inner Class? .......................................................................................................... 15-4 Inner Classes for Event Handling ........................................................................................... 15-4 Lesson 15 Review ................................................................................................................. 15-10

Lesson 16: Java Applets .......................................................................................................... 16-1 Pre-Assessment Questions ...................................................................................................... 16-2 Programming Applets ............................................................................................................. 16-3 Applets and Web Browsers .................................................................................................... 16-4 Converting an Application into an Applet ............................................................................ 16-11 Converting an Applet into an Application ............................................................................ 16-13 Lesson 16 Review ................................................................................................................. 16-17

Lesson 17: Exceptions .............................................................................................................. 17-1 Pre-Assessment Questions ...................................................................................................... 17-2 What Is an Exception? ............................................................................................................ 17-4 Handling Exceptions .............................................................................................................. 17-5 Creating User-Defined Exceptions ......................................................................................... 17-8 Exception Handling Tips ...................................................................................................... 17-10

Page 16: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

viii

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Exceptions and Inheritance ................................................................................................... 17-11 Lesson 17 Review ................................................................................................................. 17-13

Lesson 18: Creating Threads and Thread Methods ............................................................. 18-1 Pre-Assessment Questions ...................................................................................................... 18-2 What Are Threads? ................................................................................................................. 18-3 How Operating Systems Handle Multitasking ....................................................................... 18-3 Types of Threads in Java ........................................................................................................ 18-4 Creating Threads..................................................................................................................... 18-5 Thread Methods ...................................................................................................................... 18-8 Lesson 18 Review ................................................................................................................. 18-17

Lesson 19: Thread Synchronization ....................................................................................... 19-1 Pre-Assessment Questions ...................................................................................................... 19-2 What Is Thread Synchronization? .......................................................................................... 19-3 Thread Racing......................................................................................................................... 19-3 Synchronized and the Object Monitor .................................................................................... 19-4 Thread Race Condition ........................................................................................................... 19-5 Sophisticated Thread Synchronization ................................................................................... 19-9 Stopping, Suspending and Resuming Threads ..................................................................... 19-13 Deadlocks ............................................................................................................................. 19-16 Lesson 19 Review ................................................................................................................. 19-19

Lesson 20: Streams and Serialization .................................................................................... 20-1 Pre-Assessment Questions ...................................................................................................... 20-2 What Is a Stream? ................................................................................................................... 20-3 InputStream, OutputStream, Reader and Writer .................................................................... 20-4 Files ........................................................................................................................................ 20-5 Stream Classes of java.io.* .................................................................................................... 20-9 Serialization .......................................................................................................................... 20-17 Lesson 20 Review ................................................................................................................. 20-24

Lesson 21: Networking in Java ............................................................................................... 21-1 Pre-Assessment Questions ...................................................................................................... 21-2 What Is Networking? .............................................................................................................. 21-3 Connecting Computers Across the Internet ............................................................................ 21-3 Networking Classes of java.net.* ........................................................................................... 21-6 The Java Client/Server Model ................................................................................................ 21-7 Building the EchoServer ......................................................................................................... 21-7 Multithreading Your Client/Server Example ....................................................................... 21-13 Lesson 21 Review ................................................................................................................. 21-20

Appendixes....................................................................................................................Appendix-1

Glossary ......................................................................................................................... Glossary-1

Index .................................................................................................................................... Index-1

Supplemental CD-ROM Contents .................................... Supplemental CD-ROM Contents-1

Page 17: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

ix

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

List of Labs

Lab 1-1: Compiling and running your first Java program ........................................................... 1-6 Lab 2-1: Using primitive variables and operators ...................................................................... 2-11 Lab 3-1: Using while and for loops ............................................................................................. 3-9 Lab 7-1: Implementing inheritance in Java ................................................................................. 7-6 Lab 8-1: Building constructors in Java ...................................................................................... 8-14 Lab 9-1: Using interfaces and polymorphism in Java ............................................................... 9-11 Lab 10-1: Using encapsulation, accessors and mutators in Java ............................................... 10-9 Lab 11-1: Creating basic Swing components .......................................................................... 11-23 Lab 12-1: Creating sophisticated layouts in Java .................................................................... 12-15 Lab 13-1: Drawing to a JFrame............................................................................................... 13-12 Lab 14-1: Implementing a WindowListener for event handling in Java .................................. 14-13 Lab 15-1: Event-enabling your Java drawing application ......................................................... 15-7 Lab 16-1: Converting a Java application into an applet .......................................................... 16-15 Lab 18-1: Creating a threaded digital clock in Java ................................................................ 18-15 Lab 19-1: Enhancing the digital clock with advanced thread techniques in Java ................... 19-17 Lab 20-1: Creating a simple word processor in Java ............................................................... 20-22 Lab 21-1: Building a client/server chat system ........................................................................ 21-17

List of Figures Figure 1-1: Java development cycle ............................................................................................ 1-4 Figure 2-1: Casting rules chart ..................................................................................................... 2-7 Figure 4-1: Value of myInteger following initialization ............................................................ 4-6 Figure 4-2: Value of method local variable tmpInt .................................................................... 4-6 Figure 5-1: Default values stored in myIntArray ....................................................................... 5-3 Figure 5-2: Values stored in myIntArray following initialization .............................................. 5-5 Figure 5-3: Two references to same array ................................................................................... 5-6 Figure 5-4: Lost array reference .................................................................................................. 5-7 Figure 6-1: tmpEmp variable ..................................................................................................... 6-10 Figure 7-1: Hierarchy of classes .................................................................................................. 7-6 Figure 10-1: Access levels ......................................................................................................... 10-5 Figure 10-2: Object encapsulation ............................................................................................. 10-8 Figure 11-1: Portion of Swing API and relation to AWT .......................................................... 11-5 Figure 11-2: Output of ImageIconStuff .................................................................................. 11-8 Figure 11-3: Output of JButtonStuff .................................................................................... 11-10 Figure 11-4: New output of JButtonStuff is same................................................................ 11-10 Figure 11-5: Output of LabelStuff ........................................................................................ 11-12 Figure 11-6: Output of JScrollBarStuff .............................................................................. 11-13 Figure 11-7: Output of JTextFieldStuff .............................................................................. 11-14 Figure 11-8: Output of JTextAreaStuff ................................................................................ 11-15 Figure 11-9: Output of JScrollPaneStuff ............................................................................ 11-17 Figure 11-10: Output of JfileChooserStuff ........................................................................ 11-20 Figure 11-11: Output of JFrameStuff .................................................................................... 11-21 Figure 11-12: Output of JFrameStuff with JButton ............................................................. 11-22 Figure 11-13: Output of JPanelStuff .................................................................................... 11-23

Page 18: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

x

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Figure 12-1: FlowLayout resized .............................................................................................. 12-6 Figure 12-2: Output of FlowLayoutStuff ................................................................................ 12-7 Figure 12-3: Output of GridLayoutStuff ................................................................................ 12-8 Figure 12-4: Example of BorderLayout regions ...................................................................... 12-8 Figure 12-5: Output of BorderLayoutStuff ............................................................................ 12-9 Figure 12-6: Output of BoxLayoutStuff ................................................................................ 12-10 Figure 12-7: Output of BoxLayoutStuff with struts ........................................................... 12-12 Figure 12-8: Output of BoxLayoutStuff with glue ............................................................... 12-13 Figure 12-9: Example of a sophisticated layout ...................................................................... 12-13 Figure 12-10: Output of NestedLayoutStuff ........................................................................ 12-15 Figure 12-11: Sophisticated GUI model .................................................................................. 12-16 Figure 13-1: AWT class hierarchy (Graphics section) ............................................................. 13-4 Figure 13-2: Coordinate system for positioning graphics.......................................................... 13-5 Figure 13-3: Output of PaintingStuff .................................................................................... 13-6 Figure 13-4: Output of PaintingStuff with rectangle ............................................................ 13-9 Figure 13-5: Output of PaintingStuff with colors ............................................................... 13-10 Figure 13-6: Output of PaintingStuff with fonts ................................................................. 13-12 Figure 13-7: JFrame model ...................................................................................................... 13-13 Figure 14-1: Interface with JButtons and JTextArea ........................................................... 14-10 Figure 14-2: Sources and event types generated ...................................................................... 14-14 Figure 15-1: Drawing application .............................................................................................. 15-7 Figure 16-1: JApplet class hierarchy ........................................................................................ 16-3 Figure 16-2: Output of MyJApplet ............................................................................................ 16-8 Figure 16-3: Output of MyApplication .................................................................................. 16-12 Figure 16-4: Output of MyJApplet after conversion from application .................................... 16-13 Figure 16-5: Output of MyJApplet after conversion to application ........................................ 16-14 Figure 17-1: Exception class hierarchy .................................................................................... 17-5 Figure 17-2: Overridden method ............................................................................................. 17-11 Figure 18-1: Main thread ........................................................................................................... 18-5 Figure 18-2: Thread states ....................................................................................................... 18-11 Figure 18-3: DigitalClock interface ...................................................................................... 18-15 Figure 19-1: Deadlock ............................................................................................................. 19-16 Figure 20-1: Wrapper streams ................................................................................................. 20-14 Figure 20-2: Word processor GUI ........................................................................................... 20-22 Figure 21-1: Connecting Computer A to Computer B............................................................... 21-5 Figure 21-2: Client GUI ........................................................................................................... 21-17

Page 19: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

xi

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

List of Tables Table 2-1: Primitive data types in Java ........................................................................................ 2-3 Table 2-2: Default values for class variables in Java ................................................................... 2-5 Table 2-3: Relational operators in Java ....................................................................................... 2-8 Table 8-1: Common methods of String ................................................................................... 8-12 Table 16-1: Methods inherited from the Applet class ............................................................ 16-10 Table 18-1: Methods used to control single thread .................................................................... 18-9 Table 20-1: Methods of File class ............................................................................................ 20-6 Table 20-2: Useful stream classes .............................................................................................. 20-9 Table 21-1: Well-known ports and their protocols .................................................................... 21-5 Table 21-2: Common networking classes .................................................................................. 21-6

Page 20: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

xii

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 21: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

xiii

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Course Description The Java Programming Fundamentals course teaches you how to write Java applications and applets. You will learn the Java language mechanics found in other programming languages, such as variables, iterations, control statements, methods and arrays. You will also discuss object-oriented theory as it relates to Java. You will create Graphical User Interfaces (GUIs) for both applications and applets, emphasizing components, layouts, and graphics. The course concludes with an in-depth study and implementation of the SDK 1.2 event delegation model, an essential element in further Java studies. You will also complete a course-long project to create an operational client/server messaging system.

Upon completion of this course, you will be experienced in writing Java applications and applets. We recommend and will frequently refer you to another excellent Java resource, David Flanagan's Java in a Nutshell. Students who plan to pursue the jCert Level I Certification or the Sun Java Programmer certification are encouraged to study the CIW Sun Certified Java Programming Exam Preparation Guide when preparing for the exams.

Length

Java Programming Fundamentals is a 30-hour course.

Series

Java Programming Fundamentals is a single course representing the CIW Java Programming series. This series is part of the Master CIW Enterprise Developer track as well as the jCert Initiative. For students interested in the jCert Level I certification or the Sun Java Programmer certification, we recommend the CIW Sun Certified Java Programmer Exam Preparation Guide.

Prerequisites

Students must have a basic knowledge of programming fundamentals before taking this course.

Page 22: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

xiv

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

ProsoftTraining Courseware This coursebook was developed for instructor-led training and will assist you during class. Along with comprehensive instructional text and objectives checklists, this coursebook provides easy-to-follow hands-on labs and a glossary of course-specific terms. It also provides Internet addresses needed to complete some labs, although due to the constantly changing nature of the Internet, some addresses may no longer be valid.

The student coursebook is organized in the following manner:

���� course title

���� table of contents

���� list of labs

���� list of figures

���� list of tables

���� appendixes

���� supplemental CD

���� lessons

���� lesson objectives

���� narrative text

���� labs

���� lesson review

���� lesson summary

� warnings

� tech notes

� graphics

� tables and figures

� warnings

� tech notes

� graphics

� tables and figures

���� pre-assessment questions

���� glossary

���� index

Page 23: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

xv

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

When you return to your home or office, you will find this coursebook to be a valuable resource for applying the skills you have learned. Each lesson concludes with questions that review the material. Lesson review questions are provided as a study resource only and in no way guarantee a passing score on CIW exams.

The course is available in either an academic or a learning center version, and each version has an instructor book and a student book. Check your book to verify that you have the correct version, and whether it is an instructor or a student book. Following is a brief description of each version.

• Academic: Designed for students in an academic classroom environment; typically taught over a quarter (10-week) or semester (16-week) time period. Example syllabi for both time frames are included on the instructor CD-ROM. The instructor's book and CD-ROM contain all answers, as well as optional labs (computer-based labs), quizzes, a course assessment, and handouts for the instructor to assign during class or as homework. No answers exist in the student book or on the student CD-ROM. Students must obtain answers from the instructor.

• Learning Center: Designed for students in a learning center classroom environment; typically taught over a one- to five-day time period (depending on the length of the course). An example implementation table is included on the instructor CD-ROM. Similar to the academic version, the instructor's book and CD-ROM contain all answers, as well as optional labs (computer-based labs), quizzes, a course assessment, and handouts for the instructor to assign during class or as homework. However, the student CD-ROM also contains answers, including those to the pre-assessment questions, labs, review questions, optional labs, quizzes, and the course assessment.

Page 24: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

xvi

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Course Objectives After completing this course, you will be able to:

• Describe the Java Runtime Environment (JRE).

• Use Java variables, control statements, methods and arrays.

• Discuss object-oriented theory, including abstraction, encapsulation, inheritance and polymorphism.

• Describe method overloading and overriding.

• Use Java static and instance members.

• Create Java constructors.

• Identify the differences between instance and class members.

• Use Java abstract classes and interfaces.

• Use Java Strings and StringBuffers.

• Describe Java packages and accessibility.

• Use the Java Abstract Windowing Toolkit (AWT) and Swing components central to SDK 1.2.

• Use the SDK 1.2.x event delegation model.

• Define applets and the applet life cycle.

• Throw exceptions.

• Create threads.

• Use streams.

• Create network applications in Java.

Page 25: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

xvii

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Classroom Setup Your instructor has probably set up the classroom computers based on the system requirements listed below. Most software configurations on your computer are identical to those on your instructor's computer. However, your instructor may use additional software to demonstrate network interaction or related technologies.

System Requirements

Hardware

The following table summarizes the hardware requirements for all courses in the CIW program. Each classroom should be equipped with enough personal computers to accommodate each student and the instructor with his or her own system.

Note: The CIW hardware requirements are similar to the lowest system requirements for Microsoft implementation (Level 1 requirements) except that CIW requires increased hard disk space (8 GB) and RAM (128 MB). This comparison may be helpful for the many training centers that implement CIW and are also CTEC because personnel at these centers are familiar with the Microsoft hardware specifications.

CIW hardware specifications Greater than or equal to the following

Processor Intel Pentium II (or equivalent) personal computer with processor speed greater than or equal to 300 MHz

L2 cache 256 KB

Hard disk 8-GB hard drive

RAM At least 128 MB

CD-ROM 32X

Network interface card (NIC) 10BaseT or 100BaseTX (10 or 100 Mbps)

Sound card/speakers Required for instructor's station, optional for student stations

Video adapter At least 4 MB

Monitor 15-inch monitor

Network hubs Two 10-port 10BaseT or 100BaseTX (10 or 100 Mbps) hubs

Router Multi-homed system with three NICs (Windows NT 4.0/2000 server)*

* Must meet universal CIW hardware requirements.

Page 26: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

xviii

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Software

The recommended software configurations for computers used to complete the exercises in this book are as follows.

• Microsoft Windows 2000 or Millennium Edition (Me), Red Hat Linux 7.x, or any operating system with an available Java 2 SDK

• Sun Java 2 Software Development Kit (SDK), Standard Edition, version 1.2 or later

• Netscape Navigator 6 or higher.

Connectivity

The minimum requirement is a networked classroom with TCP/IP installed. Each computer should have it own IP address, or have local loop-back capability (IP 127.0.0.1). Internet connectivity is not required, but it is helpful.

Page 27: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

xix

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Conventions and Graphics Used in This Book The following conventions are used in Prosoft coursebooks.

Terms Technology terms defined in the margins are indicated in bold the first time they appear in the text. Not every word in bold is a term requiring definition.

Lab Text Text that you enter in a lab appears in bold. Names of components that you access or change in a lab also appear in bold.

Notations Notations or comments regarding screenshots, labs or other text are indicated in italic type.

Program Code or Commands

Text used in program code or operating system commands appears in the Lucida Sans Typewriter font.

The following graphics are used in Prosoft coursebooks.

Tech Notes point out exceptions or special circumstances that you may find when working with a particular procedure. Tech Notes that occur within a lab are displayed without the graphic.

Tech Tips offer special-interest information about the current subject.

Warnings alert you about cautions to observe or actions to avoid.

This graphic signals the start of a lab or other hands-on activity.

Each lesson summary includes an Application Project. This project is designed to provoke interest and apply the skills taught in the lesson to your daily activities.

Each lesson concludes with a summary of the skills and objectives taught in that lesson. You can use the Skills Review checklist to evaluate what you have learned.

Page 28: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

xx

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 29: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

1Lesson 1:

Java Runtime Environment

Objectives By the end of this lesson, you will be able to:

� Identify the differences between stand-alone applications and applets.

� Describe the role of the Java Virtual Machine (JVM).

� Create a simple Java program.

� Use Java comments.

� Compile and execute a Java program.

� Describe the differences between *.java and *.class files.

Page 30: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

1-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. What type of files are generated by the javac compiler?

a. Text files b. *.java files c. *.class files d. *.exe files

2. Which of the following employs the Java syntax for a multiline comment?

a. // This is a comment. b. /* This is a comment */ c. /** This is a comment */ d. /** This is a comment. **/

3. What benefit does the use of a virtual machine provide to Java developers?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 31: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 1: Java Runtime Environment 1-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The Java Virtual Machine Java is an object-oriented programming language developed at Sun Microsystems that is widely known for its portability. This platform independence makes Java ideal for Internet development. The Internet connects a wide variety of hardware and software systems. Java can be used to create a single program that will operate the same on many platforms. Even if you have never programmed using Java before, you are probably familiar with Java applets. Applets are small Java programs that can only be executed from within a Web browser. A Web site employing an applet will provide the same compiled program to Web browsers on all platforms. Java can also be used to create stand-alone applications.

The Java Virtual Machine (JVM) gives Java its platform independence. One of the primary design goals of the Java language is to enable the same code to run on any platform. The JVM is a software program that behaves like an entire computer. By using this artificial computer on different computer platforms (UNIX, Win32, Macintosh, and so forth), you can reuse programs without creating a version for each platform. Your Java programs will always run on a JVM. A Java program can be run on any platform for which a JVM is available.

You will begin writing a simple program by defining a class. A class is a type of container into which all Java code must be placed. You need not be familiar with classes already; you will learn more about them in a later lesson. A class consists of a name and a pair of curly braces to contain the body of the class. By convention, the class name should start with a capital letter as in the following example:

class HelloWorld { }

When you write a stand-alone application, the Java Virtual Machine must know where to begin executing the code. To begin executing code, the JVM looks for and calls a special method by the name of public static void main(String[] args). The JVM uses this method to begin executing your program. Study the following code example:

class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }

applet

A small Java

program that must

be run from a Web

browser.

class

A type of container

into which all Java

code must be

placed. Also, the

template or

blueprint for an

object.

Java Virtual

Machine (JVM)

The artificial

computer that runs

Java programs.

method

A procedural part of

a class that contains

executable Java

statements.

Page 32: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

1-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

This program is complete. Note that Java programs are case-sensitive; the word Class is not read the same as class. You must save the program with your text editor as HelloWorld.java (giving it the same name as your class), and compile it using a Java compiler. You can use the javac program if you have the Java 2 Software Development Kit (SDK) supplied by Sun.

javac HelloWorld.java

The Java compiler converts, or compiles, your source code (saved as HelloWorld.java, a text file) and creates a HelloWorld.class file. This *.class file is no longer a standard text file, but a file compiled into bytecode.

Bytecode is another element that makes Java different from other programming languages. Other compiled programming languages generate machine code binaries, which are files that contain native machine language statements. To make Java portable, the javac compiler generates bytecode. Java bytecode is composed of an instruction set native only to the JVM. Because JVMs exist for multiple platforms, the Java bytecode is portable. Portability, however, comes at a price: speed.

Finally, to launch your program, you must run it in a JVM. You can accomplish this by invoking the Java interpreter java as follows:

java HelloWorld

Note that you type java HelloWorld, not java HelloWorld.class. When you enter the proper command, the JVM will display "Hello World!" in a command line window. The Java application development cycle is shown in Figure 1-1.

*.java *.class Output WindowText Editor javac java

Figure 1-1: Java development cycle

The Java 2 Software Development Kit The development platform used in this class is the Java 2 Software Development Kit (SDK), Standard Edition, version 1.2.2 or later. The Java 2 SDK was previously known as the Java Development Kit (JDK) 1.2. In fact, if you check your installation of the Java 2 SDK, you will find that the directory reads JDK 1.2.2. The Java 2 SDK is backward-compatible with JDK 1.1. It contains several components, including:

bytecode

A platform-neutral

file consisting of

bytes that the JVM

can execute.

Page 33: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 1: Java Runtime Environment 1-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The Java Runtime Environment (JRE), which provides the JVM.

• The development tools and compilation libraries necessary to create Java applications, servlets and applets. This grouping includes the Java compiler, debugging programs, and tools to run applets without a browser.

This coursebook is written to the Java 2 specification.

Java Comments Throughout the course, you will find it useful to add comments to your code. Java supports three types of comments; two will be recognizable to those familiar with C or C++, and the third type is unique to Java.

The three types of comments are as follows:

• Single-line comment //

• Multiline comment /* … */

• Javadoc comment /** … */

The following code shows examples of all three comment types:

class HelloWorld { /**

This is a javadoc comment. It is a multiline commment unique to Java.

If you use the javadoc utility (which comes with Java), it will automatically create HTML-based documentation for you. The online help that comes with the Sun SDK was created using javadoc comments. */ public static void main(String[] args) { System.out.println("Hello World!"); // Two forward slashes indicate a single-line comment. // Notice that each line must begin with the // two forward slashes. /*

This is a multiline comment. It is possible to have multiple lines of code within this block.

*/ } }

Page 34: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

1-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

You will use the single-line and multiline comments similar to C++.

Lab 1-1: Compiling and running your first Java program

In this lab, you will write, compile and run your first Java program. As you finish the lab, note the difference between the source file you write (*.java) and the bytecode that is generated (*.class). A Java application always starts with the public static void main(String[] args) method.

1. Editor: Create a new text file and enter the following Java code:

class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }

2. Editor: Save the file as HelloWorld.java .

3. Prompt: Compile HelloWorld.java to generate a *.class file. From the command line, enter the following:

javac HelloWorld.java

4. Prompt: Execute HelloWorld. From the command line, enter the following:

java HelloWorld

5. Editor: Add another System.out.println("Hello Solar System!"); to the main method.

6. Prompt: Compile and execute your program.

7. (Optional) Modify the public static void main(String[] args) method in any way you choose (for example, delete the word void). What happens?

8. (Optional) Add some comments to the file to document each step that you made while programming this application.

Page 35: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 1: Java Runtime Environment 1-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

When Java was originally released, it was widely praised for its platform independence. This platform independence made Java applets possible, allowing Web site operators to develop applications that could be downloaded and executed by any client with a compatible browser, regardless of platform. Search the Web for at least five examples of Java applets in which the functionality could not be easily duplicated using server-side or client-side scripting technologies.

Skills review

Java consists of three types of programs: applications, applets, and servlets. In this lesson, you learned that applications contain a main method. After the program is written as a text source file (having a name *.java), the program is converted into bytecode (having a name *.class) by the Java compiler. The compiled bytecode can be executed using the Java interpreter. In the following lessons, you will learn the basic syntax of the Java programming language.

Now that you have completed this lesson, you should be able to:

� Identify the differences between stand-alone applications and applets.

� Describe the role of the Java Virtual Machine (JVM).

� Create a simple Java program.

� Use Java comments.

� Compile and execute a Java program.

� Describe the differences between *.java and *.class files.

Page 36: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

1-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 1 Review

1. How does a Java applet differ from a Java application?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

2. What is the Java Virtual Machine (JVM)?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

3. What is a class?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

4. What is a method?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

5. Are Java programs case-sensitive? Give an example that describes its policy.

_______________________________________________________________

_______________________________________________________________

Page 37: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 1: Java Runtime Environment 1-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

6. What is bytecode? How does it affect Java's portability?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

7. Identify the three types of comments you can use in Java.

_______________________________________________________________

_______________________________________________________________

8. How does a *.java file differ from a *.class file?

_______________________________________________________________

_______________________________________________________________

Page 38: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

1-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 39: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

2Lesson 2:

Data Types, Variables and

Operators

Objectives By the end of this lesson, you will be able to:

� Use primitive data types.

� Declare a variable.

� Distinguish between local and class variables.

� Distinguish between implicit and explicit casting.

� Use the operators for primitive types.

Page 40: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

2-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. What output is generated by the following code segment?

1. int i = 257; 2. byte b = (byte) i; 3. System.out.print(b);

a. 1 b. 25 c. 57 d. 257

2. What output is generated by the following code segment?

1. int i = 5; 2. if (i < 5 && ++i == 6) 3. ; 4. i += i; 5. System.out.println(i++);

a. 10 b. 11 c. 12 d. 13

3. Under what circumstances does Java require explicit casting?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 41: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 2: Data Types, Variables and Operators 2-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Data Types Java is considered to be a strongly typed language. If you want to use a variable, Java requires you to declare the type of information that this variable can store, and the compiler strictly enforces typing rules. Java has eight primitive data types, or primitives (also known as elemental or simple types): byte, short, int, long, float, double, char, and boolean. You can divide these data types into four categories, as shown in Table 2-1.

Table 2-1: Primitive data types in Java

Type Name Size Range

Integers

byte 8 bits -128 to 127 (-27 to 27-1)

short 16 bits -32,768 to 32,767 (-215 to 215-1)

int 32 bits -2,147,483,648 to 2,147,483,647 (-231 to 231-1)

long 64 bits ~-9.2 x 1015 to ~9.2 x 1015 (-263 to 263-1)

Floating-point numbers

float 32 bits ~-3.4 x 1038 to ~3.4 x 1038

double 64 bits ~-1.8 x 10308 to ~1.8 x 10308

Character

char 16 bits 0 to 65,535

Boolean

boolean 1 bit false or true

Note that the size of the various Java primitives is fixed and does not vary from one platform to another. For instance, a variable of type int is always 16 bits, regardless of the hardware used. Under many other programming languages, the size of various primitive data types is dependent on the hardware being used. By fixing the size of data types across all systems, portability is protected. Now that you know the data types, you can declare variables in Java.

strongly typed

Term used to

describe a

language. Requiring

that the

programmer specify

the kind of

information that

each variable can

hold.

primitive data types

The basic data

building blocks of

the language; all

the primitives consist

of a single value.

Page 42: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

2-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Declaring Variables To declare a variable, Java requires a type and an identifier ; optionally, you can add an initial value. Identifiers start with a letter and can contain letters, numbers and underscore characters ( _ ). An identifier can be any length, but must contain no embedded spaces or special characters. For example, to declare an integer that stores the value of 40, you can use the following statement:

int age = 40;

In this example, int is the type, age is the identifier (which starts with a lowercase letter by convention), and 40 is the initial value. The preceding statement could also be written as follows:

int age; age = 40;

Boolean variables have the value false or true. You cannot use 0 or 1 as in other languages. For example, the following is a valid Java statement:

boolean isRunning = false;

Characters are not the 8-bit ASCII representations as found in other languages; they are 16-bit Unicode characters in Java. Sixteen bits allows for 65,536 possible characters, and is considered adequate to represent the most-used characters in most written languages. With this approach, Java intends to be a truly international language. Unicode characters are represented by their hexadecimal values (between '\u0000' and '\uFFFF'). Standard English characters can be specified either as their literal Unicode values, or within single quotes such as 'A' or '7' as follows:

char letter = 'A';

Variable Scope Java supports three types of variables: local variables, class variables, and instance variables. In this section, you will be introduced to local and class variables. You will learn more about instance variables in a later lesson.

Local variables are defined within a method. So far, all of the programs you have seen contain only a single method named main. You should be aware, however, that classes may contain multiple methods. Variables declared inside a method are local variables; that is, they are local to the method in which they are defined. A variable declared within the main method cannot be accessed from other methods.

identifier

Another term for a

variable, method or

class name.

local variable

A variable defined

inside a method.

Local variables are

not available from

outside a method.

class variable

A variable defined

outside of any

method using the

keyword static.

Class variables are

available

throughout the

class.

Page 43: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 2: Data Types, Variables and Operators 2-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Class variables are defined within the body of a class but outside the body of any method. Class variables are always declared using the static keyword. The static keyword instructs the compiler to treat a variable as a class variable and not as an instance variable. You will learn more about the difference between class and instance variables in a later lesson. Class variables can be accessed from anywhere within a class. The following Java code declares both a local variable and a class variable:

class MyProgram { // This is a comment static int totalcount = 0; // class variable public static void main(String[] args) { char male = 'm'; // local variable System.out.println("Total count = " + totalcount); } }

In this example, a class variable named totalcount is declared and initialized. Notice that the totalcount variable is accessible from the main method. A local variable is declared within the main method. The variable, male, is only accessible from within the main method.

Default variable values

One Java peculiarity is the default initial values of variables. Both class variables and instance variables default to certain values. Table 2-2 lists the default value for each data type.

Table 2-2: Default values for class variables in Java

Data Type Default Value

byte, short, int, long 0

float, double 0.0

char '\u0000' (the null character)

boolean false

non-primitive types null

Local variables do not have default values and must be initialized.

Page 44: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

2-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Casting With all the data types that Java supports, it is often necessary to convert data from one type to another. This process is called casting and it is performed in several different ways.

Implicit casting

Implicit casting occurs automatically when you store data from a smaller data type to a larger type. Consider a variable of type byte. A byte is 8 bits, so a variable of type byte can store any number from –128 to 127. A short is 16 bits, so a variable of type short can store any number from –32,768 to 32,767. If you wanted to store a byte inside a variable of type short, you could do so using implicit casting because there is no possibility that data may be lost. That is, a short is larger than a byte, so any data that could be represented using a byte could also be represented using a short. The following Java code demonstrates implicit casting:

byte b = 50; short s = b;

In this example, a variable of type byte is declared and initialized. Next, a variable of type short is declared, and the byte-sized data stored in variable b is now stored within the short. This conversion from a byte to a short is performed automatically and provides an example of implicit casting.

Explicit casting

Although a short can always be used to represent a byte, the opposite is not true. A short is larger than a byte, so the possibility exists that data may be lost if you cast a short to a byte. Java requires you to acknowledge this possibility any time you attempt a type conversion that may result in lost data. This acknowledgment is called explicit casting. The following Java code demonstrates explicit casting:

short s = 100; byte a = (byte) s; // Explicit cast is required byte b = s; // Will not compile!

In this example, a variable of type short is declared and initialized. Following this, two variables of type byte are declared. Variable a uses explicit casting to convert the data stored in variable s to type byte. The explicit cast is the name of data type to which you want to convert, enclosed within parentheses. The last line attempts to perform an implicit cast from a short to a byte. This conversion is not allowed, thus the compiler will generate an error indicating that an explicit cast must be used.

casting

The process of

converting values

from one data type

to another.

implicit casting

The form of casting

that occurs

automatically when

data loss is not

possible.

explicit casting

Casting performed

by explicitly

declaring the more

restrictive data type

to which you intend

to convert.

Page 45: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 2: Data Types, Variables and Operators 2-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Other casting rules also apply. No conversions are allowed between boolean and any other data type. Also, the cast from a floating-point type to an integer type must be explicit regardless of the specific type. You can expect to lose the fractional part of the float after the cast. Integer types can be implicitly cast to floating-point types. Of course, any implicit cast can be explicitly stated:

byte b = 50; short s = (short) b;

In general, casting rules follow an elegant order, as shown in Figure 2-1.

byte short int long float double

char

Figure 2-1: Casting rules chart

This chart says that a byte can be assigned to a short or float, but a double cannot be assigned to a float, int or byte without an explicit cast.

Note that the char type holds a 16-bit number representing the Unicode value for a particular character. The following code demonstrates the implications of this:

char c = 97; System.out.println(c); // prints a lowercase 'a' int i = 'a'; System.out.println(i); // prints the number 97

Operators Java supports the standard array of arithmetic , bitwise, relational and logical operators. The entire list of operators is found in David Flanagan's book Java in a Nutshell.

Arithmetic operators

The modulus operator (%) performs a division operation and returns the remainder. The modulus operator works for both integers and floating points. The following Java code demonstrates the modulus operator:

int a = 24; double b = 24.2; System.out.println("a%10 = " + a%10) // would result in 4 System.out.println("b%10 = " + b%10) // would result in 4.2

arithmetic operators

Operators that

perform

manipulation on

numbers.

bitwise operators

Operators that

perform logical

manipulation

comparing and

changing each bit.

relational operators

Operators that

compare values of

variables; all

evaluate to the

boolean data type (false or true).

logical operators

Operators that allow

you to combine two

or more relational

operators.

Page 46: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

2-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Increment (++) and decrement (--) operate on a single variable to increase or decrease by one. The following Java code demonstrates the increment and decrement value operators:

int a = 1; a++; // a now equals 2. This is the same as a = a + 1. a--; // a now equals 1 again, same as a = a - 1.

Note that the increment and decrement operators have both a prefix and a postfix form. Using the prefix form, the variable is incremented before the rest of the expression is evaluated. In the postfix form, the variable is incremented after the rest of the expression is evaluated. The following Java code demonstrates the difference between the prefix and postfix forms of the increment and decrement operators:

int a = 1; int b = ++a; // a is incremented to 2 and b is set to 2. int c = a—-; // c is set to 2 before a is decremented to 1.

The assignment operators also work as they do in C and C++. For example:

int a = 1; a += 10; // a now equals 11. The same as a = a + 10; a -= 5; // a equals 6. Same as a = a - 5 a *= 2; // a = 12. Same as a = a * 2;

Relational operators

As in C and C++, comparison for equality is performed with the double equal signs (==) instead of a single equal sign (=). Relational operators always produce a Boolean result. The following Java code demonstrates the equality operator:

int a = 4; // Assigns the value of 4 to a. if(a == 4) // This asks "does a equal 4?" // This would evaluate to true.

Table 2-3 lists the complete set of relational operators.

Table 2-3: Relational operators in Java

Relational Operator Comparison Value

== Equal

!= Not equal

< Less than

<= Less than or equal to

Page 47: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 2: Data Types, Variables and Operators 2-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Table 2-3: Relational operators in Java (cont'd)

Relational Operator Comparison Value

> Greater than

>= Greater than or equal to

Logical operators

Logical expressions (used in conditional statements such as if and while loops) must be boolean. In other languages, numeric expressions can be substituted and evaluated; Java does not allow this.

Java supports short-circuit logical operators for the AND (&&) and OR (||) operators. These operators allow you to bypass evaluation of part of the expression if the value of the entire expression has already been determined. Study the following examples:

int a = 2; int b = 2; if(a == 1 && b == 2) // b == 2 would not be evaluated // because a == 1 is false. if(a == 2 && b == 2) // Both expressions must be tested // to determine if the expression // is true. if(a == 1 || b == 2) // Here, both expressions will be // evaluated because a == 1 // is false. if(a == 2 || b == 2) // This time only a == 2 is // evaluated because it is true and // sufficient to determine if the // expression is true.

if(a == 1 && ++b == 2) // Notice that because // the first condition // fails, b is never // incremented.

short-circuit

operators

Operators that do

not evaluate all the

relational operations

unless necessary.

Page 48: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

2-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Bitwise operators

The bitwise operators can be used to modify variables at the bit level. The operators are right shift (>>), left shift (<<), and right shift not keeping the sign bit (>>>). The point of emphasis here is on the difference between the >> and >>> operators, which is demonstrated in the following program:

class BitShifter { public static void main(String[] args) { int i = 0x80000000; int answer1, answer2; answer1 = i >> 3; answer2 = i >>> 3; System.out.println("initially: " + i); System.out.println(">> 3: " + answer1); System.out.println(">>> 3: " + answer2); } }

The output of this program is as follows:

C:\Prosoft\Java>java BitShifter initially: -2147483648 >> 3: -268435456 >>> 3: 268435456

Automatic Casting Be warned that automatic casting can sometimes become confusing because Java automatically casts bytes or shorts into ints, and floats into doubles when dealing with arithmetic expressions. Consider the following example:

byte a = 8; byte b = 8; byte c = a * b; // This would fail because a * b is // implicitly cast as an int. int c = a * b; // Either of these two statements work. byte c = (byte)(a * b);

Page 49: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 2: Data Types, Variables and Operators 2-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Java requires this explicit cast as a warning to the programmer that some data may be lost. An int is 32 bits; a byte is only 8 bits long. When you perform this explicit cast, the high 24 bits are lost. The following example demonstrates this point:

byte a = 100; byte b = 100; byte c = (byte)(a * b); System.out.println(a*b); System.out.println(c);

In the first println statement, the expression a*b is an integer and the result is 10000, as you would expect. In the second println statement, the high 24 bits are lost and the result is a surprising 16.

If you tried the optional Step 5 in the preceding lesson's lab, then you already experienced one of the most frustrating errors that can occur with new Java programmers. You will explore several ways to avoid this error later in the course.

Lab 2-1: Using primitive variables and operators

In this lab, you will use basic operators, and practice declaring and using Java's primitive data types. Later in this course, you will create your own variable types by writing classes and interfaces that will be incorporated into the project.

Continue working with the HelloWorld.java file you created in the previous lab.

1. Create eight local variables in the main method, one for each primitive data type.

2. Print all eight data types. For example: System.out.println("This is a byte: " + myByte);

3. Continue to add to your main method by testing the following declarations to see if they work. If they do not work, fix them. Print whatever results are needed.

Page 50: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

2-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Note: Be creative with your solutions; more than one solution can be correct.

int a = 30; byte c = 129; float e = 11.2; boolean f = true; long b = a; short d = c; long f = e; char g = f;

4. (Optional) Determine the value of j: float h = 10.2F; int j = 5 * (int)(h%2);

5. (Optional) Create an instance variable (declared outside of the main method) of type long. This will automatically initialize to zero. Print its value from the main method, and try to determine what the compiler is telling you.

Page 51: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 2: Data Types, Variables and Operators 2-13

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Java enforces strict rules and declaring variables and imposes restrictions on implicit casting. Identify at least one programming language that does not have these same restrictions. Consider how that language and Java are used differently. What types of development projects are best suited to relaxed typing rules? What types of projects can benefit from Java's strict enforcement of such rules?

Skills review

In this lesson, you learned about Java's primitive data types and their ranges. The fixed length of these data types is a feature that makes Java more portable. You declared a variable, and you learned the differences between local and class variables. You also learned when to use implicit and explicit casting, and you used several operators. The conclusion you should reach from this lesson is that all the standard operators used in other languages are also supported in Java.

Now that you have completed this lesson, you should be able to:

� Use primitive data types.

� Declare a variable.

� Distinguish between local and class variables.

� Distinguish between implicit and explicit casting.

� Use the operators for primitive types.

Page 52: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

2-14 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 2 Review

1. What is a data type, and what is its significance to the Java language?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

2. What is a primitive? Name two other terms for a primitive.

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

3. How does a primitive's length affect Java's portability?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

4. What is an identifier, and what rules apply to its syntax?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

5. How do local variables differ from class variables?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 53: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 2: Data Types, Variables and Operators 2-15

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

6. Which variables have default initial values? Which variables do not?

_______________________________________________________________

_______________________________________________________________

7. What is casting?

_______________________________________________________________

8. How does implicit casting differ from explicit casting?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

9. What four types of operators does Java support? Briefly describe the function of each.

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 54: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

2-16 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 55: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

3Lesson 3:

Control Statements

Objectives By the end of this lesson, you will be able to:

� Explain the block structure of Java.

� Use Java conditional statements (if/else and switch).

� Use Java iterative statements (while, do/while and for).

Page 56: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

3-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. What output is generated by the following code segment?

switch (5) { default: System.out.print(4); case 1: System.out.print(1); case 2: System.out.print(2); break; case 3: System.out.print(3); }

a. 5 b. 4 c. 412 d. 4123

2. What output is generated by the following code segment?

for (int i = 1; i < 4; i++) System.out.print(i++);

a. 13 b. 24 c. 135 d. 246

3. What is the difference between a while loop and a do while loop?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 57: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 3: Control Statements 3-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Code Blocks Java uses curly braces {} to define the beginning and end of a code block. A block is used to group the contents of a class or a method, and to designate all conditional and iterative statements. Code blocks are also used for exception handling, which will be discussed in a later section. Blocks can be used any time you want to set aside a piece of code. The placement of the curly braces is a matter of style.

The following style is common in many environments. The opening curly brace immediately follows the class name, and no indentation is used for curly braces:

class MyClass { // Many IDEs // default // to this // style. }

The next style places each curly brace on its own line but still uses indentation only for the contents of the method:

void myMethod() { // Considered // the // easiest to // read. }

This style uses subordinate levels of indentation for each method component:

if(age >= 50) { // Classic // style. }

The following style mixes indentation levels and can be difficult to interpret:

for(; i < 10; i++) { // Mixed // style, // not recommended. }

code block

A sequence of

statements

contained in curly

braces.

Page 58: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

3-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Conditional Statements Conditional statements are used to ask questions. The two types of conditionals are if statements and switch/case statements.

The if statement

The if statement makes a choice between two options. The syntax for the if statement is as follows:

if (boolean_expression1) { // One or more lines of code. } else if (boolean_expression2) // OPTIONAL { // Still more lines of code. } else // OPTIONAL { // Yet more lines of code. }

Following is an example of an if statement (with all the optional flourishes):

if (age < 30) { System.out.println("You are not old enough"); } else if (age < 59) { System.out.println("You are middle-aged"); } else { System.out.println("You have earned experience points"); }

Each if and else if statement is followed by a Boolean expression enclosed by parentheses. The Boolean expression must evaluate to true or false; an error will occur if the condition is not a Boolean expression. The construct can contain zero or more else if portions. The else portion is also optional and executes only if all the Boolean expressions that precede it evaluate as false. The curly braces are not required if only one line of code is used for any block. However, this course will always use the braces for clarity.

Remember that a Boolean expression always evaluates

to true or false, not 0 or 1 as in some other languages.

if statement

The basic

conditional

statement; chooses

one path or the

other.

Boolean expression

An expression that

evaluates as either

true or false; the

result of a relational

or logical operation.

Page 59: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 3: Control Statements 3-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The switch/case statement

The switch statement allows a choice from a number of options. Following is the syntax for the switch statement:

switch (char, byte, short or int type variable) { case value: // block to execute break; case value: // block to execute break; default: // block to execute }

If the break is not present, the next case will also be

executed. This allows several case blocks to execute the

same code.

The break statement

The break statement breaks out of the switch statement. Without the break, the program would "fall through" and execute the next case block. You will usually use a break statement at the end of each case block.

The default option should be the last option in a switch statement. If none of the cases match, the default block is executed. For this course, we will not use the braces in the switch statement, although it is allowable. Following is an example of a switch statement:

int choice = 3; switch(choice) { case 1: System.out.println("You chose #1"); break; case 2: System.out.println("You chose #2"); break; case 3: System.out.println("You chose #3"); break; default: System.out.println("You chose an illegal number"); }

The variable used can be any integer type (byte, short, int) except for long. The variable may also be a char.

switch statement

A more complex

conditional

statement; chooses

from multiple

options.

break statement

A statement that

causes the current

conditional or

iterative statement

to terminate.

Page 60: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

3-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Iterative Statements (Loops) Iterative or loop statements are used to set up and handle processes that must be repeated. The three types of loops are while, do while and for.

The while loop (entry condition loop)

The while loop checks a condition before entering the loop, then executes the loop block if the condition is true. The condition must be a Boolean expression (contained in parentheses like the if statement). The syntax for the while loop is as follows:

while (boolean_expression) { // loop block }

Following is an example of a while loop:

int myNumber = 10; while (myNumber >= 0) { System.out.println(myNumber); myNumber--; }

You should note that this program will count down from 10 to 0, then terminate. If you want to count down to 1 then terminate, change the Boolean expression in the while loop to myNumber > 0.

The do while loop (exit condition loop)

Because the condition is checked first in a while loop, it is possible that the loop may never execute. The second iterative type ensures that the loop block executes at least once by placing the condition at the end of the loop. The syntax for the do

while loop is as follows:

do { // loop block } while (boolean_expression);

entry condition/ exit

condition

Condition based on

whether the

Boolean expression

is evaluated at the

beginning or end of

the loop.

while loop

An iterative

statement that

checks a condition

and executes a

loop block if the

condition evaluates

to true.

do while loop

An iterative

statement that

checks a condition

after executing a

loop block once,

then executes the

loop block again if

the condition

evaluates to true.

Page 61: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 3: Control Statements 3-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The for loop

The while and do while loops are useful for many situations, but you must control the Boolean condition, ensuring that the variables change and eventually make the condition false. If you know how many times you want to iterate, the for loop is probably the best choice. The syntax is as follows:

for (initial_condition; boolean_expression; iteration) { // loop block }

The following steps describe how the for loop works:

1. The initial condition statement (the first portion in parentheses) is executed.

2. The Boolean expression (the second portion in parentheses) is tested to see if it is true. If so, the body of the loop is executed once. If it is false, the for loop is finished.

3. The iteration statement (the third portion in parentheses) is executed following each execution of the loop block.

Following is an example loop that counts from 1 to 10:

for (int count = 1; count <= 10; count++) { System.out.println(count); }

The iteration variable (count) can be declared outside the loop or declared in the for statement as above. In this example, the variable count would be out of scope and unavailable after the loop ends. If the variable is declared before, then it will be available after the termination of the loop.

Nested loops (break and continue)

You can end a loop prematurely by executing a break statement. Because you do not want the loop to end each time, the break statement is placed inside a conditional statement (if). For example:

for (int countDown = 10; countDown >= 0; countDown--) { System.out.println(countDown); if (countDown == 3) { System.out.println("ABORT"); break; } }

for loop

An iterative

statement that

checks a condition

and executes an

iteration variable if

the condition

evaluates to true.

Page 62: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

3-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

This example will count down from 10 to 3, then print ABORT and end the program. If you want to skip one iteration of the loop, you can use the continue statement as follows:

System.out.println("Leap years between 1896 and 1924"); for (int year = 1896; year <= 1924; year += 4) { if ((year % 100) == 0) { continue; } System.out.println(year); }

Because continue and break only work on the current loop, labels can be used to further control the loop. Labels can be placed at the beginning of a loop, and you can continue or break to the label. An example of a label follows:

boolean found = false; outer: for (int row = 0; row < 10; row++) { inner: for (int col = 0; col < 10; col++) { // Some code that may change found to true if (found) { break outer; // Jumps to outer loop } } }

Label identifiers follow the same rules as class or variable

identifiers. Many languages that use labels either

capitalize their first initials or use all uppercase letters.

Most Java reference books use the lowercase style

shown here. Whichever style you choose, use it

consistently.

continue statement

A statement that

terminates the

current iteration of a

loop.

label

An identifier that

points to a specific

line of the code, to

which a loop can

break or continue.

Page 63: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 3: Control Statements 3-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lab 3-1: Using while and for loops

In this lab, you will use two different iterative statements to perform the same operation, demonstrating that programming is often a matter of style.

1. Write a program that generates the script for a NASA countdown using a for loop. The output should appear as follows:

10 9 8 7 6 5 4 3 2 1 LIFTOFF!

2. Repeat Step 1 using a while loop.

3. (Optional) Create an unusual countdown program using the modulus operator such that the output appears as follows:

10 8 6 4 2 0 LIFTOFF!

4. (Optional) Modify Step 3 such that the output appears as follows: 9 7 5 3 1 LIFTOFF!

Page 64: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

3-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

5. (Optional) Create two integer variables, firstYear and lastYear. For any arbitrary firstYear and lastYear, print out all the leap years that exist between the first and last years. Remember that leap years are those years divisible by 4.

Remember that how you choose to use curly braces is a

matter of style. What is important is that you use them

consistently so that others can read your code more

easily.

Lesson Summary

Application project

The simplest type of computer program defines a set of steps and the order in which they are to be executed. Flow control structures such as those discussed in this lesson allow developers to create more complex applications that can make decisions at runtime to determine the order of execution. Create a list of at least five programming projects that would require the use of flow control statements.

Skills review

In this lesson, you learned about Java's block structure and how to create code blocks with curly braces. You also learned to use conditional statements and iterative statements in your code. As you will see throughout this course, Java contains constructors similar to those in all other programming languages.

Now that you have completed this lesson, you should be able to:

� Explain the block structure of Java.

� Use Java conditional statements (if/else and switch).

� Use Java iterative statements (while, do/while and for).

Page 65: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 3: Control Statements 3-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 3 Review

1. What is a code block?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

2. What type of curly braces placement is required for a Java code block?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

3. What is the purpose of a conditional statement? What are the two types of conditional statement?

_______________________________________________________________

_______________________________________________________________

4. What is the purpose of an iterative statement? What are the three types of iterative statement?

_______________________________________________________________

_______________________________________________________________

5. What is a Boolean expression?

_______________________________________________________________

_______________________________________________________________

Page 66: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

3-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

6. What is an entry condition loop? What is an exit condition loop? What type of Java statements do these conditions affect?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

7. What is a label?

_______________________________________________________________

_______________________________________________________________

Page 67: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

4Lesson 4:

Methods

Objectives By the end of this lesson, you will be able to:

� Create and use static methods.

� Return a value from a method.

� Explain pass by value.

� Describe overloading methods.

� Identify the method signature.

Page 68: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

4-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. What output is generated by the following Java code?

class MyClass { public static void main(String args[]) { int i = 1; myMethod(i++); System.out.println(i++); } public static void myMethod(int i) { i++; } }

a. 1 b. 2 c. 3 d. 4

2. What output is generated by the following Java code?

class MyClass { public static void main(String args[]) { byte b = 0; myMethod((long) b); } public static void myMethod(byte i) { System.out.println(1); } public static void myMethod(short i) { System.out.println(2); } public static void myMethod(int i) { System.out.println(3); } public static void myMethod(long i) { System.out.println(4); } }

a. 1 b. 2 c. 3 d. 4

Page 69: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 4: Methods 4-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

3. What is the significance of Java methods' operating using pass by value?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 70: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

4-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Java Methods Other languages call them functions, procedures or subroutines, but object-oriented languages refer to the executable parts of a class as methods. There are two types of methods: class methods and instance methods. In this lesson, you will learn how to write and use class methods. You will learn more about instance methods and how they differ from class methods in a later lesson.

As with variables, a method becomes a class method by the use of the keyword static. The general syntax for a class method is as follows:

[accessModifier] static returnType methodName ([parameterType parameterName, pType2 pName2]) { // body of method }

Access modifiers will be discussed in a later lesson. An example of an access modifier is the word public in public static void main(String[] args) . For now, we will omit the access modifier. The return type can be any Java data type or the type void (denoting no return value). The method name follows the same rules for names as variables, and generally begins with a lowercase letter. All methods are contained within a class and are considered members of their enclosing class. Variables are also considered members of their enclosing class.

Return Statements A method may be designed so that it returns some value. The data type of the return value must be declared with the method declaration. The return type may be any Java primitive or class. If the method will not return a value, then the keyword void is used as the return type. If the return type is not void, then a return statement is required. The value returned must be the same type as the return type. Following is a simple example of a method that determines whether an int is larger than a double. The value will return true if the int is larger, and false if it is not.

static boolean integerLarger (int i, double d) { if (i > d) { return true; } return false; }

method

The executable part

of a class.

member

A general term for

both methods and

variables.

Page 71: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 4: Methods 4-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Calling a Method A method is called by stating the name of the method, followed by the parameters to be passed to the method. To see if the int 42 is larger than the double 12.5, invoke the method integerLarger. Because the return type is a boolean, you can use the method call as you would use any boolean value. For example:

int integerNumber = 42; double doubleNumber = 12.5; if (integerLarger(integerNumber, doubleNumber)) { System.out.println("the integer is larger"); } else { System.out.println("the float is larger"); }

The method can also be invoked with numeric literals such as:

integerLarger(42, 12.5)

Parameters A method may have zero or more parameters. Each parameter has a type and a name. For the duration of the method, the parameters are similar to local variables. The type of a parameter can be either a primitive or a class. We will discuss classes as data types in later lessons.

parameter

The mechanism for

sending information

to a method.

literal

A representation of

an actual value for

a data type.

Page 72: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

4-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pass by Value Note the process that occurs when you call a method. The following method increments the integer parameter by one:

static void incrementInteger (int tmpInt) { tmpInt++; }

The call to this method is as follows:

int myInteger = 42; incrementInteger(myInteger); System.out.println(myInteger);

The main program sets up memory as illustrated in Figure 4-1.

42

myInteger

Figure 4-1: Value of myInteger following initialization

When the method is called, a temporary memory variable is set up for the duration of the method, and a copy of the value of myInteger is placed in this temporary location as illustrated in Figure 4-2.

42

tmpInt

Figure 4-2: Value of method local variable tmpInt

When the value of tmpInt is changed, it does not affect the value of the original variable myInteger. Therefore, the output printed after the call is 42, not 43. This process is referred to as pass by value, because the method has only a copy of the original value. The next lesson will discuss this effect for non-primitive data types.

pass by value

A copy of the value

of the variable is

available to the

method; changes to

the copy do not

affect the original

value.

Page 73: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 4: Methods 4-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Overloading You will often want to use the same method name several times. This practice is known as overloading and is allowed in Java, provided that the methods have different signatures. The method signature consists of the method name and parameter types (order-dependent). The return type is not part of the method signature. For example, suppose you wanted to create several methods that added numbers together. The following methods would all be acceptable even though they are all defined in the same class:

static int addNumbers (int i1, int i2) { return i1 + i2; } static int addNumbers (double d1, int i2) { return (int)d1 + i2; } static int addNumbers (int i1, double d2) { return i1 + (int)d2; } static int addNumbers (int i1, int i2, int i3) { return i1 + i2 + i3; }

Java can determine which method to call based on the data types of the parameters. You could not have added the following methods because they only differ by return type from the preceding methods:

static double addNumbers (int i1, int i2) { } static boolean addNumbers (double d1, int i2) { } static void addNumbers (int i1, int i2, int i3) { }

Overloading of methods is very important in object-oriented programming, which we will discuss in later sections.

overloading

Two or more

methods with the

same name and

different parameter

types; they usually

implement similar

types of operations.

method signature

The method name

and parameter

types; the return

type is not included

in the signature.

Page 74: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

4-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lab 4-1: Writing methods in Java

The ability to design and write methods is a fundamental skill for Java programmers. In this lab, you will practice writing methods. Meaningful implementation of methods will improve the readability and manageability of your code.

1. Create a new text file and enter the following Java code:

public class Exercise4_1 { public static void main (String[] args) { int i1 = 11; int i2 = 5; int iTotal = addNumbers(i1, i2); // Method 1 System.out.println("iTotal: " + iTotal); double d1 = 12.0; double d2 = 3.9; double dTotal = addNumbers(d1, d2); // Method 2 System.out.println("dTotal: " + dTotal); double mixedTotal = addNumbers(i1,d1); // Method 3 System.out.println("mixedTotal: " + mixedTotal); }

2. Implement the three overloaded forms of the addNumbers method.

3. Save the file as Exercise4_1.java.

4. Compile and execute Exercise4_1.java.

5. (Optional) Create a fourth method called orderedOutput that takes the three totals as parameters (iTotal, dTotal, mixedTotal) and displays them from greatest to least.

It is good coding practice to choose a method name

that is descriptive of the action being performed. The

Java convention is to begin method names with a

lowercase letter, then identify new words by capitalizing

the first letter of each subsequent word. For example, a

method meant to set the age of a person might be

named int setAge(int age) as opposed to setage or

SetAge.

Page 75: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 4: Methods 4-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Methods are the building blocks of structured programs. Later in this course, you will learn how classes and objects are the building blocks of object-oriented programs. Methods allow the developer to segregate and reuse code. Describe how methods make the developer's job easier. How does the use of methods help to reduce programming errors, promote code reuse, and facilitate concurrent development of a system by multiple programmers?

Skills review

Methods are one of the defining features of object-oriented programming languages. Overloading of methods allows same-named methods to perform different functions. Members (methods and variables) form the basic foundations of objects, and objects are the key to object-oriented programming.

Now that you have completed this lesson, you should be able to:

� Create and use static methods.

� Return a value from a method.

� Explain pass by value.

� Describe overloading methods.

� Identify the method signature.

Page 76: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

4-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 4 Review

1. What is a method in Java? What do other programming languages call methods?

_______________________________________________________________

_______________________________________________________________

2. What is a member in Java?

_______________________________________________________________

_______________________________________________________________

3. What is a return statement, and when is it required?

_______________________________________________________________

_______________________________________________________________

4. What is a parameter?

_______________________________________________________________

5. What is a literal?

_______________________________________________________________

6. What is pass by value?

_______________________________________________________________

_______________________________________________________________

7. What is overloading?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 77: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 4: Methods 4-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

8. What is the method signature? How is it significant to overloading in Java?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

9. What capitalization scheme does good coding practice dictate for naming methods in Java?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 78: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

4-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 79: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

5Lesson 5:

Arrays

Objectives By the end of this lesson, you will be able to:

� Declare and initialize an array.

� Allocate space for a new array.

� Describe array indexing.

� Use the length property.

� Discuss why arrays are passed by reference.

� Describe Java's garbage collection mechanism.

� Retrieve command line parameters.

Page 80: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

5-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. What output is generated by the following Java code?

int [] arrayA = {1, 2, 3}; int [] arrayB = arrayA; arrayB[1] = 4; System.out.println(arrayA[1]);

a. 1 b. 2 c. 3 d. 4

2. Consider the following Java program:

public class MyProgram { public static void main(String [] args) { System.out.println(args[1]); } }

What output is generated assuming the program above is executed from the command line as follows: java MyProgram Alpha Beta

a. java b. MyProgram c. Alpha d. Beta

3. When does an array become eligible for garbage collection?

_______________________________________________________________

_______________________________________________________________

Page 81: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 5: Arrays 5-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

What Is an Array? An array is a collection of items all having the same type. More importantly, the array is your first introduction to a non-primitive data type. The variable is declared as an array using the square brackets [], which you may remember seeing in a previous lesson. Like primitive variables, you can give an array an initial value or declare its value later. The variable that stores the array can be reused to store a new array later.

Initializing an Array The following is an example of an array:

int[] myIntArray = new int[10];

This array allocates or creates a data structure as illustrated in Figure 5-1.

0

0

0

1

0

2

0

3

0

4

0

5

0

6

0

7

0

8

0

9

myIntArray

Figure 5-1: Default values stored in myIntArray

In this example, myIntArray is a reference (the value is the memory location of the data) to the data structure. A reference is similar to a pointer in C/C++, but you can perform no pointer arithmetic on a reference. Instead, you can access individual members of the array by using the index (which always starts at 0). If you want to change the value of the fourth element in the array, you would use the following code:

myIntArray[3] = 42;

Note that when you create an array with the new keyword, the value of each element is automatically set to a default value, even though the array itself may be a local variable.

array

An ordered

collection of values,

referenced by an

integer index, all

having the same

type.

allocate

Java sets aside

enough space in

memory for a data

structure as soon as

it is adequately

defined.

reference

Java stores the

location of a non-

primitive type in the

variable; the actual

memory for the type

exists at the

pointed-to-memory

location.

index

A numeric

reference to a

specific element of

an array; the only

way to access

elements of an

array.

Page 82: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

5-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

An array can also be initialized by stating the value of each element. This form of initialization can be performed only when the array is declared; it will not work later in the program.

boolean[] myBooleanArray = {true, false, true};

It would be incorrect to state the following after you have created a boolean array:

myBooleanArray = {true, false, false};

Although Java has references, pointer arithmetic is strictly forbidden. The only way to access information from an

array is to reference the index.

Objects Java is an object-oriented language. A large part of this course is devoted to object theory. Imagine that you have written a small program that creates a window, and you named this program myWindow. What are some aspects of a graphical window that you should be able to manipulate? Perhaps you should be able to set the size (length and width) in pixels. Maybe you should be able to set the background color of the window. Or you should be able to hide the window and make it reappear. In an object-oriented language, these properties or methods would be programmed into your myWindow program. Object-oriented programs are unique because of how you invoke these properties or methods.

Notice that you see the name of the object (your program), a dot, then the name of the method to invoke. Each time you call a method, you must use parentheses, even if no arguments are being passed. Study the following example:

myWindow.setSize(300,200) // Set the size of the window. myWindow.setBackground(red) // Set the background color. myWindow.hide() // Hide the window. myWindow.show() // Make the window reappear.

In Java, arrays are objects. As objects, they offer functionality that you will want to be able to access.

object

A generic term for

non-primitive data

types; objects

represent data and

the operations on

data. Also, an

instance of a class,

with unique data

and operations.

Page 83: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 5: Arrays 5-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Using an Array Suppose you want to set all the elements of an array. You must traverse the array and operate on each individual element. If you know how big the array is, you can use a for statement. The array has a length property that is accessed as follows:

for (int index = 0; index < myIntArray.length; index++) { myIntArray[index] = index + 1; }

Notice that the myIntArray object has a property that you accessed using the object name (myIntArray), a dot, and then the property—in this case, the length (number of elements) of the array.

This program results in the array values illustrated in Figure 5-2.

1

0

2

1

3

2

4

3

5

4

6

5

7

6

8

7

9

8

10

9

myIntArray

Figure 5-2: Values stored in myIntArray following initialization

Similar operations can be used to print the values from the array.

Passing an Array to a Method Remember that Java uses pass by value, then notice the result when you pass an array to a method. You will write a method that increments each element of an array by one. When you tried this with primitive data types in the previous section, the original variable was unaffected by the change.

static void incrementArray (int[] tmpIntArray) { for (int ind = 0; ind < tmpIntArray.length; ind++) { tmpIntArray[ind]++; } }

length property

A characteristic of

an array; the

number of elements

it contains.

Page 84: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

5-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The call to this method is as follows:

int[] myIntArray = {1,3,5}; incrementArray(myIntArray); for (int i = 0; i < myIntArray.length; i++) { System.out.println(myIntArray[i]); }

The memory is allocated as illustrated in Figure 5-3.

1

0

3

1

5

2

MyIntArray

tmpIntArray

Figure 5-3: Two references to same array

In the previous lesson, you learned that Java uses pass by value in calling methods. When you pass an array into a method, the method obtains a copy of the array reference. Recall that a reference contains information about the array's location in memory. So although the method has a copy of the reference, the method can still make changes to the array that persist after the method returns. The value passed to the incrementArray method is a reference to the array, therefore changes to tmpIntArray will also affect myIntArray. This dependence gives Java the effect of non-primitive types being passed by reference, even though the mechanism is still pass by value. The same principle will be true with object data types.

Garbage Collection When you create an array with the new keyword, you are allocating as much space in memory as necessary to store the number of elements in the array. Notice the result when you are no longer using this space. Again, use your integer array declared previously:

int[] myIntArray = new int[10];

Now, reuse the variable myIntArray to create a three-element array:

myIntArray = new int[3];

pass by reference

A pointer to the

data is passed to a

method; changes

made to the data

by a method are

also made to the

original data.

Although Java

always uses pass by

value, pass by

reference is used for

non-primitive data

types because the

value for a non-

primitive type is a

reference.

Page 85: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 5: Arrays 5-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

This operation results in the memory illustrated in Figure 5-4.

0

0

0

1

0

2

myIntArray

0

0

0

1

0

2

0

3

0

4

0

5

0

6

0

7

0

8

0

9

Figure 5-4: Lost array reference

C and C++ programmers will probably see this as a memory leak. The old array now has nothing pointing to it. This data cannot be accessed. When this condition occurs, the JVM marks this object for garbage collection. Garbage collection is a service provided by the JVM to "deallocate," or retrieve, memory that is no longer in use. Once no references exist to a particular block of memory, it becomes eligible for garbage collection. Garbage collection may not occur immediately; the garbage collector waits for an appropriate time to deallocate memory. This process is automatic and transparent to the developer, and no mechanism exists to force garbage collection.

You can prevent the old array from becoming eligible for garbage collection by creating a reference or pointer to it before you create the three-element array:

int[] secondArray = myIntArray;

Command Line Parameters Recall that you saw the array notation earlier in this course. The main method must always have the following method signature:

public static void main (String[] args)

The args array (or any arbitrary name you choose to give it) will contain a collection of Strings. These Strings come from the command line as follows:

java Practice String1 String2

Page 86: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

5-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

As with other data types, you can access individual elements of this array with the bracket notation. For example, the first string, String1, would be contained in args[0], the second in args[1], and so forth. You can also test for the existence of command line parameters by testing the length property of the args array. You will learn more about manipulating Strings in the next lesson.

Command line parameters are always String type data.

You must to use special String methods to convert these

to chars, ints, doubles, and so forth. These special

methods will be discussed in later lessons.

Lab 5-1: Using arrays in Java

In this lab, you will create a 26-element array to store the characters of the English alphabet. Continue with your SectionOne class in your main method.

1. Declare an array that can store 26 characters.

2. Write a for loop that populates each element of the array with a character of the alphabet (lowercase).

Hint: Clever uses of casting will facilitate this.

3. Write a second for loop that prints the contents of the array created in Step 2.

4. (Optional) There are many ways to populate the array with the characters of the alphabet, some more elegant than others. Be sure to experiment with various possibilities. For example, ask your instructor about using double indexes in your for loop for a clever use of syntax.

Page 87: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 5: Arrays 5-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Arrays represent your first introduction to non-scalar data types. Arrays provide flexibility and convenience to the software developer. Create a list of at least five simple applications that could benefit from the use of arrays. Could these projects be accomplished using only scalar variables? How does the use of arrays decrease development time and limit programming errors?

Skills review

Arrays are a feature of most programming languages, and they provide an introduction to objects. In the next lesson, you will use the language features of Java to work with object-oriented programs.

Now that you have completed this lesson, you should be able to:

� Declare and initialize an array.

� Allocate space for a new array.

� Describe array indexing.

� Use the length property.

� Discuss why arrays are passed by reference.

� Describe Java's garbage collection mechanism.

� Retrieve command line parameters.

Page 88: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

5-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 5 Review

1. What is an array?

_______________________________________________________________

_______________________________________________________________

2. How are arrays similar to primitive variables?

_______________________________________________________________

_______________________________________________________________

3. What does "allocate" mean in reference to Java arrays?

_______________________________________________________________

_______________________________________________________________

4. What is a reference in relation to arrays?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

5. What is an index? At what value does the array index start?

_______________________________________________________________

_______________________________________________________________

6. What is an object, and how does it relate to an array in Java?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 89: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 5: Arrays 5-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

7. What is the length property?

_______________________________________________________________

_______________________________________________________________

8. What is pass by reference?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

9. What is garbage collection?

_______________________________________________________________

_______________________________________________________________

10. What is the args array?

_______________________________________________________________

11. How can you test for the existence of command line parameters?

_______________________________________________________________

Page 90: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

5-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 91: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

6Lesson 6:

Classes and Objects

Objectives By the end of this lesson, you will be able to:

� Identify the parts of an object.

� Create and use instance members.

� Distinguish between instance and class members.

� Define abstraction.

� Create object references.

Page 92: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

6-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. What output is generated by the following Java code?

class Employee { public String name; public double salary; public void display() { System.out.println("Employee: " + name + "\nSalary: " + salary + "\n\n"); } } public class MyClass { public static void main(String [] args) { Employee e1 = new Employee(); e1.name = "Maria Gomez"; e1.salary = 45000.00; Employee e2 = new Employee(); e2.name = "James Horner"; e2.salary = 35000.00; e1.name = "Joseph Gates"; e1 = e2; e1.display(); } }

a. Employee: Maria Gomez

Salary: 45000.0

b. Employee: James Horner Salary: 35000.0

c. Employee: Joseph Gates

Salary: 45000.0

d. Employee: Joseph Gates

Salary: 35000.0

Page 93: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 6: Classes and Objects 6-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

2. Consider the following Java code:

1. public class MyClass 2. { 3. public static void main(String [] args) 4. { 5. MyClass o1 = new MyClass(); 6. MyClass o2 = new MyClass(); 7. 8. o2 = o1; 9. o1 = o2; 10. o2 = null; 11. o1 = null; 12. } 13. }

When does the object instantiated at line 5 become eligible for garbage collection?

a. After line 8 b. After line 9 c. After line 10 d. After line 11

3. What is meant by the term "instantiation?"

_______________________________________________________________

_______________________________________________________________

Page 94: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

6-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Object-Oriented Programming In object-oriented programming, all data and methods are contained within classes. Classes are used to create objects, and objects interact with each other using messages. Each object contains attributes (variables) and behaviors (methods). In the next few lessons, you will study some of the principles of object-oriented programming, such as inheritance, abstraction, encapsulation and polymorphism, as well as how Java implements these principles.

Java code will always be contained in either a class or an interface. Although you have already used classes, we will now discuss them in more depth.

Before the advent of object-oriented programming languages, programmers used structured programming languages such as C and COBOL. Software developers with experience in these languages think of data and the code that operates on data as distinct entities.

In a C program, all the data used to define an employee, for example, might be stored in a struct that combines multiple simpler data types such as a character array (to hold the employee's name) and an integer value (to hold his or her annual salary) into a single data type, employee.

Object-oriented languages such as Java take this idea one step further by encapsulating data and code. In this way, a class stores both the data that defines an employee (such as an integer value to hold her annual salary) and methods that operate on this data (such as a method that gives the employee a 5-percent bonus).

What Is an Object? If a class is a blueprint, then an object is the realization of this blueprint. An employee object represents a particular employee, such as Rachael Ventura in Accounting who makes U.S. $52,000 per year. In object-oriented terminology, you instantiate the Employee class to create an employee object. In other words, the employee object is an instance of the Employee class. When a class is instantiated, memory is allocated to hold the data that will define the object, and these values are initialized.

To instantiate an object with Java, use the new keyword. For example, given that you have created a class called Employee, you can instantiate it as follows:

Employee rachaelVentura = new Employee();

This code is more complex than it appears. For now, it is important to understand that you must instantiate a class using the new keyword to create a functional object from the class. Once you have an instance of the class, you can work with its instance members.

instantiation

The use of a class

definition to create

an object.

Page 95: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 6: Classes and Objects 6-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Instance and Class Members The variables and methods that compose a class are its members. Members can be divided into two groups: class members and instance members.

A class member always has the modifier static in front of its name. For example:

static int age = 30; // a class variable.

Following is the same variable defined as an instance variable:

int age = 30; // an instance variable.

The following sections describe the difference between class members and instance members.

Instance members

Although you already worked with class members in an earlier lesson, we will discuss instance members first because they are more commonly used. Using class members is the exception in Java; using instance members is more the rule.

Consider the Employee class discussed earlier. An Employee has several characteristics that you can represent as variables, such as name, department, and salary. You can create a method that will print all the information about each Employee. This method consists of four println statements that print the instance variables. Your Employee class is as follows:

class Employee { // Instance Variables String name; // employee's name String department; // employee's department double salary; // salary in dollars // Instance Method void printAll() { System.out.println("Name: " + name); System.out.println("Department: " + department); System.out.println("Salary: " + salary); } }

class member

A variable or

method that exists

only once for the

class regardless of

how many objects

are created;

designated by the keyword static.

instance member

A variable or

method unique for

each object

(instance of the

class).

Page 96: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

6-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

You can create another class that contains your main method, and you can create objects (instances of Employee class). Create two variables: sam and rachael. Each of these variables will be an object of type Employee. After creating the Employee type variables, create an Employee object with the new keyword. Like primitive variables, the value can be assigned either when the variable is declared or later in the code.

class Main { public static void main(String[] args) { Employee sam = new Employee(); Employee rachael; // You may instaniate rachael = new Employee(); // a class on two // lines. } }

This code makes an essential point in distinguishing instances from classes. In this code, you instantiated the Employee class twice to obtain rachael and sam objects. Although rachael and sam are both instances of Employee, each has its own copy in memory. Therefore, the department instance variable in rachael is completely independent of the department instance variable in sam. Later, you will see that this independence does not exist with class members.

Accessing instance members

You can assign or reference the instance members by using dot notation (i.e., the object name, followed by a dot, followed by the member name). This example adds names and departments for sam and rachael, then prints the results. This code prints the instance variables from the main method first, then uses the printAll method.

class Main { public static void main(String[] args) { Employee sam = new Employee(); Employee rachael; rachael = new Employee(); sam.name = "Sam"; sam.department = "Human Resources"; rachael.name = "Rachael"; rachael.department = "Accounting"; // Print out sam's instance variables first. System.out.println(sam.name + " works in the " + sam.department + " department.\n"); // Now print out rachael's information using // printAll()

type

Identifies the kind of

information that a

variable can store.

new

A keyword that

signals the JVM to

allocate space for

an object.

dot notation

In Java, a reference

used to access a

member of an

object.

Page 97: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 6: Classes and Objects 6-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

rachael.printAll(); } }

The following output would result:

Sam works in the Human Resources department. Name: Rachael Department: Accounting Salary: 0.0

Notice the values for the uninitialized instance variables in rachael. All instance variables initialize to 0 or 0.0 for numeric types, false for Boolean types, '\u0000' for char types, and null for all non-primitive types. Each object (rachael and sam) has its own set of values for the instance variables. The object reference determines which instance variables are referenced.

When we discuss class members, you will see more similarities than differences. The greatest differences between class and instance members will be apparent when you run an example.

Class members

Class members function quite differently from instance members. First, some syntactical concerns must be noted.

• Class members (variables and methods) are prefaced with the keyword static.

• Class methods can access only class members, but instance methods can access either class or instance variables. Therefore, if you are in a static method, you can only have access to other static methods or variables.

If you want to access a class member from another class, use either the class name or the object name. Class members maintain only one copy in memory. Therefore, even though you may have instantiated many instances of a class, each member that is declared as static will be shared across all instances of that class. This concept is similar to that of global variables, but the word "global" is not acceptable in object-oriented terminology.

Page 98: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

6-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Accessing class members

An excellent example for working with class members is the Math class in the Java 2 API. The Math class is a collection of utility methods such as the sin method, which returns the sine of an angle. Because the sin method does not need to access any instance member variables in the Math class to operate, sin is defined as a static method, or a class member method. In this way, the Math class does not have to be instantiated to make use of the Math.sin method:

double mySin = Math.sin(3.14); // By accessing the // Math class // directly.

You do not have to instantiate the Math class to use its

member methods. You can reference it directly using the

name of the class.

You can use class variables to count the number of times a class was instantiated. For example, if you want to add an employeeNumber to the instances of Employee, create a class variable as follows:

class Employee { // class variable static int numberOfEmployees = 0; // instance variables int employeeNumber; String name; String department; double salary; void printAll() { System.out.println("ID: " + employeeNumber); System.out.println("Name: " + name); System.out.println("Department: " + department); System.out.println("Salary: " + salary); } } class Main { public static void main(String[] args) { Employee di = new Employee(); di.employeeNumber = ++Employee.numberOfEmployees; Employee ken = new Employee(); ken.employeeNumber = ++Employee.numberOfEmployees;

Page 99: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 6: Classes and Objects 6-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

System.out.println(di.employeeNumber); System.out.println(Employee.numberOfEmployees); } }

Study the preceding code carefully. The class Employee maintains a class-wide copy of numberOfEmployees.

Abstraction Abstraction is an important concept to understand when learning Java. Abstraction is a way of looking at an object in terms of its functionality and not its implementation details.

Abstraction is a process in which a software developer views a class as a black box, focusing on its inputs and outputs, rather than on the details of its implementation. For example, suppose you are designing an application that allows users to generate a graph depicting sales growth. You might develop a graph class that is responsible for taking in raw data and generating a graphic image to be displayed in a window.

Using abstraction, you can imagine this class as having several inputs, including the number of points to plot, the data series, and the size of the resulting graphic image on the screen. You can also expect a certain result: a graphic image of a specified size. Abstraction allows you to ignore the implementation details during the design process.

Abstraction provides several advantages. During the design process, abstraction allows software developers to focus on the design of complete applications and systems without pausing to consider implementation details. Also, by focusing on the interface to a class, abstraction allows classes to be more easily reused, modified, or replaced. If at some later time you decide to replace your graph class with a new class that generates a three-dimensional graph, the process will be simpler because the implementation details were not finalized during the design process.

abstraction

The consideration of

an object in terms of

its functionality and

not its

implementation

details.

Page 100: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

6-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Object References The preceding lesson introduced you to references. Similar to a pointer in C and other languages, a reference is a variable that holds information about the location in memory of other information. When you work with objects, you are actually working with references.

Suppose you create two Employee variables: rachael and tmpEmp. When you instantiate a new Employee object using the new keyword, the object reference rachael points to the newly created Employee object. Because tmpEmp and rachael are references, if you assign rachael to tmpEmp then both references will point to the same object. Thus any changes in one object will be reflected in the other. The result is shown in Figure 6-1.

Employee rachael = new Employee("Rachael", "Accounting", 52000); Employee tmpEmp = rachael;

rachael

tmpEmp

name: "Rachael" department: "Accounting" salary: 52000

Figure 6-1: tmpEmp variable

If you have experience developing in other programming languages, you are probably familiar with the problem of memory leaks. Memory leaks occur when data that is no longer needed continues to be held in memory, even after all pointers or references to the data are gone. Java provides a service called garbage collection that helps to eliminate memory leaks. Instead of manually freeing memory (as in languages such as C), the Java Virtual Machine automatically frees the memory used by objects to which no reference points. Garbage collection is a low-priority process. The programmer need not manually invoke the garbage collector.

The programmer should make no assumptions about

when the garbage collector will run. It is guaranteed to

run only sometime after the object no longer has a valid

reference to it.

Page 101: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 6: Classes and Objects 6-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lab 6-1: Creating your own classes in Java

In this lab, you will create your own classes, instantiate them, and practice accessing their members using dot notation.

1. Create a new text file and write an Employee class with the following (minimal) instance variables. (You may add more.)

String name; String department; double salary;

2. Add a printAll method that will print these instance variables to the command line.

3. Create the starting class and call it Exercise6_1. Add a main method. Then instantiate two instances of the Employee class, set their variables, and print them using the printAll method that you implemented.

4. Save the file as Exercise6_1.java.

5. Compile and execute Exercise6_1.java.

6. (Optional) Create a two-element array that can store elements of type Employee. Populate the array with the two Employee instances created in Step 3, then attempt to invoke the printAll method of each instance.

7. (Optional) Use a for loop to loop through the elements of the array created in Step 6, then invoke the printAll method.

Remember that each member (class and instance

members, variables and methods) begins with a

lowercase letter. You can distinguish between variables

and methods by the presence (or absence) of

parentheses. The exception to this guideline is final

variables (constants), which are typically all capitalized.

Page 102: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

6-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

In Java applications, objects are used to encapsulate data and functionality. The simplest objects are known as entity objects. Entity objects model things that exist in the real world such as an employee, an inventory item, or an airline flight schedule. Consider a system that manages inventory and handles customer checkout at a grocery store. Create a list of at least 10 classes that might be defined in such a system. What attributes might each of the classes define?

Skills review

In this lesson, you learned about the roles of classes and objects in object-oriented programming. You learned the differences between instance and class members, and how to access them. You also learned the value of abstraction when designing systems with Java. With this introduction to classes and objects, you have begun to fully understand object-oriented programming. You will use classes and objects in more complex ways in later lessons.

Now that you have completed this lesson, you should be able to:

� Identify the parts of an object.

� Create and use instance members.

� Distinguish between instance and class members.

� Define abstraction.

� Create object references.

Page 103: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 6: Classes and Objects 6-13

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 6 Review

1. What is a class?

_______________________________________________________________

_______________________________________________________________

2. What is an object?

_______________________________________________________________

_______________________________________________________________

3. Identify the parts of an object.

_______________________________________________________________

4. What is instantiation?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

5. What are class members? What are instance members? Which are more commonly used in Java?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

6. What is dot notation?

_______________________________________________________________

Page 104: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

6-14 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

7. What is abstraction?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

8. What is a reference, and what is its role in working with objects?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 105: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

7Lesson 7:

Inheritance

Objectives By the end of this lesson, you will be able to:

� Create a new class using inheritance.

� Create an overridden method.

Page 106: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

7-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. What output is generated by the following Java code?

class A { public void myMethod() { System.out.print("A"); } } class B extends A { public void myMethod() { System.out.print ("B"); } } public class C extends B { public void myMethod() { System.out.print ("C"); } public static void main(String [] args) { A a = new C(); a.myMethod(); } }

a. A b. B c. C d. CBA

Page 107: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 7: Inheritance 7-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

2. What output is generated by the following Java code?

1. class A 2. { 3. public void myMethod() 4. { System.out.print("A"); } 5. } 6. 7. class B extends A 8. { 9. public void myMethod() 10. { System.out.print("B"); } 11. } 12. 13. public class C extends B 14. { 15. public void myMethod() 16. { super.myMethod(); } 17. 18. public static void main(String [] args) 19. { 20. A a = new C(); 21. a.myMethod(); 22. } 23. }

a. A b. B c. BA d. No output is generated due to an error at line 21.

3. What is a subclass?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 108: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

7-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

What Is Inheritance? Inheritance allows you to reuse code that has already been written, and modify that code to meet your specific needs. Consider a class named Animal that models the attributes and behaviors common to all animals. Using inheritance, you could create a second class named Mammal that inherits all of the attributes and behaviors of Animal, and expands on them to model those properties unique to mammals. You could continue to use inheritance to create additional classes, such as Cat and Dog, which inherit from the Mammal class and represent unique types of mammals.

Using inheritance

Consider a class named Programmer. You might describe a Programmer as an Employee who has a specific department and salary. You can also define a method called calculateBonus, which uses salary to determine an annual bonus amount. One way to define this class is as follows:

class Programmer { // class variable static int numberOfEmployees = 0; // instance variables from Employee int employeeNum; String name; String department; double salary; // instance variables specific to Programmer String language; // language he or she programs // methods of Employee such as calculateBonus // ... }

inheritance

In Java, creation of

new classes by

defining only the

differences from

existing classes.

Page 109: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 7: Inheritance 7-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The problem with this class is its redundancy. You have already done much of the work. Inheritance allows you to reuse the Employee class previously defined. You can create a new class that extends Employee; that is, it inherits all the methods and variables from Employee. The Programmer class is a subclass of Employee, and Employee is a superclass of Programmer. Java supports inheritance from only one class, not multiple inheritance (we will discuss solutions to this limitation later in the course). The new Employee class describes how the subclass is different from the superclass:

class Programmer extends Employee { // instance variables specific to // Programmer String language; // language he or she programs }

Following is some of the code that goes inside the main method:

Programmer bill = new Programmer(); bill.name = "Bill"; bill.employeeNumber = ++Employee.numberOfEmployees; bill.department = "Development"; bill.salary = 55000.00; bill.language = "Java"; bill.printAll();

The output of this code is:

Name: Bill ID: 1 Department: Development Salary: 55000.0

Overriding Methods The printAll method that was inherited from Employee does not know about the Programmer class variable of language because that variable does not exist in Employee. This poses a problem. Although you have inherited the printAll method of Employee, it does not perform all the functions you require (it does not print the additional instance variables). You need a solution.

The best solution would be to use the printAll method inherited from Employee, and then modify it just enough to print the additional instance variables. You can do this, but you must introduce a new keyword: super.

extends

The Java keyword

that designates the

class from which to

derive.

subclass

A class that inherits

from a superclass.

superclass

A class from which

one or more classes

are derived.

super

The keyword used

to refer to the

superclass object;

allows you to call a

method defined in

the superclass.

Page 110: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

7-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The super keyword allows you to access a member of the superclass from the subclass. Therefore, instead of completely rewriting the printAll method in the Programmer class (the subclass of Employee), you can access the printAll method of Employee first, then add some more functionality. The following code demonstrates this technique:

void printAll() { super.printAll(); // call the parent object's method System.out.println("Language: " + language); }

This method, which has the same method signature (name and parameter types), overrides the method of Employee. If you call the printAll method on an object of type Programmer, you get the printAll method from Programmer. If you call the printAll method on an object of type Employee, you get the printAll method from Employee.

Notice that Employee does not extend any class. All classes are ultimately derived from the Object class in the package java.lang. If a class does not explicitly extend another class then the Java compiler assumes it extends the Object class.

Lab 7-1: Implementing inheritance in Java

In this lab, you will see the power that inheritance provides programmers by reducing code redundancy as you practice subclassing superclasses.

1. Create a new text file and write code to implement the hierarchy of classes shown in Figure 7-1.

Programmer Physician Administrator

Employee

Figure 7-1: Hierarchy of classes

overridden method

A method in a

derived class with

the same method

signature; replaces

the superclass

method for the

subclass.

Page 111: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 7: Inheritance 7-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

2. The foundations of the Employee and Programmer classes have already been given. The two additional classes (Physician and Administrator) must meet the following requirements:

• A Physician is an Employee with a DEA# for writing prescriptions.

• An Administrator is an Employee with a specific title.

3. Override the printAll method for each of the subclasses.

4. Create a public class named Lab7_1 and write a main method within it that instantiates each of the classes in the class hierarchy. Make calls to each class's printAll method.

5. Save the file as Lab7_1.java.

6. Compile and execute Lab7_1.java.

7. (Optional) Extend either Programmer, Physician or Administrator one level further. For example, a Pediatrician is a special type of Physician.

Overridden Methods and Variables The following Java code demonstrates the way in which Java treats overridden methods and variables:

class Super { int myInt = 42; String test() { return "Super"; } } class Sub extends Super { int myInt = 11; String test() { return "Sub"; } }

Page 112: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

7-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The following two objects are familiar:

Super mySuper = new Super(); Sub mySub = new Sub(); System.out.println(mySuper.test()); // prints "Super" System.out.println(mySuper.myInt); // prints 42 System.out.println(mySub.test()); // prints "Sub" System.out.println(mySub.myInt); // prints 11

Now, apply the skills you have learned to the following object:

Super superSub = new Sub();

Because Sub extends Super, this declaration is valid. The Sub object created by new Sub() must also be a Super object. The behavior of the overridden variables and methods is unusual. The variable depends on the type of the object reference superSub, whereas the method depends on the type of the object that was created. For example:

System.out.println(superSub.test()); // Prints "Sub" // from new Sub(). System.out.println(superSub.myInt); // Prints 42 // from Super type.

The rules of casting say that you can always put an object into a more general type (that is, you can implicitly cast up the hierarchy). For this reason, you can place the object created by new Sub() into a Super type object reference. Consider a class named Programmer derived from a superclass named Employee. A programmer is a type of employee, and so a reference of type Programmer can be stored in a reference of type Employee without explicit casting:

Employee e = new Programmer(); // Legal because // Employee is // derived from Programmer. Programmer p = (Programmer) e;

Because e actually contains an Employee object, you can cast e to become a Programmer. The following code would cause a ClassCastException designating an error:

Employee e = new Employee(); Programmer p = (Programmer) e; // ClassCastException

Page 113: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 7: Inheritance 7-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Inheritance is a critical component of all object-oriented languages. Create a list of at least five programming scenarios that could benefit from the use of inheritance. How does the use of inheritance facilitate code reuse? How does it reduce development time and programming errors?

Skills review

In this lesson, you learned how inheritance allows you to reuse code to meet specific needs. You also learned how to override methods and use the overridden method in its own implementation. Inheritance allows you to intelligently reuse classes that have already been written, thereby increasing the speed of development in an object-oriented language. While many design issues must be considered, you can create very sophisticated programs with few lines of code because much of the work will be done already.

Now that you have completed this lesson, you should be able to:

� Create a new class using inheritance.

� Create an overridden method.

Page 114: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

7-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 7 Review

1. What is inheritance in Java?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

2. What is the benefit of using inheritance?

_______________________________________________________________

3. What is a superclass?

_______________________________________________________________

4. What is a subclass?

_______________________________________________________________

5. What is multiple inheritance? Does Java support it?

_______________________________________________________________

_______________________________________________________________

6. What is an overridden method?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 115: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 7: Inheritance 7-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

7. What is a method signature?

_______________________________________________________________

8. If a class does not explicitly extend another class, then what class does the Java compiler assume it extends?

_______________________________________________________________

Page 116: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

7-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 117: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

8Lesson 8:

Constructors

Objectives By the end of this lesson, you will be able to:

� Use the default constructor.

� Create a constructor to initialize instance variables.

� Call other constructors from the same class (this).

� Call constructors from the parent class (super).

� Create a no-arguments constructor.

� Discuss String characteristics and define the common methods of the String class.

Page 118: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

8-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. What output is generated by the following Java code?

class A { public A(int i) { System.out.print("A"); } } public class B extends A { public B(int i) { System.out.print("B"); } public static void main(String [] args) { new B(0); } }

a. A b. B c. AB d. No output is generated due to a compile-time error.

2. What output is generated by the following Java code?

class A { public A() { System.out.print("A"); } } public class B extends A { public B() { System.out.print("B"); } public static void main(String [] args) { new B(); } }

a. A b. B c. AB d. No output is generated due to a compile-time error.

Page 119: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 8: Constructors 8-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

3. What is a callback?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 120: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

8-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

What Is a Constructor? A constructor is a special method used to instantiate an instance of a class. You have already used constructors with statements such as the following:

Employee sam = new Employee(); Programmer lanny = new Programmer();

Notice that the syntax after the new keyword closely resembles a method. This syntax is a constructor: a method that has the same name as the class in which it exists. This constructor method does not have a return type, so it is generally said that it returns nothing. However, you can think of the combination of the new keyword with a constructor as returning a reference to an object.

What can constructors do?

Constructors can define an initial state for the object you are instantiating. You accomplish this by simply recognizing that a constructor is a method. A method has parameters, so it passes an argument list to the constructor. Following is some introductory code:

Programmer lanny = new Programmer("Lanny", "Development", 120000);

In this example, the constructor method for the Programmer class could be written to accept arguments that will initialize the member variables of the lanny object.

Another use for constructors is interobject communication. This function is extremely useful. One of the primary goals of object-oriented programming is to establish an effective and architecturally correct means of interobject communication. Constructors accommodate this need with a technique referred to as callback.

If Object B needs to communicate with Object A, then B can issue a callback to A. Constructors can perform this function. We will discuss this concept in depth.

Using Constructors Once you have created a class, you instantiate it to create an object. An object of type Programmer can be created using the following statement:

Programmer lanny = new Programmer();

constructor

A special method

having the same

name as its class;

used to instantiate a

class.

callback

When an object

refers back to a

class to which it has

gained reference.

Page 121: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 8: Constructors 8-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The statement new Programmer() calls the default constructor (a constructor with no parameters). The constructor returns an object of type Programmer. The format for a constructor is as follows:

className(parameter_list) { // executable code }

Constructors look and behave like methods, with two differences: A constructor has the same name as the class, and it does not have a return type. A constructor is always called with the keyword new. When no constructor is defined (as it is currently in Employee and its subclasses), then the default constructor is as follows:

Programmer() { }

You can benefit from the fact that a constructor is a method by defining a constructor for Programmer that allows you to enter the name, department and salary as parameters. Following is the constructor:

Programmer(String tmpName) { name = tmpName; department = "Development"; salary = 0.0; }

You can use another feature of methods: overloading. Overloading is a process in which two or more member methods are given the same name. In the case of the Programmer constructor, you could define two constructor methods: one that accepts a single parameter (such as name()) and another that accepts additional parameters (such as department() and salary()). The Java compiler distinguishes between calls to either method by examining the parameters passed. For example:

Programmer(String tmpName); Programmer(String tmpName, String tmpDepartment, double tmpSalary);

In the Java 2 API, overloaded constructors are used frequently. This concept will become apparent when you study the AWT.

default constructor

A constructor

without parameters;

Java assumes a

default constructor

until you define your

own.

Page 122: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

8-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The Keyword this The keyword this has several uses in Java. The this keyword refers to the current object. We will discuss two specific uses of this: The first refers to a constructor, specifically one in the current class. The second function helps you avoid namespace conflicts between a method's parameter list and its variables.

this() as a constructor

Because you want to add different combinations of parameters to the set of constructors, you discover that much of the code is similar. One of the guiding principles of object-oriented programming is to avoid doing more work than necessary; thus, Java provides a mechanism for one constructor to call another constructor within the same class: You can rewrite the second constructor to use the first constructor. The keyword this allows you to call another constructor with the same name but a different signature. The following is the rewrite of the second constructor:

Programmer(String tmpName) { this(tmpName, 68.0, 170, 35); }

If the constructor this() is used, it must be the first statement in the constructor. Another way you might use the this() constructor is to execute the same code for all constructors. In an earlier example, you added a statement after you created an Employee to set the employeeNumber. If you want to apply that operation in the constructor, the constructor might be as follows:

Employee() { employeeNumber = ++numberOfEmployees; }

To ensure that this operation is always called, add the statement this(); at the beginning of the other constructors. Now every Employee will have an employeeNumber, regardless of which constructor is called.

Avoiding namespace conflicts

Consider the following constructor, defined previously:

Programmer(String tmpName) { name = tmpName; department = "Development"; salary = 0.0; }

this

A keyword that

refers to the current

object.

Page 123: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 8: Constructors 8-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Notice that this constructor uses the variable name tmpName in the parameter list, and later assigns it to the instance variable name. Two different names are used so that the local variable tmpName will not conflict with the instance variable name. While this naming scheme makes a class very clear, it is not the common practice.

A second approach is to use the keyword this. Recall that this refers to the current object. Therefore, the following modification is perfectly acceptable:

Programmer(String name) { this.name = name; department = "Development"; salary = 0.0; }

By using the keyword this, you can use the same variable name without conflict. For clarity in this course, you will usually use the first method (appending tmp) to define parameters. However, as a Java programmer you are likely to encounter a great deal of code that uses the second method (this).

The super keyword

If you add a constructor to the Employee class, what happens when you try to create a Programmer? The constructors for Programmer will call Employee(), and you will see an error message informing you that Employee() does not exist. Once you add a constructor, the default constructor is no longer present. You can replace this functionality by defining a no-arguments constructor:

Employee() { }

You can also call one of the other constructors of the superclass with the keyword super. As with the this() constructor, super() must be the first statement of the constructor if used. For example, if you want to call the Employee(String) constructor from the Programmer(String) constructor, use the following:

Programmer(String tmpName) { super(tmpName); }

If there is some behavior that all constructors must

perform (such as the creation of the employeeNumber), it

should be defined in the no-arguments constructor. Then

all the other constructors in the class can call this().

Constructors are not inherited. The fact that an Employee constructor takes a String does not guarantee that a constructor exists for Programmer that accepts a String.

no-arguments

constructor

A constructor for a

class having no

parameters; the

default constructor

is an example.

Page 124: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

8-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Constructor Process When a constructor is called in a class, a call is immediately made to the constructor of its superclass. This process repeats itself all the way up the class hierarchy to the class Object. This concept can be readily demonstrated as follows:

class Parent { Parent() { System.out.println("Creating the Parent"); } } class Child extends Parent { Child() { System.out.println("Creating the Child"); } } class GrandChild extends Child { GrandChild() { System.out.println("Creating the GrandChild"); } } class Main { public static void main(String[] args) { new GrandChild(); } }

Is the following output surprising?

Creating the Parent Creating the Child Creating the GrandChild

Remember that the compiler will only create the default

no-arguments constructor if no other constructors are

defined. If you define a constructor, be sure to include a

no-arguments constructor even if it contains no code, so

that your class can be subclassed.

Page 125: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 8: Constructors 8-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Constructors and Callbacks Interobject communication is one of the most important concepts in object-oriented programming. Constructors are a major facilitator in establishing interobject communication.

Suppose you want to create a Timer class whose purpose is to invoke a method in the class that instantiated it (after a certain interval of time). How can this Timer object get a reference back to the object that instantiated it? Constructors are used to accomplish this task.

Students often have difficulty adjusting to the idea of using callbacks as a regular part of their programming technique. Remember the reasons for using callbacks. Every object in Java should specialize in whatever it does best. Callbacks allow Object A to assign an appropriate task to Object B. Object B can then notify Object A (asynchronously) when the task is completed. This activity supports separation of responsibility between objects and efficient use of resources.

You will create a Client object that creates and uses a Timer object. The Timer object will invoke a method of the Client object using a callback. Study the following example carefully:

class Timer { int interval; Client client; Timer(Client client, int tmpInterval) { this.client = client; // client is a reference to the // Client object instantiated by // main method interval = tmpInterval; } void run() { while(true) { for(int i = 0; i<interval;i++); client.timerFired(); // This is the callback. } } } public class Client { public static void main(String[] args) { new Client();

Page 126: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

8-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

} Client() { Timer t = new Timer(this, 100000000); t.run(); } public void timerFired() { System.out.println("Timer method fired."); } }

This example is used commonly in object-oriented programming. One goal of this course is to make this approach to interobject communication the standard. In the next few lessons, you will establish a way to implement the preceding code in a more elegant, reusable fashion with the use of interfaces.

String and StringBuffer You have been using String throughout these lessons. A String is not an array of characters and it does not need special terminators as in C and C++. In Java, strings are objects. By using the methods of the String class, programmers are provided with comprehensive string functionality from the outset.

String constructors

Strings can be created in two ways. First, strings are objects, thus there exists a predictable constructor:

String s = new String("Hello");

This constructor declares a String object initialized to "Hello". However, so does the following:

String s = "Hello";

In this example, variable s is initialized using a string literal without instantiating a new String object.

Page 127: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 8: Constructors 8-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

String characteristics

Strings possess some interesting characteristics that merit explanation.

Strings are immutable

A String object is immutable because once a String has been instantiated, it cannot change. For example:

String s1 = "Hello"; s1 = "Goodbye";

It would seem that this code shows one String being assigned two values, but this assumption is not accurate. Actually, two different String objects were created. However, the first String ("Hello") is no longer being referenced and is available for garbage collection.

If you wonder why strings are immutable, the answer is speed. If strings were dynamic, string processes would be slower.

Concatenating strings

Concatenating strings means adding or combining strings.

If strings are immutable, how can you explain the following code?

String s = "Hello, " + "world!";

Remember that "Hello, " and "world" are immutable strings themselves, so there should be no string operation that would add the two strings together. In fact, there is not. Java uses another class to perform the concatenation: the StringBuffer class, which we will discuss shortly.

Comparing strings: equals() vs. ==

Because strings are also objects, you need two ways to compare strings.

By using the equals method of String, you can compare to see whether two strings have the same characters:

String s1 = "keyboard"; String s2 = new String(s1); if(s1.equals(s2)) System.out.println("true"); else System.out.println("false");

This code would print "true" because the two strings contain the same characters.

immutable

Unable to be

changed; a

characteristic of

Strings.

concatenation

The act of adding Strings together.

Page 128: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

8-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

If you use the == operator, you are not asking whether the two strings have the same characters, but whether they refer to the same object:

String s1 = "keyboard"; String s2 = new String(s1); if(s1 == s2) System.out.println("true"); else System.out.println("false");

This code would print "false". By creating a completely new String object with the new operator, s1 and s2 are completely different objects (albeit with the same characters).

Methods of String

The advantage of strings being objects is the availability of many methods. Table 8-1 lists the common methods of the String class.

Table 8-1: Common methods of String

Method Description

length Returns an int of the number of characters

toUpperCase Returns a new String with all uppercase letters

toLowerCase Returns a new String with all lowercase letters

equals Returns true if the Strings have the same length and same characters (case-sensitive)

equalsIgnoreCase Same as equals but not case-sensitive

charAt Returns the character at the index

indexOf

lastIndexOf

Returns the index of the first or last occurrence of a character or substring

substring Returns a substring from a String

trim Returns a new String with leading and trailing white space removed

Page 129: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 8: Constructors 8-13

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Using these methods is easy. For example:

String s = "Mother"; char c = s.charAt(2);

The character c now has the character value t.

However, you must remember that strings are immutable. Consider how you would change a string from lowercase to uppercase:

String s = "hello"; s.toUpperCase(); // This won't work – Strings are // immutable. s = s.toUpperCase(); // You must do this, i.e., // create a new String.

The preceding code could also be written as follows:

String s = "hello".toUpperCase();

Remember that a literal string in double quotation marks is considered a string object in Java.

StringBuffer

The StringBuffer class provides the functionality not included in the String class because StringBuffer is not immutable. Therefore, you can perform such operations as inserting additional characters into a StringBuffer or modifying specific characters within a StringBuffer.

Declaring a StringBuffer is just like declaring a String, except you cannot automatically call a constructor with the quotation marks:

StringBuffer sb = new StringBuffer("Hello people"); // OK StringBuffer sb = "Hello people"; // Won't work.

Because a StringBuffer is not immutable, you can take advantage of its many methods:

StringBuffer sb = new StringBuffer("Hello people"); sb.insert(6, "nice ");

The preceding code would set the variable sb to the following:

"Hello nice people"

StringBuffer

A peer class to the

String class; it is

not immutable.

Page 130: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

8-14 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

StringBuffers are slower than strings. It is therefore common to convert a StringBuffer into a String object using the toString() method, or by declaring a new String object once you are finished with your StringBuffer manipulations:

StringBuffer sb = new StringBuffer("Hello people"); sb.insert(6, "nice "); String s1 = new String(sb); // Here's one way. String s2 = sb.toString(); // Here's another way.

Lab 8-1: Building constructors in Java

In this lab, you will demonstrate several uses of a constructor, such as setting the initial state of an object. You will also use the this() constructor to make your code less redundant and more readable.

1. Add a constructor to the Programmer class that allows you to specify the following default information: department, salary and language.

2. Add another constructor to the Programmer class such that if department and salary are supplied but language is not, then a language is automatically supplied. The constructor defined in Step 1 will be called.

Hint: Use the this() constructor.

3. (Optional) Add appropriate constructors for the Physician and Administrator classes.

Constructors should be grouped together in the class and

identified by a comment statement, as you would with

instance variables, instance methods, class methods, and

class variables.

Page 131: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 8: Constructors 8-15

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Callback objects are used to provide a pathway for inter-object communications. A typical object-oriented system will contains hundred or thousands of objects that must communicate with one another. For example, an Invoice object would likely retain a reference to an associated Customer object. This reference allows the Invoice object to communicate with and extract information from a Customer object. In an earlier lesson, you identified objects that might compose a grocery store inventory system. Review this list and identify object relationships. Identify pairs of objects that might have to communicate with one another. In each object relationship, identify which of the objects should maintain a callback reference.

Skills review

In this lesson, you studied constructors and their functions, and you learned to use callbacks. You learned two uses for the keyword this. You also built constructors to supply default information for an instance of a class. You used the keyword super to call the parent class's constructor. The body of a constructor is an executable piece of a Java program, and will be called each time a class is instantiated to create an object. Although this lesson focused on default values and callbacks, you can actually perform any sort of function in a constructor, although it gets called only once for each object.

Now that you have completed this lesson, you should be able to:

� Use the default constructor.

� Create a constructor to initialize instance variables.

� Call other constructors from the same class (this).

� Call constructors from the parent class (super).

� Create a no-arguments constructor.

� Discuss String characteristics and define the common methods of the String class.

Page 132: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

8-16 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 8 Review

1. What is a constructor?

_______________________________________________________________

_______________________________________________________________

2. What does a constructor return?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

3. Name two uses for constructors.

_______________________________________________________________

_______________________________________________________________

4. What is a callback?

_______________________________________________________________

_______________________________________________________________

5. In what two ways does a constructor differ from a method?

_______________________________________________________________

_______________________________________________________________

6. What is a no-arguments constructor?

_______________________________________________________________

_______________________________________________________________

Page 133: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 8: Constructors 8-17

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

7. List three characteristics of Java strings.

_______________________________________________________________

_______________________________________________________________

8. List at least two common methods of the Java String class.

_______________________________________________________________

_______________________________________________________________

9. What is the StringBuffer class, and what is its purpose?

_______________________________________________________________

_______________________________________________________________

Page 134: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

8-18 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 135: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

9Lesson 9:

Interfaces and Abstract

Classes

Objectives By the end of this lesson, you will be able to:

� Define and use interfaces.

� Define polymorphism.

� Use abstract classes.

� Create an abstract method.

Page 136: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

9-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. What output is generated by the following Java code?

interface MyInterface { public void display() { System.out.println("MyInterface"); } } public class MyClass implements MyInterface { public void display() { System.out.println("MyClass"); } public static void main(String [] args) { MyClass mc = new MyClass(); mc.display(); } }

a. MyInterface b. MyClass c. MyInterface

MyClass d. No output is generated due to a compile-timer error.

Page 137: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 9: Interfaces and Abstract Classes 9-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

2. What output is generated by the following Java code?

abstract class MyAbstractClass { public void display() { System.out.println("MyAbstractClass"); } abstract public void anotherMethod(); } public class MyClass extends MyAbstractClass { public void display() { System.out.println("MyClass"); } public static void main(String [] args) { MyClass mc = new MyClass(); mc.display(); } }

a. MyAbstractClass b. MyClass c. No output is generated due to a run-time error. d. No output is generated due to a compile-time error.

3. What is the difference between an interface and an abstract class?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 138: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

9-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

What Is an Interface? An interface can provide a solution for objects that have multiple characteristics. In your fictional company example, consider the role of a contractor. A contractor is not an employee, but you must pay the contractor a salary. Where do you place the contractor? If you place him or her in the Employee class, some attributes and operations may be inherited that you do not want to apply to a contractor. The solution is interfaces.

Contents of an interface

An interface defines a set of abstract methods and final variables. An interface contains no implementation details. Instead, it defines the method signatures that will be implemented by a class. Classes that implement interfaces provide the implementation for these abstract methods. Consider the following example:

public interface Payable { abstract double calculateSalary(); final double NOTHING = 0.0; } abstract class Employee implements Payable { // Remainder of class definition // must either contain an abstract calculateSalary // method or a concrete calculateSalary method. } class Contractor implements Payable { // instance variables Boolean contractCompleted = false; double calculateSalary() { double salary; if (contractCompleted) { salary = 15000.00; } else { salary = NOTHING; } return salary; } }

interface

Abstract methods

and final variables

that can be used by

different classes.

Also defines a data

type.

Page 139: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 9: Interfaces and Abstract Classes 9-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

You can add another class called BillableService that implements Payable. This class would be completely external to the Employee hierarchy. Again, as in the preceding abstract class example, you can create an array of Payable and execute the calculateSalary method on each element. Java does not support multiple inheritance. Instead, interfaces are used to type a class without inserting it within multiple inheritance hierarchies.

Interface functions

Consider the earlier discussion about objects talking to objects.

Interfaces and coupling

As your object-oriented programming expertise grows, you will learn that designing by interfaces is generally a superior approach to designing by inheritance. Although inheritance is a powerful and useful feature of object-oriented programming, it has one major drawback: coupling.

Coupling refers to the level of interdependency between objects. In reference to inheritance, a subclass is tightly coupled with its superclass. If the design of a superclass changes, it will probably affect its subclasses, possibly in unpredictable and detrimental ways.

Interfaces can reduce coupling. The only responsibility an object has to its interface is to implement its methods.

Interfaces and object types

An object type is essentially a contract stating the functions that the object can perform.

The preceding statement confirms a reality that will be encountered repeatedly. Consider it in relation to the following code:

abstract class Employee implements Payable

According to this statement, the Employee object is an object of three different types:

• It is an object of type Object because all objects inherit from Object. Thus, the methods toString and notify are available to the Employee class.

• It is an object of type Employee inherently.

• It is an object of type Payable because it implements the Payable interface. Thus, the calculateSalary method is available.

coupling

The level of

interdependency

between objects.

Page 140: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

9-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The ability to make an object a type by simply adding an interface is an extremely powerful mechanism for establishing interobject communication. If Object A has implemented a certain interface, and Object B knows this, then Object B knows how to communicate with Object A (most likely through its methods).

The idea of interobject communication and object types is truly epitomized with the concept of polymorphism.

Polymorphism Polymorphism sounds more complex than it is. It is the ability to use one method name to invoke many different methods.

Polymorphism occurred when you created an array of type Employee, instantiated several objects of different types, and then invoked the printAll method—a method common to all these objects. Do not be confused by the fact that they all use the same method name.

Although each object has a printAll method, each individual object had to implement that method in a meaningful (and probably unique) way.

Note that polymorphism can also be performed by using an array of a particular type interface. For example, if the Employee class implements the Payable interface, then an array of Payable objects can be created to invoke the calculateSalary method of Payable.

The Clock/Timer system you have been developing is a strong candidate for polymorphism via interfaces if you make the following observations:

// The following is similar to your previous work: import java.util.*; public class DigitalClock { public static void main(String[] args) { new DigitalClock(); } DigitalClock() { Timer t = new Timer(this, 10000000); t.run(); } public void timerFired() { System.out.println(new Date().toString()); }

polymorphism

Using one method

name to invoke

many different

methods.

Page 141: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 9: Interfaces and Abstract Classes 9-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

} // You had a Timer class that could perform the callback: class Timer { DigitalClock dClock; int delay; Timer(DigitalClock dClock, int delay) { this.dClock = dClock; this.delay = delay; } public void run() { while(true) { for (int i = 0; i < interval; i++); dClock.timerFired(); } } }

The preceding code worked well. However, suppose you wanted to use your Timer class again. And this time, instead of using another instance of the DigitalClock class, you want to use a different class altogether. For example:

public class StockUpdateServer { public static void main(String[] args) { new StockUpdateServer(); } StockUpdateServer() { Timer t = new Timer(this, 10000000); t.run(); } public void timerFired() { // code with latest stock updates } }

Do you see the dilemma here? Currently, your Timer class is designed to receive objects of type DigitalClock. Yet with this StockUpdateServer class, you are asking it to also receive an object of type StockUpdateServer.

What options are available?

Page 142: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

9-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Following are two suggestions often posed by students. Both are incorrect, but they demonstrate good thinking processes.

• Solution 1: Overload the constructor to accept objects of both DigitalClock and StockUpdateServer.

• Response 1: This solution would work, but suppose you had 100 different type objects that would like to use this Timer object. It would not be reasonable (or flexible) to overload a constructor 100 times.

• Solution 2: Because DigitalClock and StockUpdateServer both extend from Object, redesign the constructor of the Timer class to accept objects of type Object.

• Response 2: Although both objects share the Object type, the Timer class is trying to invoke a timerFired method as a callback. Objects of type Object do not have a timerFired method.

These scenarios motivate the need for constructors, because if the DigitalClock class and StockUpdateServer class have nothing appropriate in common, you can supply an interface as a common element.

The correct solution follows:

interface TimerInterface { public abstract void timerFired(); } public class StockUpdateServer implements TimerInterface { public static void main(String[] args) { new StockUpdateServer(); } StockUpdateServer() { Timer t = new Timer(this, 10000000); t.run(); } public void timerFired() //associated with TimerInterface { // code with latest stock updates } } class Timer { TimerInterface tiObj; int delay; Timer(TimerInterface tiObj, int delay) {

Page 143: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 9: Interfaces and Abstract Classes 9-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

this.tiObj = tiObj; this.delay = delay; } public void run() { while(true) {

for (int i = 0; i< delay; i++); tiObj.timerFired(); } } }

What Is an Abstract Class? Consider an example to help you understand abstraction and its relation to an abstract class. Consider a small animal world consisting of fluffy the Cat, fido the Dog, spot the Dog and tweety the Bird. You can collect fido and spot into the Dog class, and you might recognize that both Dogs and Cats are Mammals, but what would it mean to create a Mammal object? Mammal is an abstraction that you can use to describe common properties of Dog and Cat (and Person), but you never actually create a Mammal. Therefore, Mammal is abstract.

The Employee class discussed earlier should be abstract. You can create instances of Administrator, Programmer and Janitor, but never Employee. Of course, administrators, programmers and janitors are also employees, but you cannot create an Employee object. The new Employee class would be as follows:

abstract class Employee { // Employee constructors all go here. Employee() // There will be other constructors. { } // instance variables int sickDays; String name; String department; double salary; // instance methods void printAll() { System.out.println("Name: " + name); System.out.println("Department: " + department); System.out.println("Salary: " + salary); } abstract void calculateBonus(); }

abstract

A class or object

that is incompletely

defined, used to

collect properties or

behaviors.

Page 144: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

9-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Notice that the calculateBonus method was also defined as abstract. To make a method abstract, simply include the keyword abstract and do not declare a body block. If any method is declared abstract in a class, then the class must be declared abstract. You can, however, make the class abstract without having any abstract methods. If the class is abstract, it cannot be used to create an object, but must be extended to a subclass with all methods defined. You can also make the subclass abstract if you do not define all the abstract methods.

Remember that classes also define a data type, so an abstract class can be used for a type. Suppose that you want to create an array of Employee objects, some of them instances of Administrators, some instances of Programmer and some instances of Janitor. If you want to have all the Employees execute the calculateBonus method, you could do the following:

Employee[] emps = new Employee[3]; emps[0] = new Administrator(); emps[0] = new Programmer(); emps[0] = new Janitor(); for (int i = 0; i < emps.length; i++) { emps[i].calculateBonus(); }

Even though you cannot create Employee objects, you can store Employee subclass objects into an array of Employees. You know that the calculateBonus method will be defined for all the elements of the array because they are all extending Employee, guaranteeing that they have this method.

Page 145: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 9: Interfaces and Abstract Classes 9-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lab 9-1: Using interfaces and polymorphism in Java

Currently, your Clock/Timer class system is tightly coupled because the Clock and Timer classes are uniquely dependent on each other to create their callback scenario. In this lab, you will remedy this dependency with the use of an interface.

1. Create and compile an interface called TimerInterface that prototypes a single method public void timerFired().

2. Decouple your current MyClock and Timer classes by implementing the TimerInterface with your MyClock class.

3. Modify your Timer class to accept this new TimerInterface type as its callback object.

4. Test your new system.

Hint: The effect is most noticeable if each class that uses a Timer object specifies a unique delay and output.

Page 146: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

9-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Interfaces and abstract classes are important tools for the object-oriented system designer. In an earlier lesson, you identified the classes that might compose a grocery store inventory system. From this list, identify related classes and the interfaces or abstract classes that could be used to unify your design.

Skills review

In this lesson, you learned to use interfaces to resolve multiple characteristics and demonstrate polymorphic behavior. You also learned to use abstract classes and abstract methods. The topics in this lesson were focused on teaching you object-oriented programming.

Now that you have completed this lesson, you should be able to:

� Define and use interfaces.

� Define polymorphism.

� Use abstract classes.

� Create an abstract method.

Page 147: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 9: Interfaces and Abstract Classes 9-13

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 9 Review

1. In Java, what is an interface? What purpose can it serve?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

2. How does an interface implement its methods?

_______________________________________________________________

_______________________________________________________________

3. How can interfaces be used to give Java some multiple inheritance functionality?

_______________________________________________________________

_______________________________________________________________

4. In object-oriented programming, which approach is generally superior: designing by interfaces or designing by inheritance? Why?

_______________________________________________________________

_______________________________________________________________

5. What is coupling?

_______________________________________________________________

6. What is an object type? How does it relate to interfaces and object-oriented programming in general?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 148: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

9-14 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

7. What is polymorphism?

_______________________________________________________________

_______________________________________________________________

8. What is an abstract class?

_______________________________________________________________

Page 149: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

10Lesson 10:

Packages and Access

Modifiers

Objectives By the end of this lesson, you will be able to:

� Compile and run a class with packages.

� Identify the packages in the Java 2 API.

� Identify the various access levels in Java.

� Describe how access modifiers can be used to set the access level of a variable, method or class.

� Describe the object-oriented programming principle of encapsulation.

� Identify accessor and mutator methods.

Page 150: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

10-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. What results from attempting to compile the following Java code?

1. public class MyClass 2. { 3. public int a; 4. protected int b; 5. int c; 6. private int d; 7. 8. public static void main(String [] args) 9. { 10. MyClass mc = new MyClass(); 11. mc.a = 1; 12. mc.b = 1; 13. mc.c = 1; 14. mc.d = 1; 15. } 16. }

a. A compile-time error occurs at lines 12, 13, and 14. b. A compile-time error occurs at lines 13 and 14 only. c. A compile-time error occurs at line 14 only. d. The code compiles without error.

2. What results from attempting to compile the following Java code?

1. class MyClass 2. { 3. public int a; 4. protected int b; 5. int c; 6. private int d; 7. } 8. 9. public class JPF 10. { 11. public static void main(String [] args) 12. { 13. MyClass mc = new MyClass(); 14. mc.a = 1; 15. mc.b = 1; 16. mc.c = 1; 17. mc.d = 1; 18. } 19. }

a. A compile-time error occurs at lines 15, 16, and 17. b. A compile-time error occurs at lines 16 and 17 only. c. A compile-time error occurs at line 17 only. d. The code compiles without error.

Page 151: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 10: Packages and Access Modifiers 10-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

3. What are the advantages of encapsulation?

_______________________________________________________________

_______________________________________________________________

Page 152: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

10-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Introduction to Packages and Access

Modifiers Recall that you needed a method called public static void main(String[]

args) to run a particular application. So far, you know this is a class method (static) called main with no return value (void), which can receive an array of strings. The keyword public requires an understanding of two concepts in Java: packages and access modifiers.

Packages Packages organize classes into a hierarchy of related subsystems. In Java, classes are placed in specific directories called packages.

A package is created by placing a package statement at the top of a Java source file. To place the Employee class in a package called payroll.info, the first line of the file would be as follows:

package payroll.info;

Java places the packages into subdirectories, using the period (.) as a directory separator. According to the preceding statement, a payroll directory exists with an information directory underneath it. To compile the revised Employee class (in the SDK) and create the directories if they do not exist, enter the following:

javac -d . Employee.java

The Employee.class file is placed in the payroll\info subdirectory. To run a class in the payroll\info subdirectory (assuming that the class contains a main method), enter the following:

java payroll.info.Employee

If you want to use the Employee class from another package, you have two options. You can reference the class name with the complete notation as follows:

payroll.info.Employee e = new payroll.info.Employee();

Alternatively, you can make the Employee class visible by including an import statement after the package designator, as follows:

import payroll.info.Employee; // Makes only Employee // visible. import payroll.info.*; // Makes all classes // within the payroll.info // package visible.

package

A collection of

classes designated

by the package

keyword; Java

stores the classes in

a directory structure

based on the

package.

import

A statement that

makes a package

visible within a file.

Page 153: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 10: Packages and Access Modifiers 10-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

For this course, you will generally use the default package (the default directory in which the source files are stored).

Java packages are useful for the following reasons:

• Packages can be used in more complex systems to organize subsystems of a program. For example, a program might have a database subsystem, a GUI subsystem, and a networking subsystem—each of which can be assigned to its own package. Packages are often distributed as reusable programs, which can be incorporated into other programs.

• Packages help you avoid name conflicts with other classes. If you can extend the name of your class by including the directory in which it resides, you are less likely to conflict with other classes that have the same name but reside in different packages.

• Packages allow you to control the extent to which other classes can access your classes. This principle relates to access modifiers.

Access Modifiers You can control the accessibility of your class and its members through the use of three keywords: public, protected, and private. A fourth access level, package, is assumed if no access modifier is specified. Figure 10-1 shows the level of restriction each keyword places on classes and their members, from least restrictive (public) to most restrictive (private).

public privatepackageprotected

Figure 10-1: Access levels

The access levels perform as follows.

• Public: states that the method or class is accessible from any method in any other class.

• Protected: restricts the visibility of a member or class to classes in the same package or to subclasses derived from this class but contained in other packages.

• Package (denoted by the absence of an access keyword): restricts access of members and classes to only classes defined in this package.

• Private: restricts access of a method or variable to the class in which it is defined.

public

Access modifier that

allows the class or

member to be seen

by every part of the

program.

protected

Access modifier that

allows the class to

be seen by classes

in the same

package or

subclasses in other

packages.

private

Access modifier that

is applied to the

member only;

restricts access to

the class in which it

is defined.

Page 154: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

10-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Any class member can be declared private, but a class cannot. Either a class or a class member can be declared public. A public class might have private members (i.e., a method or variable that can only be accessed by other methods in the class).

Java 2 Application Programming

Interface Another place where packages are used is the standard Java 2 Application Programming Interface (API). The Java 2 API is organized into packages such as java.lang, java.awt (for graphical elements), java.io (for input/output elements), java.util (for utility programs), and java.net (for networking elements). The specification of the visible (non-private) methods for each class is contained in the last half of the Java in a Nutshell book, and in the API documentation that supports the Java 2 SDK. To use one of the classes in these packages, you can either import the class (or the entire package) or include a complete reference. The classes in java.lang do not need to be imported; they are visible to every Java program. However, you can import java.lang.* to your program to remind you where the references come from. These classes will be used throughout this course.

Encapsulation As you create Java classes, it is good practice to restrict access to member variables and provide only the necessary access privileges to member methods. Using your Employee class, you can make all the variables private as follows:

class Employee { // Instance Variables private String name; private String department; private double salary; // Instance Method public void printAll() { System.out.println("Name: " + name); System.out.println("Department: " + department); System.out.println("Salary: " + salary);

}

Java 2 Application

Programming

Interface (API)

The built-in

functionality of

Java.

Page 155: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 10: Packages and Access Modifiers 10-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

You can no longer use direct references to the variables outside of the class. For example, rachael.name = "Rachael"; is not allowed. You must add methods to "get" and "set" instance variables. A method that allows you to read a variable is called an accessor; a method that allows you to modify an instance variable is called a mutator . Following are examples of these methods:

// accessor public String getName() { return name; } // mutator public void setName(String tmpName) { name = tmpName; }

With private variables, accessors and mutators, you can control the manner in which other programs use the classes you write. The object-oriented term for this ability is encapsulation.

In the ideal object-oriented world, the objects you create are accessible only by the methods made publicly available. In addition, how these methods are implemented is completely hidden from the user of that object. This feature has several advantages.

One advantage is reduced coupling. If an object is well-defined in terms of the methods it makes publicly available, then as long as those methods remain available, you do not have a problem. For example, suppose a database object completely changes the database engine it uses. As long as it continues to support the public methods it makes available, nothing else will be adversely affected. Other objects that may have been relying on the methods of that database object may continue to do so. The only thing that has changed is the database object's implementation of those methods, which is kept completely hidden.

Another use for good encapsulation is security. Even if other code is not inadvertently compromising your objects, a user may be trying to compromise them intentionally. If an object is encapsulated, and the only access you have to that object is through its well-defined methods, then the object is safer from tampering.

accessor

A method that

reads a variable.

mutator

A method that

modifies a variable.

encapsulation

The wrapping of

variables and

methods together;

variables can only

be accessed

through the

methods provided.

Page 156: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

10-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Figure 10-2 shows a diagram of object encapsulation.

Data 1Data 2Data 3Data 4

Figure 10-2: Object encapsulation

The variables (data) are protected from access by the methods. You can use mutators to validate data and to cause other data to be changed. Accessors allow the users of your class to see only the data they need to see. The convention of naming these methods getVariable() and setVariable() will be important if you study the development of JavaBeans.

As a general rule, you should design classes so that all the

instance variables are declared private, and the only

way to access those variables is through methods. By

using accessors and mutators, you can help maintain a

high degree of encapsulation.

Page 157: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 10: Packages and Access Modifiers 10-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lab 10-1: Using encapsulation, accessors and mutators

in Java

In this lab, you will write encapsulated objects. Encapsulated objects should have their private data accessible only through the methods made publicly available.

1. Declare all instance variables of the Employee class private.

2. Create a proper accessor and mutator for each of the private variables.

3. Guarantee that the rest of the class structure works (for example, the Programmer class). Make any necessary modifications.

4. Create a main class to test the class structure you developed in Steps 1 and 2.

5. Compile and execute the program.

6. (Optional) Some classes are defined as "read only," meaning immutable. With your understanding of accessors and mutators, create a subclass of Employee that is "read only." Ask your instructor for help if you need it.

Page 158: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

10-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Packages are an important tool for organizing classes into a hierarchy of related subsystems. Packages promote modular design and code reuse, and help to reduce programming errors. In an earlier lesson you identified a list of classes that could compose a grocery store inventory system. From these classes, identify subsystems and determine how the classes might be placed into packages.

Skills review

In this lesson, you learned to use packages as directories to store your Java classes. You also learned to use access modifiers to control accessibility to your classes and members. You were introduced to the Java 2 API, and you learned to protect the Java programs you write through encapsulation. You will use the package structure of the API, but for the duration of this course you should put all your programs into a single directory. When all your bytecode is in one directory, there is only public and private accessibility. Default and protected classes and members have the same visibility as public in this case.

Now that you have completed this lesson, you should be able to:

� Compile and run a class with packages.

� Identify the packages in the Java 2 API.

� Identify the various access levels in Java.

� Describe how access modifiers can be used to set the access level of a variable, method or class.

� Describe the object-oriented programming principle of encapsulation.

� Identify accessor and mutator methods.

Page 159: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 10: Packages and Access Modifiers 10-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 10 Review

1. What is a package in Java?

_______________________________________________________________

_______________________________________________________________

2. List three reasons that Java packages are useful.

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

3. What is the default package?

_______________________________________________________________

_______________________________________________________________

4. What are access modifiers?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

5. Name the four access levels. How is each specified?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 160: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

10-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

6. What is the Java 2 API? How does it relate to packages?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

7. What is encapsulation? Name two advantages of encapsulation in object-oriented programming.

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

8. How do accessors differ from mutators? How are they similar?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 161: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11Lesson 11:

Swing Components

Objectives By the end of this lesson, you will be able to:

� Distinguish between the AWT and Swing.

� Identify the general organization of the Swing class structure.

� Define and use Swing widgets and containers.

Page 162: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. Which of the following Swing classes is not a container?

a. ImageIcon b. JScrollBar c. JApplet d. JButton

2. Which of the following is not true with respect to Swing?

a. Swing components follow a peer pattern. b. Swing components follow the Model-View-Controller paradigm. c. Swing components are implemented as lightweight components. d. Swing extends Java's original Abstract Windowing Toolkit.

3. What is the principle difference between AWT and Swing components?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 163: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 11: Swing Components 11-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

What Is the AWT? When Sun Microsystems released the Java Development Kit (JDK) 1.0 several years ago, Java came with a platform-independent graphical toolkit called the Abstract Windowing Toolkit (AWT) .

The AWT 1.0 package does not provide many prebuilt components. Creating new AWT 1.0 components is difficult, and the only way to customize some prebuilt components is to subclass the original component, then override some methods to provide new functionality. Certain components cannot be customized at all. These restrictions make it difficult to create large-scale GUIs using AWT 1.0. However, AWT 1.0 is useful for creating simple applets that perform simple animation or other graphical effects.

The two greatest drawbacks of AWT 1.0 are:

• Event handling in one method.

• Use of heavyweight components.

Heavyweight components (peer pattern)

To make AWT 1.0 platform independent, Sun Microsystems chose to use native graphical toolkits (available to the underlying operating system) to create all the AWT components. This choice limited the AWT to those components available on all supported platforms.

AWT 1.0 uses heavyweight components. When someone creates an AWT button in Windows, the Java Virtual Machine actually creates a Windows button, a peer of the Java button. This process is called the peer pattern. Each time an AWT component is created, its native peer is created and displayed on the screen. To the programmer, it appears that a Java button was created, but the Java button is a simple interface to access the methods available on the peer button. Similarly, when a button is created on Linux, a native Linux button is created and accessed through the methods and properties available to the AWT button API.

This peer pattern makes it difficult to create complex user interfaces with advanced components (which may not be available on the underlying operating system's graphical toolkit).

Abstract Windowing

Toolkit (AWT)

The GUI classes of

Java.

peer pattern

The process by

which the JVM calls

a platform-specific

GUI component

equivalent to the

component

supplied by the GUI;

used by the Java

AWT.

Page 164: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

AWT 1.1

AWT 1.1 (which comes with the JDK 1.1 and later) still uses the peer pattern to create components. Therefore, this toolkit lacks powerful components, using the same types available in the AWT 1.0. The biggest difference between the JDK 1.0 and later releases is not in the AWT, but in the way that events are handled. Event handling will be discussed in detail later in the course.

What Is Swing? The main difference between Swing and the AWT is the absence of the peer pattern. Swing does not use native peers for every component in the API; instead, it uses 100-percent Java GUI components, which look the same across all supported platforms.

By not using platform-dependent peers or heavyweight components, Swing offers a much richer selection of powerful user-interface components for all supported platforms. All Swing components are lightweight, making the Swing API very large. All the classes are approximately 2 MB and require considerable memory. These disadvantages are not serious, however, because JVMs are becoming faster and more efficient. The Java 2 SDK 1.2.x is designed to address many Java speed and stability problems.

Because all Swing components are written from scratch (in Java), you can modify them however you like; this latitude was not possible with AWT 1.1. That version offered no way to radically change the functionality or appearance of standard AWT components. For example, you could not add an image to an AWT button. You had to create a separate class by subclassing the Panel class and implementing all desired functionality manually to create an image button. With Swing, you no longer need to recreate functionality; you can save work by subclassing existing components.

Swing also allows programmers to customize existing components without having to subclass them. By using event delegation and having a variety methods to change the behavior of each component, Swing allows you to easily customize existing components with little effort. Most of your effort will involve learning the new patterns and paradigms associated with Swing.

Swing

A GUI toolkit used

by Java.

Page 165: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 11: Swing Components 11-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Model-View-Controller (MVC) programming paradigm

A major difference between AWT 1.1 and Swing is the way in which they are written. Every component in Swing is written using a modified version of the Model-View-Controller (MVC) programming paradigm. Though difficult to understand at first, this paradigm provides a formal way to create graphical object-oriented programs. MVC programs generally have fewer bugs and are more extensible.

Basic Swing Components The Swing API is enormous. As such, this course will restrict its attention to the most commonly used components that do not rely heavily on MVC methodologies. Figure 11-1 shows the components of the Swing API and how they relate to the AWT components.

javax.swing

java.applet

java.awtObject

Component

Panel

Container

Window

JComponent

JScrollbar

JScrollPane

ImageIcon

JLabel

JPanel JTextComponent AbstractButton

JTextArea JTextField

JButton

Frame

JFrame JApplet ImageIcon

Applet

JFileChooser

Figure 11-1: Portion of Swing API and relation to AWT

Page 166: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

From the preceding figure, this course will focus on the following components.

• JComponent: the parent class to many Swing components.

• JLabel: displays simple text or images.

• JButton: a standard clickable button.

• JTextField: for single-line text entry.

• JTextArea: for multiline text entry.

• JScrollBar: a standard scrollbar.

• ImageIcon: represents a graphic or icon. Note: ImageIcon is not a component.

• JScrollPane: adds scrollable functionality to other components.

• JPanel: a non-stand-alone container.

• JFrame: a stand-alone container.

• JFileChooser: a system-independent file selection dialog.

• JApplet: a component to run Java in a Web browser.

The preceding figure illustrates the Swing class structure. At the top of the Swing hierarchy is the JComponent class. This class has been declared abstract, but offers numerous methods for your use. Many of the methods that offer the functionality you seek are inherited from JComponent.

Do not confuse JComponent with component. The former

refers to the class JComponent, whereas the latter is a

general term used to refer to any of the child classes of

the Component class.

The JComponent class can be conceptually divided into three additional categories:

• Graphical widgets

• Text components

• Containers

JComponent

A high-level Swing

class from which

many other

components

receive their core

functionality.

Page 167: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 11: Swing Components 11-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Graphical widgets

Widgets are the graphical components with which users interact, such as JButtons, JLabels, JScrollBars and others. Typically, to use a widget of any sort, you need to know the nature of its constructor. As you become accustomed to the various Java components, you can often predict the nature of constructors before referring to the API; they follow common sense.

Interestingly, every Swing component listed in Figure 11-1, except ImageIcon, is a descendent of the AWT Container class. This fact might seem to blur the line between a Container (which can contain other components) and a widget (an interactive graphical element). The ability for a Swing component to contain other components is part of its power. In this lesson, you will explore some of the more common components in detail.

ImageIcon

An ImageIcon is not a JComponent; it extends Object directly. However, ImageIcon is often used with other components, which is why you will examine it before discussing other components. The ImageIcon implements the Icon interface and its functionality. Therefore, anywhere you want to use an Icon, an ImageIcon would probably meet your needs.

Two of the more useful constructors of ImageIcon are the following:

public ImageIcon(String filename) public ImageIcon(URL url) // Java has a URL class

Because ImageIcon is not a JComponent, it cannot be directly added to a component that is expecting another JComponent. Therefore, you must add the ImageIcon to a component that can receive an ImageIcon (or Icon), such as a JButton or JLabel (which we will discuss shortly). Consider the following example:

class ImageIconStuff extends JFrame { ImageIcon icon = new ImageIcon("btn_readme.gif"); JLabel myLabel = new JLabel(icon); ImageIconStuff() { setupGUI(); } private void setupGUI() { Container c = getContentPane(); c.add(myLabel); setSize(100,100); setVisible(true); } }

widget

A term used to refer

to any interactive

visual component of

a GUI.

ImageIcon

A high-level Swing

class that facilitates

the display of

images; implements

the Icon interface

Page 168: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

To run this code, one style dictates that you create a dummy class whose purpose is to instantiate the necessary classes to begin the process. Following is an example of this approach:

public class SectionThree { public static void main(String[] args) { ImageIconStuff iStuff = new ImageIconStuff(); } }

Your output should resemble Figure 11-2.

Figure 11-2: Output of ImageIconStuff

From this point on, it will be assumed that the preceding code (or its equivalent) will be used to instantiate any necessary classes.

JButton

To create a JButton, you must instantiate it in the same manner that you would instantiate any class. You may want to access this JButton later (perhaps to disable it), therefore you should declare it as an instance variable. You need to know the nature of the constructor. It makes sense to label the JButton with a function (method) such as Calculate or Exit. Therefore, it makes sense that the JButton class has a constructor that takes a string as a parameter. Additionally, recall that JButton is really a subclass of JComponent, which is a subclass of Container. Therefore, it is possible to place an ImageIcon in a JButton. Several useful constructors of the JButton can be used to accomplish these goals:

public JButton(String text) // text only public JButton(Icon icon) // icon only public JButton(String text, Icon icon) // text and icon

JButton

A simple clickable

Swing widget.

Page 169: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 11: Swing Components 11-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

If you choose to display a JButton with both text and an icon, you may want to position the text and icon in a particular manner. The JButton class offers the following methods to do this:

JButton myButton = new JButton("Click",icon); // icon // previously instantiated // text and icon are aligned to the left myButton.setHorizontalAlignment(JButton.LEFT);// also RIGHT // and CENTER // text is placed to the left of the icon myButton.setHorizontalTextPosition(JButton.LEFT);// also RIGHT // and CENTER // text and icon are aligned with the top myButton.setVerticalAlignment(JButton.TOP);// also RIGHT // and CENTER // text is aligned with the TOP of the icon myButton.setVerticalTextPosition(JButton.TOP);// also BOTTOM // and CENTER

The following example displays a JButton with text and an icon. The default text and icon positions are assumed (centered with text to the right).

class JButtonStuff extends JFrame // JFrames are covered shortly { ImageIcon icon = new ImageIcon("btn_readme.gif"); JButton myButton = new JButton("Click", icon); JButtonStuff () // Constructor { setupGUI(); } private void setupGUI() // a private internal method { Container c = getContentPane(); c.add(myButton); // Assume this code for now setSize(100,100); setVisible(true); } }

Page 170: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Your output from this code should resemble Figure 11-3.

Figure 11-3: Output of JButtonStuff

Many holes exist in your code at this point. You have not learned about JFrame yet, and you still do not know how this JFrame is displayed. In addition, the JButton is not active (that is, nothing happens when you click it). These matters will be resolved later.

Keep in mind that a JButton class is a class like any other. It has properties and methods that may be useful. You can access these properties and methods as you would any other instance variable using dot notation.

class JButtonStuff extends JFrame { JButton myButton = new JButton("A Button"); JButtonStuff() { setupGUI(); } private void setupGUI() { myButton.setEnabled(false); Container c = getContentPane(); c.add(myButton); // Assume this code for now setSize(100,100); setVisible(true); } }

Your output from the preceding code should resemble Figure 11-4. Note that the button appears the same.

Figure 11-4: New output of JButtonStuff is same

Page 171: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 11: Swing Components 11-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

JLabel

JLabel facilitates the placement of text or images with your GUI. Its basic constructors follow a natural pattern. Notice that one of its constructors takes an ImageIcon. This feature is handy and allows you to place an ImageIcon almost anywhere as long as it is first placed in a JLabel. The syntax is as follows:

public JLabel(String name) // text label public JLabel(Icon) // icon label

Unlike the JButton, no constructor allows for an icon and text upon instantiation. However, methods of the JLabel class allow the following:

JLabel myLabel = new JLabel("My Label"); // text label myLabel.setIcon(icon); // icon previously instantiated

Like the JButton, methods control the alignment of the icon and text of the JLabel:

// text and icon are aligned to the left myLabel.setHorizontalAlignment(JButton.LEFT);// also RIGHT // and CENTER // text is placed to the left of the icon myLabel.setHorizontalTextPosition(JButton.LEFT);// also RIGHT // and CENTER // text and icon are aligned with the top myLabel.setVerticalAlignment(JButton.TOP);// also BOTTOM // and CENTER // text is aligned with the TOP of the icon myLabel.setVerticalTextPosition(JButton.TOP);// also BOTTOM // and CENTER

JLabel

A Swing widget

used to place text in

relation to an icon.

Page 172: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Consider the following example:

class JLabelStuff extends JFrame { ImageIcon myIcon = new ImageIcon("btn_readme.gif"); JLabel myLabel = new JLabel("A Label"); JLabelStuff() { setupGUI(); } private void setupGUI() { Container c = getContentPane(); myLabel.setIcon(myIcon); // add the icon // place the text to the left of the icon myLabel.setHorizontalTextPosition(JLabel.LEFT); c.add(myLabel); // Assume this code for now setSize(100,100); setVisible(true); } }

Your output should resemble Figure 11-5.

Figure 11-5: Output of LabelStuff

Page 173: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 11: Swing Components 11-13

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

JScrollBar

The JScrollBar class allows you to select from a range of values in a graphical manner. You must answer the same question: What should the constructor be? You will ultimately refer to the API, but try to determine it on your own first. A JScrollBar is either horizontal or vertical. You must specify an initial value and a size for the thumb (the indicator or elevator button) for the JScrollBar. You should be able to specify a range of values (e.g., 0 to 212 for a thermometer in Fahrenheit). Confident of your requirements, consult a Java 2 API and find an appropriate constructor. Following is an example:

class JScrollBarStuff extends JFrame { JScrollBar myScrollBar = new JScrollBar(JScrollBar.HORIZONTAL, 32, 10, 0, 212); JScrollBarStuff () { setupGUI(); } private void setupGUI() { Container c = getContentPane(); c.add(myScrollbar); setSize(200,50); setVisible(true); } }

Your output should resemble Figure 11-6.

Figure 11-6: Output of JScrollBarStuff

This constructor was sophisticated but appropriate, and used the following format:

public JScrollBar(int orientation, int initial Value, int extent, int minValue, int maxValue)

Note that extent is the term used for the scrollbar thumb (also known as the indicator or elevator button).

JScrollBar

A Swing widget

used to visually

select a single value

from a range.

Page 174: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11-14 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

JTextField

As your abstraction skills continue to improve, your assumption might be that the constructor of a JTextField should accept an integer specifying its width as a number of columns. Perhaps you should be able to set some default text, such as an example of the desired format. Such constructors are available as observed in the API. Following is an example:

class JTextFieldStuff extends JFrame { JTextField myTextField = new JTextField("Some Text",25); JTextFieldStuff() { setupGUI(); } private void setupGUI() { Container c = getContentPane(); c.add(myTextField); setSize(200,50); setVisible(true); } }

Your output should resemble Figure 11-7.

Figure 11-7: Output of JTextFieldStuff

Other constructors for JTextField include the following:

public JTextField(String text, int columns) public JTextField(); // default constructor

JTextField

A single-line text-

entry widget in

Swing.

Page 175: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 11: Swing Components 11-15

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

JTextArea

JTextArea has multiple uses. It can serve as a miniature editing window for entering text, and it can also display information. As you might expect, a class with this constructor can take two integers: the number of rows and the number of columns.

class JTextAreaStuff extends JFrame { JTextArea myTextArea = new JTextArea(10,40); // specify number of rows and columns JTextAreaStuff() { setupGUI(); } private void setupGUI() { Container c = getContentPane(); c.add(myTextArea); setSize(200,200); setVisible(true); } }

Your output should resemble Figure 11-8.

Figure 11-8: Output of JTextAreaStuff

Additional constructors for JTextArea include the following:

public JTextArea(String text) public JTextArea(); // Default constructor

JTextArea

A multiline text-entry

widget in Swing

Page 176: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11-16 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

JScrollPane

One problem with the JTextArea is that if the user types enough text to exceed the boundaries of the JTextArea, the JTextArea will not scroll to accommodate it. Additionally, if an image is loaded and exceeds the boundaries of the container in which it is displayed, the container also will not scroll. Thus, components that should be scrollable (such as JTextArea) are by default not scrollable. A JScrollPane adds this scrolling functionality to a component.

You will add scrolling behavior to your JTextArea. Perhaps the easiest way is to instantiate a JScrollPane class passing the component you want to make scrollable in its constructor. For example:

JTextArea ta = new JTextArea(); JScrollPane sp = new JScrollPane(ta); // Scrollbars now added

This code will automatically add scrollbars to the JTextArea as needed. However, you might want to modify the behavior of the scrollbars. Customization is possible with a series of methods available to the JScrollPane class:

// continuing with our example... sp.setHorizontalScrollBarPolicy(int horizoptions); // where horizontal options are: // JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS // JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED (The default) // JScrollPane.HORIZONTAL_SCROLLBAR_NEVER sp.setVerticalScrollBarPolicy(int vertoptions); // where vertical options are: // JScrollPane.VERTICAL_SCROLLBAR_ALWAYS // JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED (The default) // JScrollPane.VERTICAL_SCROLLBAR_NEVER

Finally, do not add the JTextArea to your container. You must add the JScrollPane instead because it contains the component you want to scroll.

// using the add() of your container... c.add(sp);

JScrollPane

A Swing text-entry

widget that adds

scrolling

functionality to

other components.

Page 177: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 11: Swing Components 11-17

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Following is a complete example:

class JScrollPaneStuff extends JFrame { JTextAreaStuff myTextArea = new JTextArea(10,40); JScrollPane myScrollPane = new ScrollPane(myTextArea); JScrollPaneStuff() { setupGUI(); } private void setupGUI() { Container c = getContentPane(); myScrollPane.setHorizontalScrollBarPolicy (JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); myScrollPane.setVerticalScrollBarPolicy (JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); c.add(myScrollPane); setSize(200,200); setVisible(true); } }

Your output should resemble Figure 11-9.

Figure 11-9: Output of JScrollPaneStuff

Page 178: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11-18 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

JFileChooser

A JFileChooser is a small pop-up window that allows you to select a file name to either save or load. Note, however, that the JFileChooser does not perform the actual saving or loading of the file.

JFileChooser is modal. If a JFileChooser pops up, it blocks the user from interacting with the GUI until the JFileChooser is closed (by clicking Load/Save or Cancel). The modal feature can be disabled.

The constructor for JFileChooser is appropriate; you can instantiate a JFileChooser with a default constructor, or pass it to the directory you want to initially display. If you choose to use the default constructor, your initial directory will be your working directory, depending on your environment.

Once instantiated, a JFileChooser can be displayed in either Save mode or Load mode with the following commands:

JFileChooser chooser = new JFileChooser(); // instantiated int returnVal1 = chooser.showOpenDialog(this); // open a file int returnVal2 = chooser.showSaveDialog(this); // save a file

Several considerations should be noted here. The showOpenDialog(this) and showSaveDialog(this) commands will visually display the JFileChooser. The keyword this is necessary because a dialog is commonly associated with a parent window or frame. In this case, assume that this refers to the JFrame from which the JFileChooser was instantiated. Also note that both methods return an integer. These processes are necessary because a user might select a file to save or load, but then choose to cancel this operation. Even though the user cancelled this operation, the file he or she selected will still be returned through the JFileChooser instance (chooser). Therefore, even though you have a file name, you must verify that the user did not click the Cancel button. You can perform this verification using some predefined constants of JFileChooser as follows:

// continuation of above code to determine whether a Cancel // button was clicked... if(returnVal1 == JFileChooser.APPROVE_OPTION) { // code to get the file name because the user selected // a file name and clicked the Load button } else if(returnVal1 == JFileChooser.CANCEL_OPTION) { // code to respond to cancellation because the user // clicked the Cancel button }

JFileChooser

A Swing component

used to retrieve the

names of files.

modal

A property

designating that a

component blocks

its parent

Component until

proper response is

received.

Page 179: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 11: Swing Components 11-19

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

If the user did in fact select a file, then it is necessary to obtain the actual name of the selected file:

// modification of preceding code to obtain the file name... String fileName = ""; if(returnVal1 == JFileChooser.APPROVE_OPTION) { fileName = chooser.getSelectedFile().getName(); } else if(returnVal1 == JFileChooser.CANCEL_OPTION) { // code to respond to cancellation because the user // selected the Cancel button }

In the preceding code, notice the methods used to obtain the file name. The method getSelectedFile of JFileChooser returns a file object, whereas getName is a method of the class File which returns the String representation of the file. A complete example follows:

class JFileChooserStuff extends JFrame { // specify the starting directory to be the root of // the C drive JFileChooser chooser = new JFileChooser("c:\\"); String fileName = ""; { setupGUI(); } private void setupGUI() { setSize(300,300); // just an empty frame right now setVisible(true); int retVal = chooser.showOpenDialog(this); if(retVal == JFileChooser.APPROVE_OPTION) { fileName = chooser.getSelectedFile().getName(); System.out.println("Selected file: " + fileName); } else if(retVal == JFileChooser.CANCEL_OPTION) { System.out.println("Operation cancelled"); } } }

Page 180: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11-20 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Your output should resemble Figure 11-10.

Figure 11-10: Output of JfileChooserStuff

Swing Containers With the introduction of JButtons, it was stated that some holes exist in your code. The declaration of your class used the word JFrame, and you had not yet learned how the example classes became visible. We approach these topics now, starting with an explanation of the JFrame class and Container. You will not fully understand how you can see your components until you examine layout managers.

In Java, components need to be placed in containers. Two types of containers exist: top-level and lower-level. Top-level containers (JFrame, Window) cannot be contained in other containers. Lower-level containers (JPanel, JScrollPane) can exist only inside another container. Containers are commonly nested within other containers.

Swing components were designed to be highly extensible. As such, almost all Swing components ultimately inherit from the Container class. Review Figure 11-1 to confirm the relationship between the AWT Container class and Swing components.

Container

An abstract, high-

level component

that offers JFrame

and JPanel much

of their functionality.

top-level container

A Container that

cannot be

contained in another Container,

such as a JFrame.

lower-level

container

A Container that

must be contained

in another

Container, such as

a JPanel.

Page 181: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 11: Swing Components 11-21

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

JFrame

JFrame is the primary container used to create stand-alone applications. You might expect that Window would be the primary container, but this is not the case in Java. Because JFrame is a class, you can readily extend it and inherit all its capabilities. In this example, the JFrameStuff class extends JFrame.

class JFrameStuff extends JFrame { JFrameStuff () { setupGUI(); } private void setupGUI() { setSize(150,150); // set the size in // pixels setTitle("Practice"); setCursor(Frame.HAND_CURSOR); // just an example; setVisible(true); // make the Frame } // visible }

Your output should resemble Figure 11-11.

Figure 11-11: Output of JFrameStuff

When a JFrame is first created, its display size (excluding the title) is 0x0 and it is not visible. To see the contents of a JFrame, you must invoke the setSize and the setVisible methods. You have done this throughout the previous JFrame examples.

Adding components to a JFrame is not a direct process. The reason is that the JFrame is not a single component, but rather a combination of several components all working together. These components are JFrame, JRootPane, JLayeredPane, ContentPane (actually a Container), and GlassPane (actually a Component). This level of sophistication is necessary to include in Swing such features as Multi-Document Interface (MDI) and "drag and-drop" functionality. If you do not need to create an MDI application, then your approach is straightforward. To add a component to a JFrame, first you must associate the ContentPane with the JFrame. From that point, simply add your components to the ContentPane. By adding components directly to the ContentPane, you are indirectly adding components to the JFrame.

JFrame

The fundamental

Window in Java; it

cannot be

contained in

another container.

Page 182: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11-22 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Continue with your setupGUI method, and attempt to add a single JButton to your JFrame as follows:

class JFrameStuff extends JFrame { JButton myButton = new JButton("My Button"); JFrameStuff () { setupGUI(); } private void setupGUI() { // First, associate the ContentPane with the JFrame Container c = getContentPane();

// Next, add the JButton to this ContentPane; // the JButton is automatically added to the JFrame c.add(myButton) setSize(150,150); // Set the size in // pixels. setTitle("Practice"); setCursor(Frame.HAND_CURSOR); setVisible(true); } }

Your output should resemble Figure 11-12.

Figure 11-12: Output of JFrameStuff with JButton

JPanel

A JPanel is a simple Container. It does not pop up or appear as a JFrame does. Instead, as a low-level Container, its job is to contain other Components (JButtons, JTextFields) or low-level Containers. JPanels also serve as handy Components upon which to draw graphics. In the following example, you will instantiate a JPanel. Its usefulness will not become fully apparent until later.

JPanel

A lower-level

Container used to

hold other

Containers; can

also be used as a

drawing surface.

Page 183: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 11: Swing Components 11-23

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Now you are familiar with the method add, which is a method inherited from Container class. It allows you to add your instantiated Components to your Container.

class JPanelStuff extends JFrame { JPanel myPanel = new JPanel(); JPanelStuff () { setupGUI(); } private void setupGUI() { Container c = getContentPane(); c.add(myPanel); // Add panel to frame; you will not setSize(125,125); // be able to see it setTitle("Practice"); setVisible(true); } }

Your output should resemble Figure 11-13.

Figure 11-13: Output of JPanelStuff

Lab 11-1: Creating basic Swing components

In this lab, you will create and display a Java JFrame, and populate it with the components presented in the text. The JFrame and other components will serve as the foundation for much of your GUI practice in this course and at work.

add

A method of Container used to

add components.

Page 184: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11-24 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

1. Use the following framework to instantiate and display the components as directed.

class ComponentStuff extends JFrame { // //Add code to create components from Step 2 here. // ComponentStuff() { setupGUI(); } private void setupGUI() { Container c = getContentPane(); c.setLayout(new GridLayout(6,1)); // we cover this topic next // //Add code to create components from Step 3 here. // setSize(300,500); setVisible(true); // //Add code from Step 4 here. // } }

2. Instantiate the following components: • ImageIcon with a small GIF of your choice • JButton with text and icon from ImageIcon • JLabel with text and icon from ImageIcon • JScrollBar • JTextField • JTextArea • JScrollPane to add scrollbars to the JTextArea • JFileChooser with the root directory as the start • JPanel

3. Add the following six components to your JFrame using the c.add method: • JButton • JLabel • JScrollBar • JTextField

• JScrollPane // the TextArea is automatically displayed • JPanel

Page 185: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 11: Swing Components 11-25

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

4. Display the JFileChooser in LOAD mode. Display the selected file on the command line. Be sure to test the Cancel button.

The title of a class that extends JFrame is often set by

calling the parent JFrame's constructor. Therefore, you

need not define a new constructor for JFrame.

class Practice extends JFrame { JPanel myPanel = new JPanel(); Practice() { super("My Title"); } }

You may have noticed that the JFrame you instantiated

from the last lab did not close when finished (unlike those

in earlier lessons in which the console opened and closed

unless you used an infinite while loop). This is because

graphical programs are always polling for environment

responses such as resize.

JavaBeans You should be aware of the JavaBeans technology. The JavaBeans specification is a software component model similar to the Microsoft COM. JavaBeans are individual graphic interface components that are designed according to a strict specification so that they can be easily dropped into an application window using visual tools.

For example, suppose you have access to a Web browser JavaBean. Such a bean would encapsulate all the functionality of a Web browser into an easily managed component, which can be dropped into an application using visual tools in the same manner as a JButton or a JTextField.

Libraries of JavaBeans are available from various vendors. JavaBeans can be used to rapidly develop sophisticated applications by combining several separately developed components.

Page 186: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11-26 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Because they do not rely on a peer pattern and are written in pure Java, Swing components are highly extensible. Referring to Figure 11-1, create a list of at least five user-defined components that could be derived from the existing Swing set. Identify the most likely parent class for each of the components you list.

Skills review

In this lesson, you learned how the Swing class structure is organized. You defined components, and you created an ImageIcon, a JButton, a JScrollBar and other components. You also defined containers, and you created a JFrame, a JFileChooser and a JPanel. These graphical components can be assembled in the next lesson to create complex graphical interfaces.

Now that you have completed this lesson, you should be able to:

� Distinguish between the AWT and Swing.

� Identify the general organization of the Swing class structure.

� Define and use Swing widgets and containers.

Page 187: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 11: Swing Components 11-27

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 11 Review

1. What is the AWT?

_______________________________________________________________

_______________________________________________________________

2. What are two drawbacks of the AWT?

_______________________________________________________________

_______________________________________________________________

3. What is the peer pattern?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

4. What is Swing?

_______________________________________________________________

_______________________________________________________________

5. Name at least three Swing components.

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

6. What is a widget in Swing?

_______________________________________________________________

Page 188: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

11-28 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

7. What does the term "modal" mean in relation to Swing components?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

8. What is a container in Swing? How does a top-level container differ from a lower-level container?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

9. What is the purpose of the add method in relation to Swing containers?

_______________________________________________________________

_______________________________________________________________

Page 189: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

12Lesson 12:

Layout Managers

Objectives By the end of this lesson, you will be able to:

� Define a layout manager.

� Set a layout manager for a container.

� Effectively use FlowLayout, GridLayout, BorderLayout and BoxLayout.

� Nest containers and layout managers to form more complex GUI layouts.

� Separate a complex design into its component containers and layout managers.

Page 190: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

12-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. What output is generated by the following Java code?

import java.awt.*; import javax.swing.*; public class MyFrame extends JFrame { public MyFrame () { Container c = getContentPane(); c.add(BorderLayout.NORTH, new JButton("1")); JPanel p = new JPanel(); for (int i = 2; i <= 4; i++) p.add(new JButton(Integer.toString(i))); c.add(p); setSize(200, 125); setVisible(true); } public static void main(String [] args) { new MyFrame(); } }

a.

b.

c.

d.

Page 191: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 12: Layout Managers 12-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

2. What output is generated by the following Java code?

import java.awt.*; import javax.swing.*; public class MyFrame extends JFrame { public MyFrame() { Container c = getContentPane(); c.add(new JButton("1")); JPanel p = new JPanel(); p.setLayout(new GridLayout()); for (int i = 2; i <= 4; i++) p.add(new JButton(Integer.toString(i))); c.add(p); setSize(200, 125); setVisible(true); } public static void main(String [] args) { new MyFrame(); } }

a.

b.

c.

d.

Page 192: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

12-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

3. What is the Border layout?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 193: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 12: Layout Managers 12-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

What Is a Layout Manager? Containers can hold other components, but they have no way to determine where these components should be placed. This task is performed by layout managers.

The Java API provides a variety of layout managers:

• BorderLayout

• BoxLayout

• CardLayout

• FlowLayout

• GridBagLayout

• GridLayout

• OverlayLayout

• ScrollPaneLayout

• ViewportLayout

Java also enables you to use absolute positioning, although this technique is discouraged due to variations in platforms and resolutions. It is recommended that you allow the layout manager to deal with cross-platform issues.

Layout managers can be frustrating. When you envision the way you want your interface to look, your layout manager should enable you to transform that vision into reality. However, the intended realization is not always possible. Layout managers must consider many elements before your components are actually displayed. Thus, you must often compromise in one way or another.

In this lesson, you will focus on the FlowLayout, GridLayout, BorderLayout and BoxLayout layout managers, which offer the greatest ease of use in relation to their functionality. CardLayout can be used when a tabbed index system is needed. GridBagLayout and OverlayLayout are the most flexible layouts, but also the most cumbersome. ScrollPaneLayout and ViewportLayout are component-specific.

layout manager

An object used to

control the

positioning of

components within

a container.

Page 194: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

12-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

FlowLayout Each layout is aptly named for its functionality. FlowLayout centers components on each line in a flowing manner. When no more room is available on that line of the container, the FlowLayout breaks to the next line. Figure 12-1 shows a frame with five buttons set to FlowLayout. The frame has been resized several ways.

Figure 12-1: FlowLayout resized

To use FlowLayout, follow these steps:

1. Set the layout of the container using the setLayout(LayoutManager mgr) method inherited from Container.

2. Add the components using the add(Component comp) method, also inherited from Container, as follows:

class FlowLayoutStuff extends JFrame { JButton b1 = new JButton("Button 1"); JButton b2 = new JButton("Button 2"); JButton b3 = new JButton("Button 3"); FlowLayoutStuff() { setupGUI(); } private void setupGUI() { Container c = getContentPane(); c.setLayout(new FlowLayout()); // Set the layout // before adding the c.add(b1); // components. c.add(b2); // Notice that you do not c.add(b3); // need a reference to the setSize(200,100); // FlowLayout object. This setVisible(true); // is typical. } }

FlowLayout

A Java layout

manager that adds

components

centered on each

line, top to bottom,

in a flowing manner

similar to the layout

of HTML pages.

Page 195: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 12: Layout Managers 12-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Your output should resemble Figure 12-2.

Figure 12-2: Output of FlowLayoutStuff

GridLayout GridLayout, as you might expect, is a layout based on a grid-like format. The constructor to the GridLayout class requires the number of rows and columns necessary to form the grid. Following are some important points about GridLayout:

• Components are automatically added from left to right and top to bottom.

• Component size is entirely controlled by the grid.

• If you add more components than will fit, another row will automatically be added.

In the following code, you will create a GridLayout that has two rows and three columns:

class GridLayoutStuff extends JFrame { JButton b1 = new JButton("Button 1"); JButton b2 = new JButton("Button 2"); JButton b3 = new JButton("Button 3"); JButton b4 = new JButton("Button 4"); JButton b5 = new JButton("Button 5"); JButton b6 = new JButton("Button 6"); GridLayoutStuff() { setupGUI(); } private void setupGUI() { Container c = getContentPane(); c.setLayout(new GridLayout(2,3)); c.add(b1); c.add(b2); c.add(b3); c.add(b4); c.add(b5);

GridLayout

A Java layout

manager that adds

components in a

grid-like format.

Page 196: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

12-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

c.add(b6); setSize(200,100); setVisible(true); } }

Your output should resemble Figure 12-3.

Figure 12-3: Output of GridLayoutStuff

BorderLayout BorderLayout is an unusual but useful layout. In this case, the layout is divided into five regions, as shown in Figure 12-4.

CENTER

EAST

WEST

SOUTH

NORTH

Figure 12-4: Example of BorderLayout regions

When you add components, you must specify the region in which the component is to appear. To set a BorderLayout and add a button called myButton to the west region, enter the following code:

c.setLayout(new BorderLayout()); c.add(BorderLayout.WEST, myButton);

Following are some important points about BorderLayout:

• You can add only one component to any one area. If you add more than one, you will only see the last one added.

BorderLayout

A Java layout

manager that adds

components in

specified regions.

Page 197: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 12: Layout Managers 12-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

• The west and east regions give the added component its preferred width, but will change the component height.

• The north and south regions give the added component its preferred height, but will change the component width.

• The JFrame is, by default, already set to BorderLayout. However, you should always explicitly set a layout manager, instead of assuming one. Study the following code:

class BorderLayoutStuff extends JFrame { JButton b1 = new JButton("Button 1"); JButton b2 = new JButton("Button 2"); JButton b3 = new JButton("Button 3"); JButton b4 = new JButton("Button 4"); JButton b5 = new JButton("Button 5"); BorderLayoutStuff() { setupGUI(); } private void setupGUI() { Container c = getContentPane(); c.setLayout(new BorderLayout()); c.add("North",b1); c.add("East", b2); c.add("South", b3); c.add("West",b4); c.add("Center",b5); setSize(300,300); setVisible(true); } }

Your output should resemble Figure 12-5.

Figure 12-5: Output of BorderLayoutStuff

Page 198: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

12-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

BoxLayout BoxLayout is similar to FlowLayout. The difference is that BoxLayout allows either a horizontal or a vertical layout of components. In the following basic example, you will create two JPanels and populate them with JButtons to demonstrate the BoxLayout:

class BoxLayoutStuff extends JFrame { JPanel horizPanel = new JPanel(); JPanel vertPanel = new JPanel(); JButton b1 = new JButton("b1"); JButton b2 = new JButton("b2"); JButton b3 = new JButton("b3"); JButton b4 = new JButton("b4"); JButton b5 = new JButton("b5"); JButton b6 = new JButton("b6"); BoxLayoutStuff() { setupGUI(); } private void setupGUI() { Container c = getContentPane(); c.setLayout(new GridLayout(1,2)); horizPanel.setLayout (new BoxLayout(horizPanel,BoxLayout.X_AXIS)); vertPanel.setLayout (new BoxLayout(vertPanel,BoxLayout.Y_AXIS)); horizPanel.add(b1); horizPanel.add(b2); horizPanel.add(b3); vertPanel.add(b4); vertPanel.add(b5); vertPanel.add(b6); c.add(horizPanel); c.add(vertPanel); setSize(400,150); setVisible(true); } }

Your output should resemble Figure 12-6.

Horizontal BoxLayout

Vertical BoxLayout

Figure 12-6: Output of BoxLayoutStuff

BoxLayout

A Java layout

manager that adds

components

horizontally or

vertically.

Page 199: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 12: Layout Managers 12-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Swing introduces a new component called Box. This component is simply a container with the BoxLayout already set. However, it offers some useful methods and two useful components: strut and glue.

Strut

A strut is an invisible component that allows you to add either horizontal or vertical (fixed) spacing to your layouts. You can create a strut by using a factory method of the Box class. For example, you could create a horizontal and a vertical strut, each 15 pixels in width and height, as follows:

Component hStrut = Box.createHorizontalStrut(15); Component vStrut = Box.createVerticalStrut(15);

Add these components to your layout as usual to achieve the desired effect. Notice the slight modification to the code regarding struts; this approach is more typical:

class BoxLayoutStuff extends JFrame { JPanel horizPanel = new JPanel(); JPanel vertPanel = new JPanel(); JButton b1 = new JButton("b1"); JButton b2 = new JButton("b2"); JButton b3 = new JButton("b3"); JButton b4 = new JButton("b4"); JButton b5 = new JButton("b5"); JButton b6 = new JButton("b6"); BoxLayoutStuff() { setupGUI(); } private void setupGUI() { Container c = getContentPane(); c.setLayout(new GridLayout(1,2)); horizPanel.setLayout (new BoxLayout(horizPanel,BoxLayout.X_AXIS)); vertPanel.setLayout (new BoxLayout(vertPanel,BoxLayout.Y_AXIS)); horizPanel.add(b1); horizPanel.add(Box.createHorizontalStrut(15)); horizPanel.add(b2); horizPanel.add(Box.createHorizontalStrut(15)); horizPanel.add(b3); vertPanel.add(b4); vertPanel.add(Box.createVerticalStrut(15)); vertPanel.add(b5); vertPanel.add(Box.createVerticalStrut(15)); vertPanel.add(b6); c.add(horizPanel); c.add(vertPanel);

strut

An invisible Swing

component that

creates fixed-sized

horizontal or vertical

space in a

container.

Page 200: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

12-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

setSize(400,150); setVisible(true); } }

Your output should resemble Figure 12-7.

Horizontalstruts

Vertical struts

Figure 12-7: Output of BoxLayoutStuff with struts

Glue

A glue component allows you to control the positions of other fixed-size components in your layout. This invisible component expands to absorb extra space in the container. Glue components will consume as much horizontal or vertical space as possible. You can create horizontal and vertical glue components by using factory methods of the Box class:

Component hGlue = Box.createHorizontalGlue(); Component vGlue = Box.createVerticalGlue();

Add these components to your layout as usual, and note the effects:

class BoxLayoutStuff extends JFrame { JPanel horizPanel = new JPanel(); JPanel vertPanel = new JPanel(); JButton b1 = new JButton("b1"); JButton b2 = new JButton("b2"); JButton b3 = new JButton("b3"); JButton b4 = new JButton("b4"); JButton b5 = new JButton("b5"); JButton b6 = new JButton("b6"); BoxLayoutStuff() { setupGUI(); } private void setupGUI() { Container c = getContentPane(); c.setLayout(new GridLayout(1,2)); horizPanel.setLayout

glue

An invisible Swing

component that

expands to

consume free

space in a

container.

Page 201: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 12: Layout Managers 12-13

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

(new BoxLayout(horizPanel,BoxLayout.X_AXIS)); vertPanel.setLayout (new BoxLayout(vertPanel,BoxLayout.Y_AXIS)); horizPanel.add(Box.createHorizontalGlue()); horizPanel.add(b1); horizPanel.add(b2); horizPanel.add(b3); vertPanel.add(Box.createVerticalGlue()); vertPanel.add(b4); vertPanel.add(b5); vertPanel.add(b6); c.add(horizPanel); c.add(vertPanel); setSize(400,150); setVisible(true); } }

Your output should resemble Figure 12-8.

Horizontalglue

Vertical glue

Figure 12-8: Output of BoxLayoutStuff with glue

Combining Layouts At this point, you should be wondering how to create the GUI you want given the apparent limitations of each of the layouts. Typically, you will not rely on a single layout manager but on a combination of layouts (referred to as nesting). You can combine your knowledge of the layout managers with the use of JPanels to achieve some fairly sophisticated results. As an example, try to duplicate the layout shown in Figure 12-9.

Button 4

Button 1

Button 2

Button 3

Figure 12-9: Example of a sophisticated layout

nesting

The use of

containers within

containers to

achieve

sophisticated

layouts.

Page 202: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

12-14 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Realistically, you can approach this task in more than one way. This layout strongly resembles a BorderLayout with three JButtons in the west region, and a fourth JButton in the center region. However, you know that if you add multiple JButtons in any one region, only the last JButton will be displayed. Therefore, you must further separate the problem. The west region resembles a GridLayout with three rows and one column. You can summarize the solution as follows:

1. Create a JFrame with a BorderLayout.

2. Create a JPanel with a GridLayout of three by one, and add three JButtons.

3. Add the JPanel to the west region.

4. Add the fourth JButton to the center region.

Study the following code:

class NestedLayoutStuff extends JFrame { JButton b1 = new JButton("Button 1"); JButton b2 = new JButton("Button 2"); JButton b3 = new JButton("Button 3"); JButton b4 = new JButton("Button 4"); JPanel west = new JPanel(); NestedLayoutStuff() { setupGUI(); } private void setupGUI() { Container c = getContentPane(); c.setLayout(new BorderLayout()); west.setLayout(new GridLayout(3,1)); west.add(b1); west.add(b2); // Add Buttons to the // JPanel west.add(b3); c.add(BorderLayout.WEST, west); // Add JPanel c.add(BorderLayout.CENTER,b4); setSize(250,150); setVisible(true); } }

Page 203: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 12: Layout Managers 12-15

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Your output should resemble Figure 12-10.

Figure 12-10: Output of NestedLayoutStuff

Other possibilities exist. Perhaps a BoxLayout in the west JPanel, or even a FlowLayout, would be more accommodating. You will find that layout managers offer you great flexibility and creativity. Remember to test your layouts under various conditions (such as different screen resolutions and operating systems).

Lab 12-1: Creating sophisticated layouts in Java

In this lab, you will create a sophisticated GUI. This GUI will serve as the front end for a painting program similar to the one in the Windows operating systems. You will develop this painting program over the next several lessons; the general form is provided here. You are strongly encouraged to experiment with layout techniques to find the most suitable solution.

Page 204: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

12-16 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

1. Create a GUI as shown in Figure 12-11. Ultimately, this GUI will become fully functional with the ability to draw in many predefined and user-defined colors. Note that this entire GUI consists of one JFrame, four JPanels, five JButtons, and three JScrollBars.

Five JButtons

Two JPanels The large (center) JPanel will serve as the drawing surface. The smaller JPanel (beneath the JButton) will always display the current drawing color.

Three JScrollBars Each JScrollBar will be able to select an integer from 0 to 255, ultimately to create a color based on an RGB value. Top: Red JScrollBar Middle: Green JScrollBar Bottom: Blue JScrollBar

JFrame

Figure 12-11: Sophisticated GUI model

2. (Optional) Change the background colors of the three JScrollBars to red, green and blue, respectively (their representative colors).

3. (Optional) Change the background colors of the red, green, blue and black JButtons to their representative colors.

4. (Optional) Change the background color of the small JPanel to black, which is the default drawing color in Java.

5. (Optional) Add three JLabels to the left of the three JScrollBars, labeling each JScrollBar with the color name it represents.

Page 205: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 12: Layout Managers 12-17

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Although they may seem somewhat awkward at first, Java's layout managers provide the flexibility to create sophisticated layouts. Identify two common applications that maintain GUIs. Using a pencil and paper, draw sketches of how each could be realized using the layout managers discussed in this lesson.

Skills review

In this lesson, you learned about the four most commonly used Java layout managers: FlowLayout, GridLayout, BorderLayout and BoxLayout. You learned to nest containers and layout managers to create more sophisticated designs, and you recreated a complex layout by studying its elements of design. Now that you know how to assemble containers and components into more complex graphical interfaces, you will learn how to place shapes, text and images onto a graphical component in the next lesson.

Now that you have completed this lesson, you should be able to:

� Define a layout manager.

� Set a layout manager for a container.

� Effectively use FlowLayout, GridLayout, BorderLayout and BoxLayout.

� Nest containers and layout managers to form more complex GUI layouts.

� Separate a complex design into its component containers and layout managers.

Page 206: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

12-18 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 12 Review

1. What is a layout manager?

_______________________________________________________________

_______________________________________________________________

2. Name at least three layout managers provided by the Java API.

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

3. What is FlowLayout?

_______________________________________________________________

_______________________________________________________________

4. What steps should you follow to use FlowLayout?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

5. What is a BoxLayout?

_______________________________________________________________

6. What is the purpose of the glue component?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 207: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

13Lesson 13:

Graphics in Java

Objectives By the end of this lesson, you will be able to:

� Identify the AWT class structure for graphics.

� Gain access to a container's graphic context by overriding the paint(Graphics g) method.

� Use methods of the Graphics class via the graphics context, including drawString and drawRect.

� Effectively use the Color and Font classes.

Page 208: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

13-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. Which of the following is true with respect to the Graphics class?

a. The Graphics class is abstract. b. The Graphics class is instantiated by a component prior to use. c. The Graphics class provides facilities for defining a color. d. The Graphics class extends a graphics context class.

2. Which of the following is true with respect to the paintComponent method?

a. When overriding the paintComponent method, it is not advisable to call super.paintComponent.

b. If the programmer wants to update a component, he or she should call the repaint method, rather than call the paintComponet method directly.

c. The paintComponent method does not accept any parameters. d. The paintComponent method provides facilities for drawing arcs,

lines, and polygons.

3. Describe the features of the Color class?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 209: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 13: Graphics in Java 13-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Graphics Class Java provides a rich set of classes to create graphics. In this lesson, you will study three classes in the AWT package that are useful for graphics: the Graphics class, the Color class, and the Font class.

The Graphics class is an abstract class. As a cross-platform language, Java cannot implement the necessary hard code to properly handle the many graphics systems available. For this reason, the individual Java Virtual Machine must implement this abstract class. As a Java programmer, you need not worry about the various implementations of the Graphics class if you adhere to the methods provided.

Considering that abstract classes cannot be instantiated, how can you access the functionality of the Graphics class when it is abstract? You must work with the graphics context, which is the AWT implementation of the many methods defined in the Graphics class. The graphics context is a wrapper for the surface upon which you want to draw. You never draw directly to the surface of a component; you draw to its graphics context, and the graphics context draws to the surface of the component.

You can access this graphics context in many ways. You can specifically request it from the AWT for the component or image with which you want to work. Usually, you will override a specific method depending on whether the component to which you want to paint is a subclass of JComponent or a subclass of Container alone. If the component to which you want to paint is a subclass of JComponent (JPanel, for example), then you can override the following method:

public void paintComponent(Graphics g) { super.paintComponent(g); // This will redraw the background color; otherwise your // component will be transparent, and might draw to the // component beneath it // Additional code for drawing }

Graphics

An abstract class

used to get a

graphics context of

a component or

image.

graphics context

The workable

representation of the Graphics class

for a component or

image.

paintComponent

(Graphics g)

A method inherited from JComponent

that is passed a

reference to the

graphics context of

that component.

Page 210: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

13-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

If the component to which you want to paint is a subclass of Container alone, then you can override the following method:

public void paint(Graphics g) { super.paint(g); // JFrame might have problems refreshing its onscreen image // without calling its super method first // Additional code to do some drawing... }

Figure 13-1 lists the many classes available in the AWT for creating graphics, as well as some of the methods made available in the Graphics class itself.

Color

O b j e c t

Cursor

Dimension

Font

FontMetrics

Graphics

Image

Insets

MediaTracker

Point

Polygon

Rectangle

Toolkit

Graphics Class Methods

Method Description

draw3DRect() Draws a 3-D rectangle

drawArc() Draws an arc

drawLine() Draws a line

drawOval() Draws an oval

drawPolygon() Draws a polygon connecting point to point

drawPolyline() Draws a line connecting point to point

drawRect() Draws a rectangle

drawRoundRect() Draws a rounded-corner rectangle

fill3DRect() Draws a filled 3-D rectangle

fillArc() Draws a filled arc

fillOval() Draws a filled oval

fillPolygon() Draws a filled polygon

fillRect() Draws a filled rectangle

fillRoundRect() Draws a filled rectangle with rounded corners

Abstract Class

Class

Figure 13-1: AWT class hierarchy (Graphics section)

Page 211: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 13: Graphics in Java 13-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Typically, when you want to create graphics (either text or shapes), you will override the paintComponent(Graphics g) method derived from JComponent. The coordinate system used to position graphics is contrary to the one taught in algebra classes, but it is consistent with computer graphics coordinates: The origin (0,0) begins at the upper-left corner of the system instead of the bottom-right corner, as illustrated in Figure 13-2.

(0,0)

(x,y)

Figure 13-2: Coordinate system for positioning graphics

You can perform the "Hello World" program graphically with the following code:

import java.awt.*; import java.awt.event.*; import java.awt.Window.*; import javax.swing.*; class PaintingStuff extends JPanel { PaintingStuff () { // empty } // The AWT passes the graphics // context of the frame as a // parameter to the paint method. public void paintComponent(Graphics g) { super.paintComponent(g); // Avoid transparency issues. g.setColor(Color.blue); // The foreground must be // different from the background, or you will not see // the result (we will discuss this topic shortly). g.drawString("Hello World",70,100); } }

Page 212: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

13-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Of course, you must add this JPanel to a JFrame. For example:

import java.awt.*; import java.awt.event.*; import java.awt.Window.*; import javax.swing.*; class StartPaintingStuff extends JFrame { PaintingStuff pStuff = new PaintingStuff(); StartPaintingStuff() { setupGUI(); } private void setupGUI() { Container c = getContentPane(); c.setLayout(new BorderLayout()); c.add(BorderLayout.CENTER,pStuff); setSize(200,200); setVisible(true); } }

Your output should resemble Figure 13-3.

Figure 13-3: Output of PaintingStuff

Page 213: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 13: Graphics in Java 13-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Overriding paintComponent(Graphics g) is usually the preferred method for accessing the graphics context of a JComponent; remember that for a JFrame, the method is paint(Graphics g). Sometimes programmers will try to capture the graphics context used elsewhere in their code by using an inherited method of Component called getGraphics. This way, the programmer is not forced to remain in the specific inherited method.

This technique can be problematic. The graphics context is generated by the AWT spontaneously. Maintaining a reference to it may cause problems later. If you use this technique, be sure to obtain a fresh reference to the graphics context each time you use it. For example, you could run the "Hello World" program without committing to overriding a specific method as follows:

import java.awt.*; import java.awt.event.*; import java.awt.Window.*; import javax.swing.*; class PaintingStuff extends JPanel { PaintingStuff () { // empty } // The AWT passes the graphics // context of the frame as a // parameter to the paint method. private void drawSomething() { Graphics g = getGraphics(); // Request the Graphics // context. g.setColor(Color.red); g.drawString("Hello World",70,100); } }

Page 214: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

13-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The drawSomething method can be invoked as follows:

import java.awt.*; import java.awt.event.*; import java.awt.Window.*; import javax.swing.*; class StartPaintingStuff extends JFrame { PaintingStuff pStuff = new PaintingStuff(); StartPaintingStuff() { setupGUI(); pStuff.drawSomething(); } private void setupGUI() { Container c = getContentPane(); c.setLayout(new BorderLayout()); c.add(BorderLayout.CENTER,pStuff); setSize(200,200); setVisible(true); } }

The result is identical to the previous example; the only difference is the manner in which the graphics context was obtained.

One surprising aspect is the frequency with which the AWT calls the paintComponent(Graphics g) method. Each time you drag, resize, cover or uncover some part of a window, the AWT will update its graphics context and automatically call the paintComponent(Graphics g) method. The paintComponent(Graphics g) method should contain all the code to redraw the entire component. You may also force the AWT to call paintComponent(Graphics g) if data affecting the output of your program has changed. In this case, a call to repaint will force the AWT to call the component's paintComponent(Graphics g) method. The repaint method performs some updating, but ultimately calls the paintComponent(Graphics g) or the paint(Graphics g) method.

Once you have a current reference to the graphics context, you need to become comfortable with all the methods available in the Graphics class. For example, if you want to draw a rectangle around the text, you can implement one of the methods available to the Graphics class (such as the drawRect method).

import java.awt.*; import java.awt.event.*; import java.awt.Window.*; import javax.swing.*;

repaint

A method of Component that is

used to indirectly

call paintComponent

for a graphics

update.

drawRect

A method of the Graphics class that

draws a rectangle.

Page 215: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 13: Graphics in Java 13-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

class PaintingStuff extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.blue); g.drawString("Hello World",70,100); g.drawRect(50,50,100,100); } }

Your output should resemble Figure 13-4.

Figure 13-4: Output of PaintingStuff with rectangle

Color Class It may seem odd that a color would require a class, but if you consider color from the perspective of object-oriented programming, it makes sense. You may want to determine a color as an RGB value: Color(int R, int G, int B). You may want to specify a number between 0 and 2563 – 1 (16.7 million colors): Color(234222). You may want to simply specify the color: Color.red. Or you may want to adjust the brightness of a color: Color.brighter. As you can see, something as seemingly simple as color can fit nicely into the framework of an object.

The Color object may be readily used to change the current color of the graphics context (which is black by default). The following code demonstrates three ways to set the color of the graphics context using the setColor method of the Graphics class and a properly created Color object.

public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.red); // M1 – using a constant. g.setColor(new Color(255,0,0)); // M2 – using a constructor. g.setColor(new Color(256*256*255)); // M3 – using a constructor. }

Color

A class of the AWT

that represents

colors.

setColor

An overloaded

method of the

Graphics class that

establishes the

current color of the

graphics context.

Page 216: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

13-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Study the following code:

import java.awt.*; import java.awt.event.*; import java.awt.Window.*; import javax.swing.*; class PaintingStuff extends JPanel

{ public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.red); // M1 g.drawString("Hello World",70,100); g.setColor(new Color(200,100,200)); // M2 g.drawRect(50,50,100,100); } }

Your output should resemble Figure 13-5.

Figure 13-5: Output of PaintingStuff with colors

Font Class The Font class, also available in Java, functions similarly to the Color class. Because a Font is defined by its name (Helvetica, Times Roman, and so forth), its style (bold, italic) and its size (e.g., 14 point), you can infer that the constructor of a Font object also requires a name, a style, and a size, as shown:

public void paintComponent(Graphics g) { super.paintComponent(g); g.setFont(new Font("Helvetica", Font.BOLD, 15)); }

Font

A class of the AWT

that represents

fonts.

Page 217: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 13: Graphics in Java 13-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

As is often the case with Java, you must consider how a Font object translates from one system to another. To successfully cross platforms, Java makes the following font types available to any JVM:

• Serif

• SansSerif

• Monospaced

• Dialog

• DialogInput

You are not limited to the aforementioned Font types; the Toolkit class contains a method that will retrieve all the fonts available to the system (consult Java in a Nutshell or the Java 2 API for further details).

The final modification to your practice code will set a font:

import java.awt.*; import java.awt.event.*; import java.awt.Window.*; import javax.swing.*; class PaintingStuff extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.red); g.setFont(new Font("Serif", Font.BOLD + Font.ITALIC, 20)); g.drawString("Hello World",70,100); g.setColor(new Color(200,100,200)); g.drawRect(50,50,100,100); } }

Page 218: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

13-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Your output should resemble Figure 13-6.

Figure 13-6: Output of PaintingStuff with fonts

Lab 13-1: Drawing to a JFrame

In this lab, you will draw to the surface of your JFrame by overriding the appropriate method. Interestingly, you are drawing to the surface of the JFrame, not the JPanel. How do you see the result if the JPanel is on top of the JFrame? In Swing, components are transparent by default. In effect, you see through the JPanel to the surface of the JFrame, as shown in Figure 13-7.

Your red rectangleshould appear here

Page 219: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 13: Graphics in Java 13-13

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Figure 13-7: JFrame model

1. Draw a filled red rectangle in the top center of the JFrame by overriding the appropriate method to obtain a reference to the graphics context.

2. (Optional) Add 3-D borders to your red rectangle by using the Graphics method of draw3DRect(int x1,int y1,int width, int height, boolean raised). Try to achieve the visual effect of a raised button.

3. (Optional) Adjust the fonts on the JButtons to make them aesthetically appealing.

Page 220: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

13-14 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

You may have noticed that graphics programming demonstrates the benefits of object-oriented programming, and inheritance in particular. When you define a class that extends a Swing class, you are reusing the Swing class's functionality to create your own graphical component. The parent class offers a number of features, such as the common interface that allows a component to be placed within a container, and your class overrides methods to provide unique functionality. Consider the examples in this lesson. Many of the classes extend the JPanel class and override the paintComponent method to provide unique functionality. These classes benefit from reusing much of the code that has already been written within the JPanel class. Review the Swing/AWT class diagram depicted in Figure 11-1. Notice that all of the common Swing components use inheritance. Each of these components is built using the same principles of code reuse and method overriding used in this lesson. Create a list of at least five proprietary components that could be built by inheriting from one of the Swing classes.

Skills review

In this lesson, you learned about some of the techniques used to obtain the graphics context of a component, as well as some of the methods of the Graphics class. You also learned about the Color and Font classes. Additionally, the Cursor class works similarly to Color and Font. The ideas discussed in this lesson create the visual aspects of a Java program, but so far, the graphical interface does not react to the mouse or keyboard.

Now that you have completed this lesson, you should be able to:

� Identify the AWT class structure for graphics.

� Gain access to a container's graphic context by overriding the paint(Graphics g) method.

� Use methods of the Graphics class via the graphics context, including drawString and drawRect.

� Effectively use the Color and Font classes.

Page 221: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 13: Graphics in Java 13-15

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 13 Review

1. Java is a cross-platform language. How does it properly handle the many graphics systems available?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

2. What is the graphics context?

_______________________________________________________________

_______________________________________________________________

3. What is usually the preferred method for accessing the graphics context of a JComponent?

_______________________________________________________________

4. What is the purpose of the repaint method?

_______________________________________________________________

_______________________________________________________________

5. What is the purpose of the setColor method?

_______________________________________________________________

_______________________________________________________________

Page 222: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

13-16 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 223: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

14Lesson 14:

The Event Delegation

Model

Objectives By the end of this lesson, you will be able to:

� Describe the event delegation model.

� Create listener classes that can respond to events.

� Register listener classes with their Component sources.

� Capture events and deal with them in meaningful ways.

Page 224: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

14-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. Which of the following components can generate a MouseEvent?

a. JComponent b. JCheckbox c. JTextComponent d. All of the above.

2. Which of the following components can generate an ItemEvent?

a. JComponent b. JCheckbox c. JTextComponent d. All of the above.

3. Describe the purpose of a listener interface.

_______________________________________________________________

_______________________________________________________________

Page 225: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 14: The Event Delegation Model 14-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

What Is an Event? An event can be described as something that happened or occurred. This definition, though basic, is appropriate. To describe an occurrence relative to Java, you must ask some questions:

• What caused the event? Was it a JButton, a JTextField, or a keystroke?

• What was the exact nature of the event? Was a JButton pressed, or was it released? Was a mouse clicked once, or was it double-clicked?

• Is additional information available about the event? If a mouse button was clicked, where was it clicked (the coordinates)? If a key on the keyboard was pressed, was it in conjunction with the CTRL key or the ALT key?

Based on these questions, you can surmise that when an event occurs in Java, Java (being an object-oriented language) creates an event object. This event object contains all the information you need to properly process the event:

• The source of the event (the Component that generated it).

• The ID of the event (e.g., a mouse down or mouse up).

• Other important information based on the type of event (such as the label of the JButton that generated the event).

Event handling has one notable problem. Java supports three distinctly different event models: the JDK 1.0 model, the model introduced with JDK 1.1 (and still in place for SDK 1.2), and a third model that combines the two. This lesson will discuss the 1.0 model briefly and focus heavily on the JDK 1.1/SDK 1.2 model. We will ignore the third model because it is rarely used.

JDK 1.0 Event Handling The JDK 1.0 has been criticized because of the way in which it handles events. Although it was a relatively quick and easy way of implementing event handling, the JDK 1.0 event handling model had some serious drawbacks, including the following:

• JDK 1.0 was tightly coupled with the AWT. Event handling took place in a method called handleEvent inherited from Component.

• JDK 1.0 was inefficient. Events were turned loose, to be captured by any Component. The capturing Component was decided by a form of inheritance by containment

event

An occurrence or

happening.

event object

The informational

object Java creates

in response to an

event.

source

The Component that

generates the event

object.

ID

A way of

distinguishing the

type of event

generated.

handleEvent

The method most

widely used in the

JDK 1.0 to handle

event processing.

Page 226: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

14-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

• JDK 1.0 was too general. Only one type of event object was generated (an object of type Event), whether a Button generated the event or a key.

• JDK 1.0 was unruly. Because almost all event handling was performed in the handleEvent method, this method could grow to be very large and difficult to maintain.

• Code and event handling could not be separated. Any event handling code had to be implemented as part of your program code. This requirement made scalability nearly impossible.

The JDK 1.0 event model has been deprecated (that is, declared to be obsolete, although old code continues to be supported). It is still supported because some browsers do not support the JDK 1.1/SDK 1.2 model. The current releases of all major browsers support the new event handling model that you will study in this lesson.

SDK 1.2 Event Handling The JDK 1.1 model was an advance in elegance, scalability and efficiency over the 1.0 method. This remains unchanged in SDK 1.2. The JDK 1.1/SDK 1.2 model is based on a concept called the event delegation model.

Although the enhanced event delegation model was

introduced in JDK 1.1, this book will refer to it as belonging

to the SDK 1.2.

The event delegation model relies on the concept of event sources (objects that generate events—often Components) and event listeners (objects that receive Events). The following questions must be addressed in relation to the event delegation model:

• How does the event source generate the Event object?

• How does the event source know where to send the Event object?

• How does a listener prepare to receive the Event?

• What does the listener do once the Event is received?

The following sections will address these steps systematically.

event delegation

model

The event handling

model used in JDK

1.1 and SDK 1.2.

listeners

Classes that listen

for, and usually

process, the events

generated by an

event source. Such

classes will

implement an

appropriate listener

interface.

Page 227: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 14: The Event Delegation Model 14-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Generating the event object

An event object is generated automatically by an action such as a user moving the mouse or clicking a button. Although you have the ability to generate your own events, you need not generate events for standard AWT components (although this is done frequently with JavaBeans).

As mentioned earlier, one disadvantage of the 1.0 model was that the event object generated was too general (only one type of object, Event, was generated). The 1.2 model takes a different approach. The 1.2 model generates many different types of events depending on the source. For example, a Window generates a WindowEvent, and a JCheckboxMenuItem generates an ItemEvent. Some less obvious examples are JButton and JTextField, which generate an ActionEvent.

Once you know which sources generate which events, how does the source know where to send the event object so it can get the proper response?

Sending the event object to the listener

The event object that the source object creates must be sent to a listener object. How does it know which listener to send the event object to? What if more than one listener is available? The source must register the listener to which it wants to send the event object. This arrangement is common and can be demonstrated with everyday events.

If you (the listener) want to receive a subscription to Time magazine (the event object) from the publisher (the event source), what would you do? You would ask the publisher to put you on its mailing list (register yourself with the source). Then, when the publisher releases the next issue of Time magazine, you automatically receive a copy. Java handles its process the same way.

The difference in this analogy is the level of strictness with which Java adheres to this relationship. The publisher of Time magazine will send the magazine to anyone who pays. Java is not so liberal. Event sources can send event objects only to listeners that have been specifically designed to receive those events. Therefore, when you design a listener object, you must design it in preparation to receive event objects of a specific type.

Preparing the listener to receive the event

The class designed to receive the event object must adhere to a specific contract. How do you establish this contract? You can use interfaces. Recall that an interface is a contract between the interface and the class which implements that interface and the methods that must be implemented by the class.

Consider all that you have learned for the next example.

Page 228: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

14-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Example: Creating a closeable JFrame

You may have noticed that when you create a JFrame, it does not close the application but rather the JFrame itself. You will now remedy this situation.

What is the source of the event?

If you want to close a JFrame, and a JFrame is a type of Window, then your source is a Window object.

What type of event object is generated?

You can probably guess the event object type, but for now consult Figure 14-2 (at the end of this lesson) or any good API. According to this diagram, Window objects create events of type WindowEvent.

What object types are capable of receiving WindowEvents?

According to Figure 14-2, objects that implement the WindowListener interface are able to receive WindowEvent objects.

Now you have all the information needed to design the listener class. Study the following code:

import java.awt.*; import java.awt.Window.*; import java.awt.event.*; import javax.swing.*; public class MyWindowListener implements WindowListener { public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { Window w = (Window)e.getSource(); // Step 1 w.setVisible(false); // Step 2 w.dispose(); // Step 3 System.exit(0); // Step 4 } public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} }

WindowListener

One of many

interfaces that allow

an object to receive

certain events.

Page 229: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 14: The Event Delegation Model 14-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Some items in the preceding code should be noted:

• The implementation of the interface forces you to implement all the methods of that interface, even if they do nothing.

• The steps discussed previously provide an accepted way to close your window and application:

— Step 1—Window w = (Window)e.getSource(): One piece of information contained in every event object is the source of the Event (the JFrame object reference itself). Because a JFrame is a Window (by inheritance), you must cast the variable w as such. The WindowEvent type also contains a method called getWindow, which returns a variable of type Window (requiring no casting).

— Step 2—setVisible(false): The current JFrame is visible. This step visually removes the JFrame from the screen.

— Step 3—dispose(): Although the JFrame is no longer visually displayed, it is still a reference within the JVM. This step removes the reference from the JVM.

— Step 4—System.exit(0): This step shuts down the JVM. Be sure this outcome is the one you want.

Although you have created a listener that will properly respond to a WindowEvent, you still need to register this class with the source.

Now create a simple JFrame called CloseableJFrame that you will make visible so you can close it with your listener class. In the following code, notice the use of the public static void main(String[] args) to instantiate itself. This technique is common:

import java.awt.*; import java.awt.Window.*; import java.awt.event.*; import javax.swing.*;

public class CloseableJFrame extends JFrame { CloseableJFrame () { setSize(200,200); setVisible(true); }

public static void main(String[] args) { CloseableJFrame cjf = new CloseableJFrame (); } }

Page 230: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

14-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Now that you have a simple JFrame to display, you must register the event listener class to the CloseableJFrame class (the source). Notice the method used to register the listener. This convention is used each time you add a listener. If you were to register a listener class that was designed to handle events of type ItemEvent, the class would have to implement the ItemListener interface. The method to actually register the listener (in the source) would be called addItemListener. Study the following code:

import java.awt.*; import java.awt.Window.*; import java.awt.event.*; import javax.swing.*; public class CloseableJFrame extends JFrame { MyWindowListener myWindowListener; CloseableJFrame () { setupGUI(); } public static void main(String[] args) { CloseableJFrame cjf = new CloseableJFrame (); } private void setupGUI() { myWindowListener = new MyWindowListener(); addWindowListener(myWindowListener); setSize(200,200); setVisible(true); } }

Summary of the event handling process

1. Determine the source of the Event. Is it a Window or a Button?

2. Determine the type of event the source Component will generate. If the source is a Button, then an API will tell you that it generates an ActionEvent. Note the type of listener the addSomeListener requires. In the case of a Button, the API will tell you that Button has a method called addActionListener, which means that it generates an ActionEvent.

3. Determine the type of listener class that must be created. Again, in the case of a Button, it requires a listener of type ActionListener because it generates an ActionEvent.

addItemListener

One of a series of

methods that

register a listener

object with its

source; this method

is always of the form

addSomeListener.

Page 231: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 14: The Event Delegation Model 14-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

4. Create a listener class that implements the appropriate listener. Implement all methods of the interface. Make the necessary method(s) truly functional.

5. Register an instance of the listener class from the source using the appropriate addSomeListener method.

JFrame convenience methods for event handling

You might have noticed that the JFrames you created were able to close by default (although not to the point of closing the JVM). This default feature of JFrame is new to Swing.

To set some default closing operation on a JFrame without implementing a listener class, use the JFrame method of setDefaultCloseOperation(int mode). The three modes are demonstrated as follows:

class CloseableJFrame extends JFrame { CloseableJFrame () { setupGUI(); } private void setupGUI() { // You would not set all three modes // at the same time in your own code. // 1. Hide and remove the JFrame reference from memory. setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 2. Do not hide or close at all. setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // 3. Simply hide the JFrame. This is the default mode. setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); setSize(200,200); setVisible(true); } }

Page 232: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

14-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Example: Event handling and callbacks

To further the development of the event model, consider another scenario. Suppose you need to modify something in the source class (or interface) from the listener class. This situation is common, and it relates directly to a concept discussed earlier regarding callbacks. For the listener class to modify any of the components from the source, the listener class needs a reference to the component.

In this example, you have two JButtons and a JTextArea. Ultimately, a message will pop up in the JTextArea when a JButton is clicked. Start with the basic framework. The interface is shown in Figure 14-1. When a user clicks a button, you want a message to be displayed in the JTextArea. You must pass a reference for this JTextArea to the EventListener class.

Figure 14-1: Interface with JButtons and JTextArea

import java.awt.*; import java.awt.Window.*; import java.awt.event.*; import javax.swing.*; // This is the frame with the JButton and JTextField. // As shown here, it will only display a message // to the command line when the JButton is clicked. // You will put both classes on the same page. public class CloseableJFrame extends JFrame { JButton top = new JButton("Say Hello"); JButton bottom = new JButton("Say Goodbye"); JTextArea textArea = new JTextArea(15,30); MyJButtonListener myJButtonListener; CloseableJFrame () { setupGUI(); }

Page 233: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 14: The Event Delegation Model 14-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

public static void main(String[] args) { CloseableJFrame cjf = new CloseableJFrame (); } private void setupGUI() { Container c = getContentPane(); c.add(BorderLayout.NORTH, top); c.add(BorderLayout.SOUTH, bottom); c.add(BorderLayout.CENTER, textArea); myJButtonListener = new MyJButtonListener(); top.addActionListener(myJButtonListener); bottom.addActionListener(myJButtonListener); setSize(300,300); setVisible(true); } } class MyJButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { // Notice how you can distinguish one button from // another by examining the JButton label. if(e.getActionCommand().equals("Say Hello")) { System.out.println("Hello"); } else if(e.getActionCommand().equals("Say Goodbye")) { System.out.println("Goodbye"); } } }

Although this program responds to your JButtons, it does not yet meet your objective, which is to display the messages back in the JTextArea. How can you obtain a reference to the JTextArea from the listener object? The key is that you pass a reference to the listener object via its constructor.

In the original code, you added the ActionListener as follows:

myJButtonListener = new MyJButtonListener(); top.addActionListener(myJButtonListener); bottom.addActionListener(myJButtonListener);

Page 234: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

14-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Now that you want to pass a reference to the MyJButtonListener, you can modify the preceding code as follows:

myJButtonListener = new MyJButtonListener(textArea); top.addActionListener(myJButtonListener); bottom.addActionListener(myJButtonListener);

Of course, by passing a reference of type JTextArea to MyJButtonListener, you need an appropriate constructor to receive textArea. The new and complete MyJButtonListener is:

import java.awt.*; import java.awt.Window.*; import java.awt.event.*; import javax.swing.*; class MyJButtonListener implements ActionListener { JTextArea textArea; MyJButtonListener(JTextArea tmpTextArea) { textArea = tmpTextArea; } public void actionPerformed(ActionEvent e) { // Notice how you can distinguish one button from // another by examining the JButton label. if(e.getActionCommand().equals("Say Hello")) { textArea.append("Hello \n"); } else if(e.getActionCommand().equals("Say Goodbye")) { textArea.append("Goodbye \n"); } } }

Although this process seems to handle additional work, the code can grow and become unmanageable when you need callbacks to several components in your GUI. In this case, it may be better to simply pass a reference to the GUI itself (e.g., the CloseableJFrame class) and access the various components in that manner. For example:

myJButtonListener = new MyJButtonListener(this);

Page 235: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 14: The Event Delegation Model 14-13

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Now the MyJButtonListener class has a reference to the entire CloseableJFrame class.

You will learn that the SDK 1.2 model is very flexible and offers multiple options for handling each situation. In the next lesson, you will examine one of these options: the use of inner classes.

Lab 14-1: Implementing a WindowListener for event

handling in Java

In this lab, you will modify your drawing application so that closing the JFrame will also close the Java Virtual Machine.

1. Create a class called MyWindowHandler that implements the WindowListener interface. You must implement all the methods as prototyped in the interface. Be sure to override the appropriate method to invoke the necessary steps to close your application and the JVM.

2. Register an instance of the MyWindowHandler class with your drawing application (within your setupGUI method) so that closing your drawing application will also close the JVM.

3. Test your class system.

4. (Optional) Experiment with some of the additional methods made available in the WindowListener interface. Perhaps you can send a message to your command line alerting you when the various methods have been invoked.

5. (Optional) For a challenge, try changing the background color of the large JPanel (your drawing surface) to green when your application has been deiconified. Execute this change from within the MyWindowHandler class.

Page 236: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

14-14 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Figure 14-2 illustrates the relationships between components, event objects and interfaces.

ActionListener• actionPerformed()

AdjustmentListener• adjustmentValueChanged()

ContainerListener• componentAdded()• componentRemoved()

FocusListener• focusGained()• focusLost()

ItemListener• itemStateChanged()

KeyListener• keyPressed()• keyReleased()• keyTyped()

MouseListener• mouseClicked()• mouseEntered()• mouseExited()• mousePressed()• mouseReleased()

MouseMotionListener• mouseDragged()• mouseMoved()

WindowListener• windowActivated()• windowClosed()• windowClosing()• windowDeactivated()• windowDeiconified()• windowIconified()• windowOpened()

TextListener• textValueChanged()

ActionEvent

AdjustmentEvent

ContainerEvent

FocusEvent

ItemEvent

KeyEvent

MouseEvent

TextEvent

WindowEvent

JScrollbar

JButton/ JMenuItem/JList/ JTextField

Container

JComponent

JCheckbox/ JOptionJList/

JMenuItem

JComponent

JComponent

JTextComponent

Window

TheseComponents

generate theseEvent Objects

which are listened forby Objectsimplementing theseInterfaces

Figure 14-2: Sources and event types generated

Page 237: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 14: The Event Delegation Model 14-15

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

In this lesson you learned about the SDK 1.2 event handling model, as well as how to implement listener interfaces and register a class to receive event notifications. In Lab 14-1 you created a class named MyWindowHandler to handle the events generated by the Scribble class. It is not necessary to separate this functionality from the Scribble class. Indeed, the Scribble class could be written to act as its own event listener. Rewrite your solution to Lab 14-1 so that the Scribble class handles its own events.

Skills review

In this lesson, you learned about events and Java's models for event handling. You studied the event delegation model, and you stepped through its processes. You also learned that if an event listener is used by several different classes, then the event listener should exist as a separate class. In the next lesson, you will learn how to include the event listener directly into the class where it is used, when it is used in only one class.

Now that you have completed this lesson, you should be able to:

� Describe the event delegation model.

� Create listener classes that can respond to events.

� Register listener classes with their Component sources.

� Capture events and deal with them in meaningful ways.

Page 238: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

14-16 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 14 Review

1. What is an event in relation to Java?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

2. What is an event object?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

3. What is an event source?

_______________________________________________________________

4. What is an event ID?

_______________________________________________________________

_______________________________________________________________

5. What is the event delegation model?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

6. How is an event object generated?

_______________________________________________________________

_______________________________________________________________

Page 239: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 14: The Event Delegation Model 14-17

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

7. How does an event source determine where to send an event object?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

8. Can a listener class modify any of the components from the source? How?

_______________________________________________________________

_______________________________________________________________

9. When should an event listener exist as a separate class?

_______________________________________________________________

_______________________________________________________________

Page 240: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

14-18 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 241: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

15Lesson 15:

Inner Classes

Objectives By the end of this lesson, you will be able to:

� Define an inner class.

� Explain the advantages of inner classes over package-level classes in relation to event handling.

� Design and implement inner classes for event handling.

Page 242: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

15-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. Which of the following code segments properly defines an anonymous inner class?

a. public class MyClass { class anon {}; }

b. public class MyClass { public Object o = class {};

} c. public class MyClass

{ public static void main(String [] args) { Color c = new Color(255, 0, 0) { public String toString() { return "Red"; } }; } }

d. public class MyClass { public static void main(String [] args) { Color c = Color(255, 0, 0) { public String toString() { return "Red"; } }; } }

Page 243: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 15: Inner Classes 15-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

2. Which of the following is true with respect to inner classes?

a. An inner class always inherits from its enclosing class. b. An inner class may be defined anonymously if it does not explicitly

inherit from another class or implement an interface. c. An inner class must be defined within a class definition and outside a

method body. d. Any number of inner classes may be defined within a class.

3. What is the difference between a member inner class and an anonymous inner class?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 244: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

15-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

What Is an Inner Class? As their name suggests, inner classes are classes defined within other classes. This feature was not available with the JDK 1.0; it was introduced with the SDK 1.2. Inner classes are one of the most significant changes to the SDK model.

Inner classes offer some conceptual advantages. For example, you might be designing a Body class (such as a human body). A body contains organs such as the heart and brain. Inner classes allow you to visualize this idea easily. For example:

class Body { class Heart { // Code } // Inner classes allow you to // conceptualize your constructs class Brain // in meaningful and highly { // encapsulated ways. // Code } }

Like many of the concepts in object-oriented programming, inner classes are appealing, but how are they useful?

Inner Classes for Event Handling Event handling is streamlined by inner classes. Recall the example in which clicking a JButton caused a message to display back in the JTextArea. To accomplish this, it was necessary to pass a reference to the JTextArea through the constructor. However, this process can become overly complicated as your needs grow. Inner classes can solve this problem.

Because inner classes are defined within a normal class (a class defined at the package level), inner classes follow the same scope access as curly braces. For example, if you define an inner class at the same curly-brace level as a method, then that inner class has the same scope as a method of that class. Therefore, in the example of your JButton sending a message to the JTextArea, if the MyJButtonListener class was defined as an inner class at the member level, it would be able to reference to the JTextArea.

inner class

A class defined

within the body of

another class.

Page 245: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 15: Inner Classes 15-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The modified code is as follows:

import java.awt.*; import java.awt.event.*; import java.awt.Window.*; import javax.swing.*; public class CloseableJFrame extends JFrame { JButton top = new JButton("Say Hello"); JButton bottom = new JButton("Say Goodbye"); JTextArea textArea = new JTextArea(15,30); MyJButtonListener myJButtonListener; CloseableJFrame() { setupGUI(); } public static void main(String[] args) { CloseableJFrame cjf = new CloseableJFrame(); } private void setupGUI() { Container c = getContentPane(); c.add(BorderLayout.NORTH, top); c.add(BorderLayout.SOUTH, bottom); c.add(BorderLayout.CENTER, textArea); myJButtonListener = new MyJButtonListener(); top.addActionListener(myJButtonListener); bottom.addActionListener(myJButtonListener); setSize(300,300); setVisible(true); }

// Inner class defined class MyJButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("Say Hello")) { textArea.append("Hello \n"); } else if(e.getActionCommand().equals ("Say Goodbye")) { textArea.append("Goodbye \n"); } } } // End inner class } // End CloseableJFrame

Page 246: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

15-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Note the immediate access that the inner class has to any of the instance variables of the outer class (the CloseableJFrame class).

The preceding example demonstrates one type of inner class: a member inner class, the one most commonly used. The other two types of inner classes have certain syntactical and functional differences, but for all practical purposes, they are equivalent. The following is an example of an anonymous inner class. An anonymous inner class is performed within the opening and closing parentheses of the listener registration method. Following is an example:

class AnonymousInnerClassStuff extends JFrame { JButton btn = new JButton("A JButton"); AnonymousInnerClassStuff() { setupGUI(); } private void setupGUI() { btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Code to respond to JButton being clicked... } });// End () and anonymous inner class. } }

How do inner classes represent themselves? If you were to find the compiled source for your CloseableJFrame.class, you would now find another file named CloseableJFrame$MyButtonListener.class. This file is the inner class.

member inner class

An inner class

defined at the same

scope as a method

or instance variable.

anonymous inner

class

An inner class

defined within the

parentheses of the

appropriate addItemListener

method.

Page 247: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 15: Inner Classes 15-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lab 15-1: Event-enabling your Java drawing

application

In this lab, you will event-enable the drawing application to fully implement all its features. Although you have learned several forms of event handling, you might find that using member inner classes is the best approach. Figure 15-1 shows the application and the JPanels with which you will be working.

This small JPanel is your "palette." It always displays the current drawing color.

This large JPanel is your "canvas," the surface upon which you will draw.

Figure 15-1: Drawing application

1. Event-enable the red, green, blue and black JButtons so that when they are clicked, the palette will change to the appropriate color.

2. Event-enable the three JScrollBars so that as they are dragged, a new Color object is constantly generated. The palette should always reflect the color represented by the state of the three JScrollBars.

Page 248: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

15-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

3. Event-enable your mouse so that when you press and hold the button, you will draw to the surface of the large JPanel (the canvas) in the current color of your palette.

Hint: You must implement two interfaces to trap the "mouse-pressed" and "mouse-dragged" events.

4. Event-enable the Erase JButton so that when it is clicked, the palette changes to the current background color of the drawing canvas. You can use your mouse to "erase" any previous drawings with this color.

5. (Optional) Modify Step 1 so that when the red, green, blue or black JButton is clicked, the JScrollBars automatically adjust to represent the proper RGB value.

6. (Optional) Consult your API to enable double-buffering for your palette. Once double-buffering is enabled, note any visual improvements to the performance of your palette.

Page 249: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 15: Inner Classes 15-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Anonymous inner classes are best used when a component has only one or a few events it must handle. Anonymous inner classes can then take responsibility for event delegation without the need for an entirely separate listener class. Instead, the entire anonymous class definition can be located within the definition for the component. Compose a paragraph describing where anonymous classes should be used and why they can be beneficial.

Skills review

In this lesson, you learned about inner classes and their roles in event handling. You also designed and implemented inner classes. Now that you can create graphical elements and make them react to events, you will learn how to combine all these elements into applets—the Java programs that run on the World Wide Web.

Now that you have completed this lesson, you should be able to:

� Define an inner class.

� Explain the advantages of inner classes over package-level classes in relation to event handling.

� Design and implement inner classes for event handling.

Page 250: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

15-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 15 Review

1. What conceptual advantage do inner classes offer for Java programming?

_______________________________________________________________

_______________________________________________________________

2. What advantages do inner classes offer for event handling in Java?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

3. What is a member inner class?

_______________________________________________________________

_______________________________________________________________

4. What is an anonymous inner class?

_______________________________________________________________

_______________________________________________________________

Page 251: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

16Lesson 16:

Java Applets

Objectives By the end of this lesson, you will be able to:

� Compare and contrast Java applets and applications.

� Implement the life cycle of an applet through its inherited methods.

� Embed an applet into an HTML document.

� Pass parameters from an HTML document to its contained applet.

� Identify applet security restrictions.

� Convert an applet into an application.

Page 252: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

16-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. Which of the following might an applet do when executing within a Web browser?

a. Execute code residing on the local machine b. Write to the hard drive on the local machine c. Open a network connection with a remote host d. Read from the hard drive on the local machine

2. Which of the following classes is not a parent class of a Java applet?

a. Object b. Component c. Container d. Window

3. What is a signed applet?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 253: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 16: Java Applets 16-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Programming Applets At the beginning of this course, you learned that Java programmers create either applications, servlets, or applets. Thus far, you have focused on applications. However, if you are comfortable with components, containers and event handling, you will find that programming applets poses only minor conceptual differences from programming applications.

Look at the AWT class hierarchy shown in Figure 16-1. Observe that JApplet (the parent class for all applets) extends Panel. The Applet class adds significant functionality to the Panel class. The difference is that applets always run inside a Web browser.

Object

Component

Applet

Panel

Container

JApplet

Figure 16-1: JApplet class hierarchy

Page 254: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

16-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Applets and Web Browsers The relationship between applets and browsers is a special one. Foreign code is trying to run in a browser (from any of various vendors), which is running on any of various operating systems. Therefore, rules are needed.

• Rule No. 1: An applet does not have a main method.

• Rule No. 2: An applet has a distinct life cycle by supporting the following method signatures:

public void init() public void start() public void stop() public void destroy()

• Rule No. 3: Applets are started from HTML pages, and they are able to receive information from these HTML pages.

• Rule No. 4: Because they are program code, applets should not be trusted. They should be limited in their ability to access system resources.

Consider compatibility when you use applets. Not all

browsers support the latest versions of Java. Sun JavaSoft

offers a plug-in to make your Web browser Java 2-

compliant. Visit www.javasoft.com/products/plugin/ to

download the plug-in. We will now explore the concepts associated with these applet rules.

An applet does not have a main method

Applets are Java classes in every sense of the word. If you were to create an applet, it would be declared as follows:

public class MyJApplet extends JApplet { // Code to write your applet }

Although this code represents a properly declared class, the code is different: A JApplet does not have a main method.

Remember that a JApplet is essentially a Panel (note the class hierarchy). And like a Panel, a JApplet cannot exist as a stand-alone application. The browser window must instantiate and display a JApplet, just as a JFrame must instantiate and display a JPanel.

Page 255: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 16: Java Applets 16-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

This requirement poses a problem. Although a JApplet is a Panel, you must still treat it as though it were an application. Fortunately, when the Panel class is extended, the JApplet class supplies significant functionality, most notably the addition of the init, start, stop and destroy methods.

An applet has a life cycle

Several methods are involved in the life cycle of an applet.

The init method is the first method called in an applet, and is often compared to the main method of an application or the constructor of a class. Initialization occurs here. Although an applet can have a default constructor, this method works best.

The start method is the second method called in an applet. The start method typically works in conjunction with the stop method. Whereas the init method is called only once in the lifetime of an applet, the start method might be called repeatedly. It is called when the applet gains focus. This may happen if the browser is minimized and then restored. It may happen if the user moves to another Web page and then comes back to the page containing the applet. Though this functionality may seem odd at first, if you are running processes in your applet that need not be running if the applet has lost focus, then you should be able to stop and later start these processes within the lifetime of your applet.

The stop method works in conjunction with the start method. For example, you may have started some type of animation in the start method. If the user navigates to another Web page, you should be respectful of your user's resources and stop the animation. If the user returns to your applet, you would then start the animation again. If you have no need to start and stop some functionality of your applet, you may never even use these methods.

The destroy method is called when the applet is removed from memory. It is difficult to predict exactly when the destroy method will be called because it varies from browser to browser, but it should be called after the final stop. Therefore, use it to release any system resources that may have been allocated. Such resources include a database connection, a thread, or an open stream.

The paint method could be considered one of the five essential methods when working with applets. Recall that the paint method is inherited from Container. Being a Panel, an applet also inherits this method. Typically, any Graphics drawn to the applet's graphics context will be performed by overriding the paint method.

With the exception of paint (which you can force to be called by invoking the repaint method), you have little control over how methods are called in an applet. Various actions occur transparently, under the control of the browser and the AWT. As long as you follow the rules guiding the life cycle of the applet, you should not encounter problems.

life cycle

The life of an applet

as controlled by the init, start, stop

and destroy

methods.

init

The first method

called in the life

cycle of an applet;

it resembles a

constructor.

start

The second method

called in the life

cycle of an applet.

destroy

The last method

called in the life

cycle of an applet;

should be used to

release system

resources.

stop

A method that

works in conjunction with start; should

be used to suspend

resource-draining

code.

paint

An inherited

method from Container that

allows painting to

the applet surface.

Page 256: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

16-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

You need not leave the life cycle of an applet undetermined. You can easily implement the methods of an applet's life cycle to test them, as shown:

import java.awt.*; import javax.swing.*;

public class AppletLifeCycleStuff extends JApplet { public void init() { System.out.println("init() method"); } public void start() { System.out.println("start() method"); } public void stop() { System.out.println("stop() method"); } public void destroy() { System.out.println("destroy() method"); } }

Applets and HTML pages

Applets are started from within an HTML page. To embed an applet into a Web page, some minimum requirements must be met. You must specify the HTML 3.2 <APPLET> tags. Within those tags, you must specify CODE, WIDTH and HEIGHT parameters. Suppose you write an applet called MyJApplet.class. You can embed it into a Web page as follows:

<HTML> <BODY> <APPLET CODE="MyJApplet.class" WIDTH=300 HEIGHT=200> </APPLET> </BODY> </HTML>

This HTML code will create an applet that resides in the current directory with a size of 300 by 200 pixels.

<APPLET>

HTML 3.2 tag used

to embed an

applet.

CODE

Required attribute

of <APPLET>,

needed to embed

an applet in an

HTML page;

specifies the name

of the applet class.

WIDTH/HEIGHT

Required attributes

of <APPLET>,

needed to embed

an applet in an

HTML page;

determines the size

of the applet.

Page 257: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 16: Java Applets 16-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Several attributes can be used within the <APPLET> tags, including CODEBASE, ALIGN, and ALT.

CODEBASE allows you to specify a directory relative to your current directory where you can store your *.class files (often images and class files will be arranged this way). ALIGN allows you to position the applet in the same manner that you would position an image in an HTML page (LEFT, RIGHT, BOTTOM, TOP, TEXTTOP, MIDDLE, ABSMIDDLE, BASELINE, ABSBOTTOM, VSPACE, HSPACE). ALT allows you to display a message to a user who has disabled Java on his or her browser. These options are demonstrated in the following code:

<HTML> <BODY> <APPLET CODEBASE = "Applet/Classes" CODE ="MyJApplet.class" WIDTH="300" HEIGHT="200" ALIGN="LEFT" ALT="Your Java feature has been disabled"> Your browser does not support Java. </APPLET> </BODY> </HTML>

In addition to implementing the optional tags, this code also accommodates those who may not have a Java-capable browser (which is rare) by adding the text between the <APPLET> tags. Only browsers that do not support Java or have Java disabled will see the message.

Passing parameters to applets

HTML pages can send information to an embedded applet by using parameter tags. Following is an example:

<HTML> <BODY> <APPLET CODE="MyJApplet.class" WIDTH=300 HEIGHT=200> <param name = "fontSize" value = "20"> <param name = "fontColor" value = "red"> </APPLET> </BODY> </HTML>

ALIGN

Optional attribute of

<APPLET>; specifies

the position of the

applet.

CODEBASE

Optional attribute of

<APPLET>; specifies

a relative directory

in which to save the

applet class.

ALT

Optional attribute of

<APPLET>; allows

you to display a

comment to a

Java-disabled

browser.

parameter tags

Optional

name/value tags

that send

information to an

applet from within

the HTML page.

Page 258: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

16-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Although any type of information can be passed, the Applet method used to retrieve the name/value pairs, getParameter, only returns a String. Therefore, you may have to write some additional code to properly use the received information. Following is the applet that will receive the previously discussed parameters. Notice the conversion from Strings to other data types:

public class MyJApplet extends JApplet { int fontSize; Color fontColor; String tmpFontColor; public void init() { fontSize = new Integer(getParameter("fontSize")). intValue(); tmpFontColor = getParameter("fontColor"); if(tmpFontColor.equals("red")) fontColor = Color.red; else if (tmpFontColor.equals("green")) fontColor = Color.green; else fontColor = Color.blue; repaint(); } public void paint(Graphics g) { g.setColor(fontColor); g.setFont(new Font("Courier",Font.BOLD, fontSize)); g.drawString("Java does it better!", 25,100); } }

Your output should resemble Figure 16-2.

Figure 16-2: Output of MyJApplet

getParameter

A method of Applet used to

obtain the

name/value pairs

sent by the HTML

page.

Page 259: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 16: Java Applets 16-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Applets should not be trusted

Applets have strict security limitations placed on them; these limitations present advantages and drawbacks.

Applet security is an advantage because an untrusted piece of code running on your computer does not have the freedom to perform malicious acts (such as deleting your hard drive contents or transferring your financial information over the Internet).

Applet security is a drawback because many common tasks performed with applications (such as accessing a file for writing) simply cannot be done with an applet.

Applets are said to live in a sandbox, which imposes the following security restrictions:

• Applets cannot run any executable code on the local machine.

• Applets can neither read nor write disk information from the local machine.

• An applet can establish a network connection only with the host from which it was downloaded.

• All windows that pop up from an applet have warning messages that alert users not to enter sensitive information.

It is important to realize that these security restrictions are not part of the Java language, but are imposed on the applet via the browser's setting of the SecurityManager. The SecurityManager class can be set with specific security restrictions within the browser. Each browser has different security restrictions. The Appletviewer supplied by the Sun SDK offers the same level of access for an applet as for an application. The Sun HotJava browser is also somewhat liberal, especially when compared to Netscape or Microsoft browsers. Although the security restrictions can be frustrating, alternatives do exist.

Since the introduction of the JDK 1.1, applets can be signed. A signed applet has a designation similar to a personal signature on it. Theoretically, if you were to download a signed applet from a trusted source, you could give it some level of unrestricted access to your computer, thus largely increasing the applet's level of functionality.

sandbox

The strict security

restrictions placed

on applets.

SecurityManager

A Java class used

by browsers to set

security restrictions

on an applet.

signed applet

A digitally signed

applet; if accepted

by the user, security

limitations are

reduced.

Page 260: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

16-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Methods inherited from the Applet class

The JApplet class adds many other methods to the Panel class to assist its functionality in a browser. Table 16-1 describes these methods.

Table 16-1: Methods inherited from the Applet class

Method Description

AppletContext getAppletContext()

Returns an AppletContext. This object provides several methods useful for interacting with the browser.

String getAppletInfo() Some applets override this method to display useful information to the user of the applet.

AudioClip getAudioClip() Returns an AudioClip object at a specified URL.

URL getCodeBase() Returns the URL that launched the applet.

URL getDocumentBase() Returns the URL of the HTML page that launched the applet.

Image getImage() Returns an Image at a specified URL.

String[] getParameterInfo()

Some applets display their parameter information as stored in an array.

Boolean isActive() Returns true or false depending on whether the applet is started or stopped.

Void play() Plays the AudioClip returned by getAudioClip().

Void resize() Resizes the applet.

Void showStatus() Displays a message in the status window of a browser (browser permitting).

Page 261: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 16: Java Applets 16-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Converting an Application into an

Applet You can convert an application into an applet, or an applet into an application. Turning an application into an applet is an easier, more natural transformation. In most cases, applying the following principles will be sufficient to make the conversion.

• Remember that the init method of an applet is similar to the main method in an application. Use it to perform any form of initialization or instantiation.

• You need not instantiate the applet; the Web browser will perform this action.

• Applications normally are derived from JFrame, whereas applets must be derived from JApplet.

• The size and visibility of the JFrame in an application is set within the application via the setSize and setVisible methods. The size of an applet should be set within the HTML document, while the Web browser makes it visible.

• Applets must be declared public.

Following is a simple GUI application, which you will convert into an applet:

import java.awt.*; import java.awt.Window.*; import java.awt.event.*; import javax.swing.*; class MyApplication extends JFrame { JButton north = new JButton("North"); JButton south = new JButton("South"); JButton east = new JButton("East"); JButton west = new JButton("West"); JTextArea textArea = new JTextArea(); MyApplication() { setUpGUI(); } public static void main(String[] args) { MyApplication m = new MyApplication(); } void setUpGUI() {

Page 262: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

16-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Container c = getContentPane(); c.setLayout(new BorderLayout()); c.add(BorderLayout.NORTH, north); c.add(BorderLayout.SOUTH, south); c.add(BorderLayout.EAST, east); c.add(BorderLayout.WEST, west); c.add(BorderLayout.CENTER"Center", new JScrollPane(textArea)); setSize(200,200); setVisible(true); } }

Your output should resemble Figure 16-3.

Figure 16-3: Output of MyApplication

Following is the same program written in applet form:

/* HTML code necessary to start the applet <HTML> <BODY> <APPLET CODE ="MyJApplet.class" WIDTH="200" HEIGHT="200"> </APPLET> </BODY> </HTML> */ public class MyJApplet extends JApplet { JButton north = new JButton("North"); JButton south = new JButton("South"); JButton east = new JButton("East"); JButton west = new JButton("West"); JTextArea textArea = new JTextArea(); public void init() { setUpGUI();

Page 263: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 16: Java Applets 16-13

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

} void setUpGUI() { Container c = getContentPane(); c.setLayout(new BorderLayout()); c.add(BorderLayout.NORTH, north); c.add(BorderLayout.SOUTH, south); c.add(BorderLayout.EAST, east); c.add(BorderLayout.WEST, west); c.add(BorderLayout.CENTER"Center", new JScrollPane(textArea)); } }

Your output should resemble Figure 16-4.

Figure 16-4: Output of MyJApplet after conversion from application

Converting an Applet into an

Application Remembering that an applet is a Panel, consider that an applet can be added to a JFrame so it can run as a stand-alone application. You can do this by adding a public static void main(String[] args) and a JFrame to the MyJApplet class. By adding an instance of the JApplet to the JFrame and calling its init and start methods, the conversion from JApplet to stand-alone JFrame readily takes place.

Page 264: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

16-14 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Because you are no longer receiving parameters from the HTML page, you must set some variables, as follows:

public class MyJApplet extends JApplet { int fontSize = 20; String tmpFontColor = "red"; Color fontColor;

public static void main(String args[]) { JFrame f = new JFrame(); MyJApplet myJApplet = new MyJApplet(); f.getContentPane().add(myJApplet); myJApplet.init(); myJApplet.start(); f.setSize(300,125); f.setVisible(true); }

public void init() {

if(tmpFontColor.equals("red")) fontColor = Color.red; else if (tmpFontColor.equals("green")) fontColor = Color.green; else fontColor = Color.blue;

repaint(); }

public void paint(Graphics g) { g.setColor(fontColor); g.setFont(new Font("Courier",Font.BOLD, fontSize)); g.drawString("Java does it better!", 25,50); g.drawString("(now an application)",25,75); } }

Your output should resemble Figure 16-5.

Figure 16-5: Output of MyJApplet after conversion to application

Page 265: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 16: Java Applets 16-15

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lab 16-1: Converting a Java application into an applet

The differences between applets and applications are subtle. Other than the inept security restrictions placed on an applet by its environment (typically a Web browser), application and applet development are virtually identical. In this lab, you will convert your drawing application into an applet. If you do not have a browser that supports the Swing components, you can either download the plug-in from Sun JavaSoft (at http://www.javasoft.com/products/plugin/) or use the Appletviewer that is included with the SDK 1.2.

1. Convert your drawing application into an applet. Keep the following points in mind:

• You must extend JApplet instead of JFrame.

• Although applets support a default constructor, you will probably want to substitute the role of the main method in your application with the init method of your applet.

• Applets should not be able to close the browser in which they are contained.

Page 266: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

16-16 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Java platform independence makes it an ideal solution for the Internet. The Internet connects computers using a variety of architectures and operating systems. Java allows you to create programs that will run on any machines with an available Java Virtual Machine. Locate five Web sites that host Java applets. Consider how the functionality of these applets is limited by the security restrictions imposed on applets.

Skills review

In this lesson, you learned the differences between Java applets and applications. You learned about the applet life cycle and some of its inherited methods. You also considered the security restrictions placed on applets, as well as some alternatives to those limitations. Finally, you converted an application into an applet and an applet into an application. Although the development of applets is an important part of the Java language, you will use many applications in this course because you know that they can easily be converted into applets. You will focus on more advanced topics, such as exceptions, threads, streams, and networking.

Now that you have completed this lesson, you should be able to:

� Compare and contrast Java applets and applications.

� Implement the life cycle of an applet through its inherited methods.

� Embed an applet into an HTML document.

� Pass parameters from an HTML document to its contained applet.

� Identify applet security restrictions.

� Convert an applet into an application.

Page 267: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 16: Java Applets 16-17

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 16 Review

1. What is an applet?

_______________________________________________________________

2. What are the four rules to remember regarding applets and Web browsers?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

3. What methods are involved in the applet life cycle?

_______________________________________________________________

_______________________________________________________________

4. What are parameter tags in relation to applets?

_______________________________________________________________

_______________________________________________________________

5. What does the term "sandbox" mean in relation to applets?

_______________________________________________________________

_______________________________________________________________

6. From what source are security restrictions imposed on Java applets?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 268: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

16-18 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

7. What is a signed applet?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

8. Can you convert an applet into an application? Can you convert an application into an applet?

_______________________________________________________________

_______________________________________________________________

Page 269: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

17Lesson 17:

Exceptions

Objectives By the end of this lesson, you will be able to:

� Differentiate between errors and exceptions.

� Differentiate between runtime exceptions and explicit exceptions.

� Propagate an exception using the throws statement.

� Handle an exception using the try/catch statement.

� Create and use a user-defined exception.

Page 270: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

17-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. What output is generated by the following Java code?

class MyException extends Exception {} public class MyClass { public static void myMethod() throws MyException { throw new MyException(); } public static void main(String [] args) { try { myMethod(); } catch(MyException me) { System.out.println("MyException"); } catch(Exception e) { System.out.println("Exception"); } catch(Throwable t) { System.out.println("Throwable"); } } }

a. MyException b. Exception c. MyException

Exception

d. MyException

Exception Throwable

Page 271: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 17: Exceptions 17-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

2. What output is generated by the following Java code?

public class MyClass { public static void myMethod() throws Exception { throw new Exception(); } public static void main(String [] args) { try { myMethod(); } catch(Exception e) { System.out.println("Exception"); } catch(Throwable t) { System.out.println("Throwable"); } finally { System.out.println("Finally"); } } }

a. Exception b. Exception Throwable

c. Exception

Finally

d. Exception Throwable Finally

3. What is the difference between runtime exceptions and explicit exceptions?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 272: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

17-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

What Is an Exception? In a Java program, an exception is some abnormal condition. Because Java is an object-oriented language, exceptions are represented by subclasses of java.lang.Exception objects. Java provides a model by which exceptions can be handled through an understanding of the Exception class hierarchy and the use of the following keywords: try, catch, throw, throws, and finally.

Exceptions can arise for a variety of reasons. For example, the user might enter incorrect information (e.g., wrong file name); the programmer might make errors in the code (e.g., an array that goes out of bounds); or in rare instances, equipment errors might occur (hard drives malfunction or run out of space, or serial ports are unavailable).

All exceptions are derived from the Throwable class. Under Throwable, there are two subclasses: Error and Exception.

Errors

Error is one subclass of Throwable. Errors can occur at runtime and usually should not be handled by the exception handling mechanism. Errors will terminate a program and are generally functions over which the programmer has little control, such as OutOfMemoryError, StackOverflowError or UnknownError. This course does not discuss errors in detail.

Exceptions

There are two types (subclasses) of exceptions: runtime exceptions and explicit exceptions.

Runtime exceptions (unchecked)

RuntimeException is an abstract class defining a set of possible conditions that might occur anywhere in a program. Some examples of runtime exceptions are ArithmeticException (often the result of attempting to divide by 0), ClassCastException (trying to perform an illegal cast operation), IndexArrayOutOfBoundsException (e.g., accessing element 15 of a 10-element array), and NullPointerException (trying to access an object when the variable contains null). The Java compiler does not enforce programmatic handling of runtime exceptions (you can ignore them), which is why they are referred to as "unchecked" exceptions. Although runtime exceptions can often be avoided through good programming practices, they can be handled like other exceptions. Because they are avoidable, this course will focus on the other type of exceptions: explicit or checked exceptions.

exception

An abnormal

condition that

occurs in a

program.

error

An inoperable

condition that can

occur in a program

and cause it to

terminate.

runtime exception

A set of possible

conditions that can

occur in a program

and cause an illegal

operation.

Page 273: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 17: Exceptions 17-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Explicit exceptions (checked)

Explicit exceptions can be found in any Java package. Some of them are defined in java.lang (such as an InterruptedException for a sleeping thread). Others are defined in java.net or java.io (such as a network connection not found or a file not available). You can even create your own exceptions, and use the same handling mechanisms discussed in this lesson with your customized exceptions. You can accomplish this by creating a class that is derived from Exception and using a default constructor. Another term for explicit exceptions is checked exceptions, because you must state that they might occur and you must make provisions for them (you cannot ignore them).

Figure 17-1 illustrates how the various exceptions are related to one another.

Object

Throwable

Exception

RuntimeException Explicit Exceptions

Error

• • •

• • •

• • •

Figure 17-1: Exception class hierarchy

Handling Exceptions Exceptions will occur in your programming. Better programming practices can help you avoid runtime exceptions, and you cannot do much to prevent errors, so we will focus on explicit exceptions.

There are four possible actions you can take if an Exception occurs:

• Ignore the Exception.

• Handle the Exception with a try/catch statement.

• Throw the Exception to the calling method.

• Handle the Exception and rethrow it to the calling method.

Page 274: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

17-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Ignoring the exception

In the case of a runtime exception, you can simply ignore the occurrence. If no action is taken when an exception occurs, the method in which it occurs immediately stops. It then reports back to the method that called it, stating that an exception occurred. If this method ignores the reporting method, the reporting method continues to propagate up the calling methods until the program finally terminates. This propagation should be avoided by careful programming.

For explicit exceptions, this scenario cannot occur. If a method might generate an exception, it is explicitly stated by a throws declaration. For example, the method specification for clone() in the Object class is as follows:

protected native Object clone() throws CloneNotSupportedException;

Once this declaration exists, you cannot ignore it, so you must take other action.

Catching the exception

This action is the one most often taken with exceptions. The code that might generate an exception (usually a call to a method with a throws statement) is written into a try/catch statement as follows:

try { myObject.clone(); } catch (CloneNotSupportedException e) { // action to take if the Exception occurs System.out.println("This clone wasn't supported!"); }

The goal is to catch an exception and correct it so it does not interfere with the smooth flow of your program. A potential Exception might occur in the try statement. If an exception is thrown, control is immediately transferred to the catch statement to handle the exception in an appropriate manner.

An additional bit to the try/catch clause is called finally and is used as follows:

try { //some code that may throw an exception } catch(Exception e) { // fix any problems } finally

Page 275: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 17: Exceptions 17-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

{ // clean up – for example, close any IO streams. }

It is possible to catch different types of exceptions. For example:

try { //some stuff that throws an Exception } catch(IOException e1) { //fix problems } catch(InterruptedException e2) { // fix problems } catch(Exception e3) { // fix problems }

In the previous code, you tested first for IOException. If it did not occur, maybe it is an InterruptedException. If not, it must be an Exception because all exceptions ultimately inherit from Exception. Notice the order of the catch statements. Note that if an IOException were caught by this example, the first catch block would handle the exception and execution would resume after the last catch block.

In this example, if no Exception exists, the return statement will return control to the calling method. However, the finally clause is always invoked, even if no exception was thrown.

Throwing the exception to the calling method

Sometimes, you want to defer catching an exception. For example, you can create a program that handles all exceptions in methodA, and notifies the programmer that they occurred:

void methodA() { try { methodB(); } catch (Exception e) { System.out.println("something went wrong"); }

Page 276: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

17-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

} void methodB() throws MyException { methodC(); } void methodC() throws MyException { throw new MyException() }

In this program, methodA calls methodB, which calls methodC. Then methodC declares that it throws MyException, so the MyException is passed up to methodB. Now methodB appears to have thrown the MyException, and passes it up to methodA. The methodA contains the MyException handling code (try/catch), so the processing occurs here. This process describes how explicit Exceptions are passed up the calling stack.

Handling and rethrowing the exception

It is possible to try/catch an exception and then rethrow it. The syntax is as follows:

public someMethod() throws SomeException { try { // code that may throw SomeException } catch(SomeException e) { // some Exception handling code throw e; } }

This way, some level of exception handling can take place, then the program can be passed back up the calling stack for further exception handling.

Creating User-Defined Exceptions Java allows you to create user-defined exceptions by extending the exception classes. User-defined exceptions are caught and thrown in the same manner as other exceptions. In this section, you will learn how to create user-defined exceptions.

Page 277: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 17: Exceptions 17-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Creating the exception

Creating exceptions in Java is straightforward. Typically, you will want to create a checked exception. You can create a checked exception by subclassing the Exception class (your exception becomes a checked exception by default).

public class MyException extends Exception { // You now have your own exception. // There is a little more to do still... }

Each exception generates a unique message when it is thrown. The exception you build should generate a message in case it is not caught. The constructors defined in the exception class are designed to make a message available when the exception occurs. However, constructors are not inherited, so you must use the super constructor from within MyException to access this feature:

public class MyException extends Exception { public MyException(String message) { // Let the Exception class do all the work. super(message); } public MyException() { // It is possible to set a default message. super("A MyException was thrown."); } }

Throwing the exception

Throwing an exception in Java is straightforward. It also provides much insight into the ways in which certain methods used in this course were defined. For example, you have used the Thread.sleep(int) method several times, yet it was never explained why you must place this method in a try/catch block, for example. The following code, which throws a MyException, would be nearly identical to the Thread.sleep(int) method, which throws an InterruptedException.

public class ThrowMyException { // In this method, if help is set to true (and it // is), a MyException is thrown. // Notice that the method itself is designed to throw // the MyException with the "throws" keyword. public void throwMyExceptionMethod() throws MyException { boolean help = true; if(help)

Page 278: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

17-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

{ // If the conditions are right, throw an instance // of the MyException class. throw new MyException("Help! Help!"); } } }

Now, the system is set. The MyException class is well-defined, and the code within the method that throws the MyException is also well-defined. Now, test the system:

public class TestMyException { public static void main(String[] args) { ThrowMyException throwME = new ThrowMyException(); // It is a checked exception, so the method must be // placed inside of a try/catch (for example). try { throwME.throwMyExceptionMethod(); } catch(MyException e) { System.out.println(e); } } }

Upon running TestMyException, you will see the following on your command line:

test2.MyException: Help! Help!

Exception Handling Tips • Sometimes you can avoid using a try/catch by performing a simple test. For

example, testing for an array index of outbounds is good, but it adds unnecessary overhead (often by factors). It is preferable to simply test to verify that you are not exceeding your array.

• Defining your own exceptions certainly has its purpose, but obligating other programmers to deal with all your possible exceptions can be cumbersome and inefficient. When designing Java, Sun could have designed everything to throw exceptions to produce the most error-free language ever, but it would have been highly inefficient and annoying for programmers.

• If you can put several potential exception throwing methods in one try statement, do so. Writing a separate try/catch block for each exception throwing method is inefficient.

Page 279: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 17: Exceptions 17-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

• If you catch exceptions, do something meaningful. Code is not robust or easily distributed if exceptions have been "hidden." If necessary, throw the exception back to the calling method when appropriate to handle the exception.

Exceptions and Inheritance It is interesting to see which exceptions can be thrown when a method is overridden in a subclass. An overridden method cannot throw any checked exceptions that are not thrown by the method overridden. Figure 17-2 demonstrates this.

class A { public void test() throws MyException; }

class B extends A { public void test(); }

class C extends B { public void test(); // cannot throw MyException }

Figure 17-2: Overridden method

In this example, three classes are defined. Class A defines a method named test that throws a MyException. Class B overrides the test method with a method that does not throw this exception. Overriding methods may throw any subset of the exceptions thrown by the overridden method. That is, the test method defined in class B may throw a MyException or it may throw no exception at all. Note that the test method defined in class C cannot be defined to throw a MyException because MyException is not thrown by the test method defined in class B.

Page 280: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

17-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Exceptions provide a unified mechanism for reporting errors. Before the concept of exceptions entered programming languages, the developer often used a nonsensical return value to indicate that an error occurred. For example, if a particular method had a return type of int, and a positive value were expected if the code was successful, the method might be designed to return a value of –1 to indicate that an error occurred. Obviously, this is a clumsy solution when compared with exceptions. Write a paragraph describing how Java exceptions fit into the object-oriented paradigm. How do exceptions promote encapsulation and good design?

Skills review

In this lesson, you defined exceptions and errors, and you learned to manipulate Java's exception handling capabilities. You will catch exceptions in the upcoming lessons. Thread methods, IO methods, and networking methods are all prone to exceptions beyond the control of the programmer, so they must use the try/catch or exception propagating mechanisms discussed in this lesson.

Now that you have completed this lesson, you should be able to:

� Differentiate between errors and exceptions.

� Differentiate between runtime exceptions and explicit exceptions.

� Propagate an exception using the throws statement.

� Handle an exception using the try/catch statement.

� Create and use a user-defined exception.

Page 281: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 17: Exceptions 17-13

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 17 Review

1. What is an exception?

_______________________________________________________________

_______________________________________________________________

2. What keywords are used to handle exceptions in Java?

_______________________________________________________________

_______________________________________________________________

3. What is an error?

_______________________________________________________________

_______________________________________________________________

4. From what class are exceptions and errors derived?

_______________________________________________________________

5. What is a runtime exception?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

6. What is a checked exception?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 282: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

17-14 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

7. What four possible actions can you take if an exception occurs?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

8. Generally, how can you create your own exceptions in Java? Which type of exception will this generate?

_______________________________________________________________

_______________________________________________________________

Page 283: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

18Lesson 18:

Creating Threads and

Thread Methods

Objectives By the end of this lesson, you will be able to:

� Define threads.

� Create and instantiate threads using two different techniques.

� Control single-thread flow.

� Define the four thread states and their relationships to thread methods.

Page 284: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

18-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. Which of the following is true with respect to thread states?

a. A thread in the dead state can be moved into the runnable state. b. A thread in the runnable state always has control of the CPU. c. A thread in the not runnable state can moved into the runnable state. d. A thread in the dead state can be moved into the not runnable state.

2. Which of the following is true with respect to threads in Java?

a. Threads created by the JVM for purposes such as garbage collection are typically user threads.

b. The yield method must be called in order for control to pass from one thread to another.

c. A user thread may itself spawn additional user threads. d. The main thread of execution is one example of a daemon thread.

3. What are the two techniques for creating threads?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 285: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 18: Creating Threads and Thread Methods 18-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

What Are Threads? A thread is best defined by first differentiating among multitasking, multiprocessing and multithreading.

Multitasking is a general term referring to the ability to perform more than one function simultaneously. Multiprocessing is the ability to run more than process at the same time. If you are running a word-processing program and a graphics editor and also listening to your favorite CD on your computer, you are running three processes at once. Most modern operating systems are efficient at multiprocessing.

Multithreading is the ability to perform multiple functions within the same process. Suppose that you are running a Web browser (a process), and you are using it to send an e-mail message, download an audio file, and upload another file to an FTP server. You are running three threads within one process. Java is multithreaded. The primary difference between multiprocessing and multithreading is that each process maintains a separate data set, whereas multiple threads can work on the same data set.

Java's ability to perform multithreading has been part of the Java language from the beginning. The Object class contains methods of Object such as wait or notify; these methods are used to control threads. Multithreading is also very efficient. It is less taxing for an operating system to maintain multiple threads than it is to maintain multiple processes. This fact can help you write very efficient Java code.

How Operating Systems Handle

Multitasking One of the difficulties faced by Java's designers was how to handle the fact that different operating systems handle multitasking differently. Different operating systems use either of two techniques to perform multitasking: pre-emptive multitasking and cooperative multitasking.

Pre-emptive multitasking allows the operating system to pre-empt (or interrupt) the execution of one process or thread, and transfer control to another process or thread. Each process notifies the OS of its priority. The OS uses this information to continuously provide each active process with its "slice" (allotment) of CPU time. In such a system, the tasks need not cooperate with each other because a task can receive CPU time as a product of its priority. Thirty-two-bit Windows operating systems use pre-emptive multitasking.

thread

Program code

running in parallel

with other program

code within the

same application.

multitasking

The ability to

perform more than

one function

simultaneously.

multiprocessing

The ability to

execute multiple

processes

(applications) in

parallel.

multithreading

The ability to

execute multiple

threads in parallel.

pre-emptive

multitasking

A system of

multitasking in which

one task can pre-

empt another task if

it has a higher

priority.

cooperative

multitasking

A system of

multitasking in which

one task must

willingly yield to

another task.

Page 286: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

18-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Cooperative multitasking requires that a task willingly surrender control so another task can gain CPU time. The problem becomes apparent: What if a task is unwilling to relinquish control? The possibility for dominating the CPU is great.

Because your Java programs may be run on any of several operating systems, you cannot know if the threads you create will operate under the pre-emptive multitasking model or the cooperative multitasking model. However, this uncertainty does not pose a problem provided that you design your threads in Java to behave considerately.

Types of Threads in Java Java uses two types of threads: daemon threads and user threads. Most daemon threads are created by the JVM (garbage collection, AWT, and so forth), while the programmer creates most user threads. User threads may be set as daemon threads.

The difference between the two threads is based on the services they perform. Daemon threads are usually designed to run in the background for the purpose of servicing user threads. The garbage collector thread is a good example of a daemon thread. It performs its garbage collection service for other threads transparently. When all other user threads have finished, the garbage collector thread will no longer exist.

You rarely will work directly with daemon threads. The JVM provides other servicing threads in addition to the garbage collector. One daemon thread processes mouse events and maintains your graphics context. If you need some type of scheduling service to run transparently, you could create a daemon thread for this purpose. Daemon threads expire when the last user thread expires. At that point, the program will terminate.

Programmers create and utilize user threads more frequently than daemon threads. You have worked with one particular user thread since your first Java program: the main thread.

daemon thread

A thread designed

to service user

threads. Daemon

threads terminate

after the last user

thread terminates.

user thread

A thread created

by other user

threads with the

purpose of being

controlled by the

programmer.

main thread

The user thread

created by the JVM

from which all other

user threads are

generated.

Page 287: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 18: Creating Threads and Thread Methods 18-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The main thread is a user thread made available by the JVM. This thread is launched in the public static void main(String[] args) method. From this main thread, you will launch all other threads, as depicted in Figure 18-1.

main thread

user thread user thread

user thread user thread

Figure 18-1: Main thread

Creating Threads The two ways to create a thread within your Java application or applet are to subclass the Thread class or to implement the Runnable interface. Both techniques are used extensively in Java, and each has advantages and disadvantages. This section will examine these techniques in detail and discuss their strengths and weaknesses.

Subclassing the Thread class

Java has a class called Thread. By extending the Thread class, you inherit all the functionality of this class.

class MyThread extends Thread { }

This code is a valid Thread that does nothing. You can remedy this by adding a method called run.

The run method is where the JVM expects to find all code intended to execute as part of a Thread. The JVM knows that the run method is available by consulting the Runnable interface.

run

The method that

contains the body

of a thread.

Page 288: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

18-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The Thread class implements an interface called Runnable. The only method defined in this interface is run. When you extend Thread, you also inherit this run method. At this point, you need only override the run method to implement your threaded code.

To actually start your thread, you cannot simply call the run method of your Thread instance. You must call the start method of the Thread instance, and the start method calls the run method. As you might imagine, threading varies extensively among operating systems. The fact that the programmer calls start and the JVM calls run is a reminder that much must be done behind the scenes before your threads can run.

The following code demonstrates a simple thread created by extending the Thread class:

class MyThread extends Thread { // After you implement threading // the MyThread class inherits the start() method from the // Thread class. public void run() { while(true) { System.out.println("MyThread Thread"); } } }

One possible output is as follows (output may vary each time this class is run):

MyThread Thread Main Thread MyThread Thread Main Thread MyThread Thread Main Thread . . .

start

The method that

starts a thread by

calling the run

method.

Page 289: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 18: Creating Threads and Thread Methods 18-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Implementing the Runnable interface

The previous example of multithreading by extending Thread was straightforward and functional. This technique, however, has two serious drawbacks. The first is that Java does not support multiple inheritance. Once you extend Thread, you have locked your class into being a subclass of Thread, and you forfeit a level of flexibility in your class design.

The second drawback is that the Thread class may not be an appropriate superclass for your class in terms of your design. More than likely, you wanted to gain the functionality of the Thread class, yet by inheriting from Thread you are forcing yourself to assume a type that does not support your class structure.

The solution is elegant. You learned earlier that you use the run method to write your code because the Thread class implements the Runnable interface and (by contract) must implement this method. You can do the same for your class; that is, you can implement the Runnable interface. The rewrite is as follows:

class MyThread implements Runnable { // Rewrite using Runnable instead of Thread public void run() { while(true) { System.out.println("MyThread Thread"); } } }

This threaded class has now been rewritten to use the second method of writing threaded classes (you changed only two words). Of course, you still must get your Thread started.

If you consider your Main class again, you instantiated the Thread and then started it by calling its start method as follows:

MyThread thread = new MyThread(); thread.start();

You cannot call this method with your modified MyThread class because there is no start method. Remember that you are no longer inheriting from Thread, therefore you do not have a start method.

Runnable interface

An interface that

prototypes the run

method, targeting it

as a thread.

Page 290: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

18-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

You can solve this problem because the Thread class has a constructor that takes an Object of type Runnable. The delegation design pattern is very common in object-oriented design. In essence, a front-end object delegates the responsibility of the work to an implementation object. You can now start your runnable MyThread as follows:

class ThreadStuff { public static void main(String[] args) { Thread myThread = new Thread(new MyThread()); myThread.start(); while(true) { System.out.println("Main Thread"); } } }

Which technique?

Which thread-creation technique should you use? This question is common and deserves some consideration.

Object-oriented purists would argue that one should never subclass another class without the intention of further defining it. This point counters the subclassing technique because you would not add to the base class Thread.

On the other hand, the Thread class is such an inherent part of the Java language that it is almost a reusable component. It is also easier to understand. This point favors the subclassing technique.

However, the interface technique requires you to become accustomed to it. Overall, its adherence to the rules of subclassing and its relationship to the delegation design principle make it an elegant and recommended technique.

Thread Methods A thread can be compared to a talented violinist: Playing solo is one skill, but playing in an orchestra is completely different. So far, your MyThread class has been playing solo. You must now learn ways of orchestrating your threads.

Page 291: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 18: Creating Threads and Thread Methods 18-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

A note should be made about three methods of the Thread class: stop, suspend and resume. These three methods have been deprecated with the release of Java SDK 1.2. The stop and suspend methods were prone to leaving a thread in an inconsistent state, and the resume method is the counterpart to the suspend method. In the next lesson, you will learn some alternative techniques to replace these methods.

You can orchestrate your threads with the many thread-controlling methods available in Java. Table 18-1 lists the methods you will use in this lesson to help control a single thread. In the next lesson, you will learn ways of controlling many threads simultaneously.

Table 18-1: Methods used to control single thread

Method Description

currentThread Returns an instance of the thread currently running

getName Returns the name assigned to this thread

notify Notifies the single thread that initially called wait on the object

notifyAll Notifies all threads that called wait on the same object

* resume Resumes the execution of this thread (*deprecated)

run Executes the body of the thread

setName Sets the name of the thread

setPriority Sets the priority of the thread

sleep Causes the currently running thread to sleep for a specified amount of time (in milliseconds)

* stop Kills the thread (*deprecated)

start Calls the thread's run method to begin executing the thread

* suspend Suspends execution of this thread until resumed (*deprecated)

yield Causes the currently running thread to yield to other threads

wait Dictates that the calling thread give up the object monitor and sleep until it is notified by a later thread

Page 292: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

18-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Thread states

Before you use any of the preceding thread-controlling methods, it helps to know the various thread states and how these methods affect a thread's state. The Java specification defines four thread states: new, runnable, not runnable, and dead.

New

A thread is in the new state after it is instantiated but before it is started. The following statement will place a thread in the new state:

MyThread myThread = new MyThread();

Runnable

A thread is runnable once its start method has been called. It may seem odd to define the state as runnable instead of running. Runnable is more appropriate because a thread spends much of its life on a thread queue waiting to be run. The following statement places a thread in the runnable state:

MyThread.start();

Not runnable

Certain methods will remove a runnable thread from the active queue. The thread is then not runnable. At this point, it cannot be placed back on the active queue until specifically requested. In the next section, you will learn techniques for placing a thread in the "not runnable" state. In essence, you will simulate the now-deprecated suspend method of the Thread class.

thread state

The current

condition of a

program thread.

new

The state of a Java

thread once it has

been instantiated.

runnable

The state of a Java

thread once it has

been started.

not runnable

The state of a Java

thread when it is

removed from the

runnable queue but

is not dead.

Page 293: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 18: Creating Threads and Thread Methods 18-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Dead

A thread is dead once it has been explicitly stopped (you will simulate the now-deprecated stop method in the next section). A thread is also dead once its run method exits normally. In Java, dead is a permanent state; the thread cannot be resurrected.

Figure 18-2 illustrates the thread states.

New Thread

Dead

Not RunnableRunnable

stop()

start()

stop()

suspend()

resume()

yield()

stop()

Figure 18-2: Thread states

The currentThread, getName and sleep methods

To gain a better understanding of the methods of Thread, consider the user thread provided by the JVM: the main thread.

currentThread and getName

The currentThread method allows you to obtain an instance of the currently running thread, while getName provides the String name associated with the thread. Study the following example:

class ThreadStuff { public static void main(String[] args) { Thread myThread = Thread.currentThread(); // Obtains an instance of // the currently running // thread System.out.println(myThread.getName()); } }

The output of ThreadStuff is as follows:

main

dead

The state of a Java

thread once it has

been stopped or the run method has

exited.

Page 294: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

18-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

In the preceding code, the only thread running is the user thread main supplied by the JVM. When you asked to get the current thread, you were guaranteed to get an instance of the main thread.

sleep

The static method sleep is a utility method of Thread. You can specify (as an argument) the number of milliseconds you want the current thread to sleep. However, you must invoke the method in a try/catch statement, otherwise you will get a compiler error.

In the following code, you will display the name of your main thread, and then display an additional message two seconds later:

class Main { public static void main(String[] args) { Thread myThread = Thread.currentThread(); System.out.println(myThread.getName()); try { Thread.sleep(2000); } catch(InterruptedException e) { System.out.println(e); } System.out.println("2 seconds since our last message."); } }

The setName method

The setName method will associate a String name with a Thread. This function is optional, but it may help you distinguish one thread from another when necessary.

MyThread myThread = new MyThread(); myThread.setName("My Thread");

Page 295: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 18: Creating Threads and Thread Methods 18-13

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The setPriority method

The setPriority method is an important method of Thread.

The beginning of this lesson stated that Java followed a model of pre-emptive multitasking. This model requires that one thread be able to pre-empt another thread. This operation is accomplished by assigning a priority (from 1 to 10) to any Java thread.

You need not assign a priority to a thread because threads automatically receive a priority of 5 upon creation, including the main thread. However, if you create many threads and all have a priority of 5, then you need to ensure that you make your threads behave correctly. You will see how to accomplish this later.

You can set a thread's priority as follows:

MyThread myThread = new MyThread(); // Has priority of 5 myThread.setPriority(8); // Has priority of 8

Interestingly, this change in priority affects the behavior of your threaded program. To see this, refer back to your well-behaved thread example in which the main thread and myThread took turns displaying messages in an infinite while loop. Adjust only the priority of myThread, as follows:

class ThreadStuff { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.setPriority(8); myThread.start(); while(true) { System.out.println("Main Thread"); } } } class MyThread extends Thread { public void run() { while(true) { System.out.println("MyThread Thread"); } } }

Page 296: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

18-14 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

You should be able to predict that the thread with higher priority will claim all the CPU time, but you cannot. The nature of thread behavior will vary greatly among systems. In Microsoft Windows Me, both threads are able to display their messages, although an almost two-to-one ratio favors the thread with the higher priority. Your system may behave differently.

It is apparent that you cannot rely on thread priority alone to control the behavior of your threads.

The yield method

One way to force your threads to behave better is by using the yield method. The thread that is asked to yield must relinquish its current running cycle and be placed on the thread queue. A high-priority thread will be running again very quickly; in the interim however, it will give some CPU time to other threads. A common thread technique is to always yield at some point within the body of a Thread. For example:

class MyThread extends Thread { public void run() { while(true) { System.out.println("MyThread Thread"); yield(); // Relinquish some CPU time graciously } } }

The yield method provides an excellent way to create "considerate" threads. In reality, whenever a thread has completed a cycle of its responsibilities (for example, a mathematical calculation or part of an animation), it should release the CPU to allow processing time for other threads. Using the yield method will facilitate this action.

Page 297: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 18: Creating Threads and Thread Methods 18-15

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lab 18-1: Creating a threaded digital clock in Java

You have seen two ways to create threads, and you have used numerous methods of the Thread class. In this lab, you will expand the Timer class to make it a threaded class. You will use this thread-enabled Timer class to build a digital clock.

1. Create a class called DigitalClock that extends JFrame and implements TimerInterface (from an earlier lab). This class will serve as the GUI for your digital clock and should resemble Figure 18-3.

JLabel

Figure 18-3: DigitalClock interface

2. Using the interface technique of creating threads, modify your Timer class so it is a threaded class.

3. Add a method to the Timer class called public void startTimer. Invoking this method will start the thread (the body of the run method).

Hint: You will probably want to create an instance variable of type Thread in your Timer class called timerThread. This timerThread variable will refer to the run method of your Timer class.

4. Event-enable your interface's Start button so that when it is clicked, the Timer thread will start and the time will be continuously updated on the JLabel. Note the following considerations:

• You will use this Timer instance in several methods of your DigitalClock class. Therefore, declare it as an instance variable.

• The remaining three buttons (Stop, Suspend and Resume) will be enabled in the next lesson.

5. (Optional) Adjust the font of the JLabel so that the display is large and readable. Perform any other cosmetic enhancements you deem necessary to the GUI.

Page 298: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

18-16 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Unlike most other programming languages, threads are an integral part of Java. Having a unified method for creating and managing threads makes Java an ideal solution for enterprise development. Create a list of five applications that could benefit from the use of threads.

Skills review

In this lesson, you learned the two ways to create a process: extending the Thread class and implementing Runnable. You also examined some of the methods of Threads. In the next lesson, you will learn how to control shared resources and coordinate the action of several Threads.

Now that you have completed this lesson, you should be able to:

� Define threads.

� Create and instantiate threads using two different techniques.

� Control single-thread flow.

� Define the four thread states and their relationships to thread methods.

Page 299: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 18: Creating Threads and Thread Methods 18-17

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 18 Review

1. What is a thread?

_______________________________________________________________

_______________________________________________________________

2. What is multitasking?

_______________________________________________________________

3. What is multiprocessing?

_______________________________________________________________

_______________________________________________________________

4. What is multithreading?

_______________________________________________________________

5. How does pre-emptive multitasking differ from cooperative multitasking?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

6. Name the two types of threads used by Java.

_______________________________________________________________

7. What two techniques can you use to create threads in Java?

_______________________________________________________________

_______________________________________________________________

Page 300: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

18-18 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

8. What is the purpose of the run method in relation to threads?

_______________________________________________________________

_______________________________________________________________

9. How does the start method differ from the run method in relation to threads?

_______________________________________________________________

_______________________________________________________________

10. What is a thread state? Name the four thread states defined in the Java specification.

_______________________________________________________________

_______________________________________________________________

Page 301: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

19Lesson 19:

Thread Synchronization

Objectives By the end of this lesson, you will be able to:

� Define synchronization in relation to object monitors.

� Control thread racing using thread synchronization.

� Convert non-atomic processes to atomic processes to avoid thread racing.

� Use sophisticated methods for controlling threads.

� Stop, suspend and resume threads.

� Explain thread deadlock.

Page 302: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

19-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. Which of the following is true with respect to thread synchronization?

a. The notify method can be used to pass control to a specific thread. b. Calling the wait method relinquishes a lock. c. The notifyAll method notifies all interested threads that the current

thread has obtained a lock. d. The notify method operates asynchronously.

2. Which of the following is true with respect to thread synchronization?

a. The synchronized keyword can be applied only to a method. b. The synchronized keyword can be applied only to a free standing

code block. c. A lock controls access to an entire class instance. d. The volatile keyword prevents an thread from accessing volatile

data.

3. What is thread racing?

_______________________________________________________________

_______________________________________________________________

Page 303: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 19: Thread Synchronization 19-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

What Is Thread Synchronization? You have already learned how to control single threads. In realistic systems, where typically more than one thread is competing for the same resource, you need more sophisticated ways to control the threads. If you do not control your threads in a predictable manner, you will likely produce corrupt data where that data is shared.

Java uses a method of controlling threads called synchronization. To appreciate the power of thread synchronization, this lesson will introduce and duplicate the concept of thread racing. Later, through synchronization, you will solve the problem of thread racing.

Thread Racing An excellent example of thread racing is based on banking.

Assume that a husband and a wife use an ATM system that does not incorporate thread synchronization.

The husband goes to the ATM to withdraw $250 from a joint checking account. The wife does the same thing in another part of town. The checking account has only $300 in it.

When the husband makes the request to withdraw $250, the ATM recognizes that $300 is available in the account, and it grants the request. At almost the same time, the wife's ATM also says that $300 is available and also grants the request. The couple has now overdrawn the account by $200.

While the wife was accessing the account, the account should have been made unavailable until the entire process was complete. Only after that should the husband have had access to the account. It then would have been apparent that the funds were insufficient to grant the husband's request.

synchronization

Controlling the flow

of multiple,

simultaneous

threads.

thread racing

Competition

between two or

more threads for the

same resource.

Page 304: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

19-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Following is a simple class that could have handled the request:

class Account { public double withdraw(double amount) { if(amount <= amountAvailable) { amountAvailable -= amount; } else { amount = 0; // return nothing – an error; } return amount; } }

In the preceding scenario, the mishap could have been avoided by use of an object monitor.

Synchronized and the Object Monitor An object that contains a monitor is able to control its methods (or blocks of code) so that only one thread has access to that method at a time.

You can associate a monitor with an object by simply declaring a method as synchronized. For example, if you consider your Account object, you can place a monitor on that object by declaring its method synchronized as follows:

class Account { public synchronized double withdraw(double amount) { if(amount <= amountAvailable) { amountAvailable -= amount; } else { amount = 0; // return nothing – an error; } return amount; } }

monitor

A control device for

an object that limits

thread access to

the object's

methods.

synchronized

The keyword used

to access an

object's monitor.

Page 305: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 19: Thread Synchronization 19-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

In this example, once a thread enters the withdraw method, it obtains the object's monitor. At this point, all other threads are blocked from entering this method and are placed on a thread queue. When the first thread exits the synchronized method and releases the monitor (automatically), the threads on the wait queue may now enter the method to obtain the monitor (one at a time).

If you have more than one method declared as synchronized, then only one thread may enter any of the synchronized methods. Even if only one synchronized method was entered by a thread, all synchronized methods will be blocked to other threads until the first thread exits its method and releases the monitor. Methods that are not synchronized are available to all threads.

Thread Race Condition You will now create a race condition, then attempt to solve it. Use the RaceThread class as follows:

class RaceThread { MainThread m; RaceThread (MainThread tmpM) { m = tmpM; } public void run() { for (int i=0; i < 10; i++) { int c = m.getCount(); m.setCount(c+1); } } }

Page 306: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

19-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Competing for resources

Creating a race condition is not difficult. Using your RaceThread from the preceding example, you need to make only minor modifications. You will add a second RaceThread so that two threads will compete to set the count value. You will also add a pause method to help magnify the race condition. See the following code:

class MainThread extends CloseableFrame { // All the GUI components... and in addition ... private int count; RaceThread raceThread1; RaceThread raceThread2; MainThread() { raceThread1 = new RaceThread(this); raceThread2 = new RaceThread(this); } public static void main(String[] args) { MainThread mainThread = new MainThread(); } public void setCount(int tmpCount) { pause(50); count = tmpCount; textArea.append(count + "\n"); } public int getCount() { pause(50); return count; } public void pause(int milliseconds) { try { Thread.sleep(milliseconds); } catch(InterruptedException e) { System.out.println("MainThread: pause() " + e); } } }

Page 307: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 19: Thread Synchronization 19-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The results will vary among systems, but the output probably shows a double print of the count values, as follows:

1 1 2 2 3 3 . .

This result is not as intended. Each thread should be updating a unique count.

Synchronizing the methods

The natural solution to your race condition is to synchronize your methods. As stated earlier, when the synchronized keyword is added to a method, a thread can get the monitor of that Object, and prevent any other method from entering a synchronized method, as shown:

public synchronized void setCount(int tmpCount) { pause(50); count = tmpCount; textArea.append(count + "\n } public synchronized int getCount { pause(50); return count; }

After running the program again, the result is the same:

1 1 2 2 3 3 . .

Why? The synchronization should stop the race condition. This problem is not the fault of the synchronization feature of the Java language; this problem is a design issue called an atomic process.

Page 308: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

19-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Atomic processes

Atomic processes do not have intermediate states. In your example, the task of updating the count variable in MainThread is not an atomic process. Consider the following:

1. RaceThread1 performs a synchronized getCount method. It now exits that method briefly to increment the count in its run method.

2. RaceThread1 now performs a synchronized setCount method to set the updated count variable.

The fact that a break occurred in the complete process between the getCount and setCount method calls means that the process was not atomic, and that RaceThread2 was able to enter between these method calls and corrupt the data.

Conceptually, the solution is apparent: Make a single process. Following is some code that would make this an atomic process:

// Pseudo code for the solution public synchronized void updateCount() { int c = getCount(); setCount(c + 1); } private int getCount() { // return the count } private void setCount() { // set the count }

You should note two points about this code:

• Making getCount and setCount private is a design choice. If you are going to increment count via the updateCount method, do not make the methods more accessible than necessary.

• If getCount and setCount are only called internally from updateCount (a synchronized method), you need not make them synchronized as well; doing so will slow the system.

atomic process

A process that has

no intermediate

state.

Page 309: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 19: Thread Synchronization 19-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Sophisticated Thread Synchronization Java provides a more sophisticated way to synchronize threads: the methods wait, notify and notifyAll.

Normally, a thread is suspended and later resumed either by some external factor (such as pushing a button) or by continuously polling for the condition upon which to change the thread's state. Java has a poll-free mechanism to conditionally control threads through the method invocations of wait and notify/notifyAll.

The wait and notify methods are not methods of Thread; they are methods of Object, which proves that Java was originally designed as a multithreaded language. And although wait and notify do constitute a form of thread synchronization, they do not solve the thread race problem. In fact, the wait and notify methods must be called within a synchronized block themselves. For this reason, the wait and notify techniques are often regarded as a form of interthread communication.

An excellent example for the use of wait and notify is the consumer/producer model.

Consumer/producer scenario

A print queue represents a consumer/producer scenario. Although the following situation is somewhat outdated, the skills learned here can be directly applied to other consumer/producer scenarios, such as graphics in Java.

A primitive computer (a producer thread) is going to print a document by placing it on a print queue one character at a time. A primitive printer (a consumer thread) will take the characters from the print queue and print them one at a time. The problem is that the printer can print information only when the information is available. Therefore, two possibilities must be considered. The first possibility is that no information is available to print. The second possibility is that information is available to print.

No information available for printing

If no information is available to print, then the printer must call wait on itself until the computer has placed some information in the print queue.

The wait method can be called only from within a synchronized block. Therefore, the printer will have had control of the object monitor just before calling wait.

Page 310: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

19-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Once the printer calls wait on itself, it is placed in a wait queue and relinquishes the object monitor, allowing another thread to gain access to the synchronized block (in this case, the computer thread).

The printer thread will remain in this wait queue until an external thread (the computer thread) calls notify or notifyAll. At this point, the printer thread may now have access to the print queue.

Information available for printing

If information is available for printing, the printer can take that information from the print queue and print it.

Because information was available for printing, the printer must assume that the computer is waiting (on the wait queue) for the opportunity to place more information on the print queue.

The printer can notify the computer that new information is available on the print queue by calling notify or notifyAll. This action releases the computer from the wait queue.

These steps could have been stated from the computer's perspective with no loss of clarity. Overall, it is important to understand that the computer and printer take turns working with the print queue. When one has access to the print queue, the other is waiting in a wait queue until it is notified. This process continues back and forth.

You will now develop a more general consumer/producer system with the creation of four classes. Study the following code:

// class One – the queue class Q { // This class represents the queue. A producer thread // will place information in the queue using the putData() // method or wait. A consumer thread will get information // from the queue using getData() or wait. boolean info_in_q = false; int data; synchronized public void putData(int tmpData) { if(info_in_q) { try { wait(); } catch(Exception e) {

Page 311: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 19: Thread Synchronization 19-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

System.out.println(e); } } data = tmpData; System.out.println("Put: " + data); info_in_q = true; notifyAll(); } synchronized public int getData() { if(!info_in_q) { try { wait(); } catch(Exception e) { System.out.println(e); } } info_in_q = false; notify(); return data; } } // class Two – the producer class DataProducer extends Thread { // The DataProducer continuously places an // incremented integer into the Q. Q q; int data; DataProducer(Q tmpQ) { q = tmpQ; start(); } public void run() { while(true) q.putData(data++); } } // class Three – the consumer class DataConsumer extends Thread { // The DataConsumer retreives the incremented

Page 312: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

19-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

// integer that the DataProducer placed in the Q. Q q; DataConsumer(Q tmpQ) { q = tmpQ; start(); } public void run() { while(true) System.out.println("Got: " + q.getData()); } } //class Four – the dummy class class Main { // This class starts the activity public static void main(String[] args) { Q q = new Q(); DataProducer producer = new DataProducer(q); DataConsumer consumer = new DataConsumer(q); } }

The only difference between notify and notifyAll is

that notify calls the first Thread that called wait on the

Object, whereas notifyAll calls all Threads that called

wait on the Object. In a multithreaded program,

notifyAll is almost always used.

The output of the preceding class system resembles the following:

.

. Put: 21 Got: 21 Put: 22 Got: 22 Put: 23 Got: 23 Put: 24 Got: 24 Put: 25 Got: 25 Put: 26 . .

Page 313: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 19: Thread Synchronization 19-13

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Stopping, Suspending and Resuming

Threads SDK 1.2 deprecates the stop, suspend and resume methods of the Thread class. This decision was wise for the stop and suspend methods, which were prone to putting a thread into an inconsistent state. It was common for a thread in the middle of a function to be forcibly stopped or suspended. Ideally, threads should always be allowed to gracefully stop or suspend. You will explore such techniques in this section.

Before discussing thread-controlling techniques, one point must be made clear. The thread you want to control is the thread executing the contents defined in the run method of a Runnable object. Confusion may arise if you try to imagine the locations of these threads and ways to control them. Keep it simple: You want to control the thread in the body of the run method (the reason it is called the body of a thread). Consider the following example:

public class ReminderStuff implements Runnable { public void run() { // Code you want to run // in its own thread. } }

Stopping a thread

Because you are trying to control the thread running in the run method, you can write code in this method to stop the thread. The best approach is to allow the thread to run only while a certain condition is true. If that condition becomes false, stop the execution of the thread. This approach is elegant because the thread itself is testing the condition, which guarantees the opportunity for a graceful termination of the thread. Consider the following example:

public class ThreadControlStuff implements Runnable { boolean doRun = true; public void run() { // Do stuff in the body of this thread until // doRun becomes false while(doRun) { // Code to execute in the body of a thread. } } // This method, when called, will change the

The thread you want to control

Page 314: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

19-14 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

// value of doRun, and stop the thread. public void stopTimer() { doRun = false; } }

Suspending a thread

Suspending a thread is somewhat more difficult because you must use the object monitor. The approach is similar to stopping a thread in that you will suspend the thread only if a certain condition is met. The actual suspension is tricky. The thread will be suspended by waiting on the object monitor of the thread. Consider the following code:

public class ThreadControlStuff implements Runnable { boolean doRun = true; boolean doSuspend = false; public void run() { // Do stuff in the body of this thread until // doRun becomes false. while(doRun) { // Code to execute in the body of a thread // If the thread is to be suspended, have it // wait on the object monitor. if(doSuspend) { synchronized(this) { wait(); } } } } // This method, when called, will change the // value of doRun, and stop the thread. public void stopTimer() { doRun = false; } // This method, when called, will change the // value of doSuspend, and suspend the thread. public void suspendTimer() { doSuspend = true; } }

Page 315: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 19: Thread Synchronization 19-15

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Resuming a thread

Resuming a thread works in conjunction with suspending a thread, and involves releasing the thread that is waiting on the object monitor via notification. Consider the following example:

public class ThreadControlStuff implements Runnable { boolean doRun = true; boolean doSuspend = false; public void run() { // Do stuff in the body of this thread until // doRun becomes false. while(doRun) { // Code to execute in the body of a thread // If the thread is to be suspended, have it // wait on the object monitor. if(doSuspend) { synchronized(this) { wait(); } } } } // This method, when called, will change the // value of doRun, and stop the thread. public void stopTimer() { doRun = false; } // This method, when called, will change the // value of doSuspend, and suspend the thread. public void suspendTimer() { doSuspend = true; } // This method, when called, will change the // value of doSuspend, and notify the waiting thread. public void resumeTimer() { synchronized(this) { doSuspend = false; notify(); } } }

Page 316: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

19-16 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Deadlocks Another common timing problem with threads is called deadlock. A deadlock occurs when two or more threads from different objects are waiting for the same object monitor. Consider the situation illustrated in Figure 19-1.

ObjectA { synchronized methodA() }

ObjectB { synchronized methodB() }

Thread1

blocked

blocked

Thread2

Figure 19-1: Deadlock

Thread1 enters methodA and obtains the ObjectA monitor. It then proceeds to methodB for further processing. However, at the same time, Thread2 obtains the ObjectB monitor, then proceeds to methodA. The two threads are now deadlocked, neither willing to give up its own object monitor.

Java provides no built-in mechanism to avoid deadlocks. The programmer is responsible for avoiding the deadlock scenario.

deadlock

A condition that

occurs when two or

more threads reach

an impasse due to

competition for

object monitors.

Page 317: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 19: Thread Synchronization 19-17

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lab 19-1: Enhancing the digital clock with advanced

thread techniques in Java

In a previous lab, you created a DigitalClock class that had four buttons: Start, Stop, Suspend and Resume. Only the Start button was implemented. In this lab, you will use more advanced threading techniques to implement functionality in the remaining three buttons.

1. Add a method to the Timer class called public void stopTimer. Invoking this method will stop the thread.

2. Add a method to the Timer class called public void suspendTimer. Invoking this method will suspend the thread.

3. Add a method to the Timer class called public void resumeTimer. Invoking this method will resume the thread.

4. Event-enable the Stop, Suspend and Resume buttons on your interface so that when those buttons are clicked, the appropriate method of the Timer class will be called.

Page 318: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

19-18 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Understanding thread synchronization is critical to success in developing thread-based Java applications. Consider the ATM example discussed in this lesson. Identify five other scenarios that would require the use of the thread synchronization tools presented in this lesson.

Skills review

In this lesson, you learned how to protect data that is sensitive to being changed by multiple threads. You also practiced stopping, suspending and resuming threads. Remember that the more object monitors you place on a program, the greater the likelihood of deadlock occurring. Experience will help you learn what needs to be monitored and what does not.

Now that you have completed this lesson, you should be able to:

� Define synchronization in relation to object monitors.

� Control thread racing using thread synchronization.

� Convert non-atomic processes to atomic processes to avoid thread racing.

� Use sophisticated methods for controlling threads.

� Stop, suspend and resume threads.

� Explain thread deadlock.

Page 319: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 19: Thread Synchronization 19-19

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 19 Review

1. What is synchronization in relation to threads?

_______________________________________________________________

_______________________________________________________________

2. What is thread racing?

_______________________________________________________________

_______________________________________________________________

3. What is an object monitor?

_______________________________________________________________

_______________________________________________________________

4. What is an atomic process?

_______________________________________________________________

5. Name three sophisticated methods for controlling threads.

_______________________________________________________________

_______________________________________________________________

6. When using thread-controlling techniques, which thread is the one you want to control?

_______________________________________________________________

7. What is thread deadlock? How does Java help you avoid deadlock?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 320: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

19-20 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 321: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

20Lesson 20:

Streams and Serialization

Objectives By the end of this lesson, you will be able to:

� Define a stream.

� Differentiate between byte streams and character streams.

� Recognize the abstraction of byte streams through the InputStream and OutputStream classes.

� Recognize the abstraction of character streams through the Reader and Writer classes.

� Create and use file objects.

� Use System.in and System.out to perform stream operations.

� Nest streams using wrapper classes to enhance basic stream behavior.

� Perform file I/O.

� Define object serialization.

� Use serialization to save an object to a file, then deserialize the object.

� Explain the transient keyword and issues relative to security.

Page 322: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

20-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. Which of the following is not likely to be accessed using a stream?

a. Data within a file b. Input from a keyboard c. Input from a mouse d. Data from a network connection

2. Which of the following is true with respect to the object serilialization?

a. The Serializable interface defines the number of methods that must be implemented in order for an object to be eligible for serialization

b. When an object is serialized, any object references it maintains are followed and such objects are serialized only if they implement the Serializable interface

c. Object serialization is the process by which data is extracted from an input stream and used to create an object

d. Variables marked with the transient keyword can be serialized.

3. What is wrapper stream?

_______________________________________________________________

_______________________________________________________________

Page 323: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 20: Streams and Serialization 20-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

What Is a Stream? A stream is a path of information from a source to a destination. Though somewhat vague, it is a widely applicable concept.

Some examples of elements that form a path of communication between a source and a destination are:

• A keyboard (source) and a monitor (destination).

• A page of text on a monitor (source) and a file on a hard drive (destination).

• A file on a hard drive (source) and a monitor (destination).

• A Web server (source) and a browser (destination).

• A keyboard (source) and a string (destination).

• A text file (source) and a printer (destination).

It may seem daunting that you should have to develop various programming mechanisms to handle the many stream possibilities. In truth, you do not. The process of streams is a well-abstracted concept. Java takes advantage of this abstraction and provides a rich set of classes to handle a wide variety of stream situations.

Because of the flexibility in the ways that streams can be used, Java provides dozens of stream classes. Consider that C provides only one type of stream, and Visual Basic provides three. However, by providing solid guidelines for handling a specific stream situation, your Java code will be more robust and have fewer errors.

Although dozens of streams exist, you need not learn the more than 50 different classes. Streams are well-organized and can be classified as one of four types: InputStream, OutputStream, Reader and Writer.

stream

A path of

information from a

source to a

destination.

Page 324: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

20-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

InputStream, OutputStream, Reader and

Writer With the introduction of the JDK 1.0, all streams in Java were subclasses of either InputStream or OutputStream.

InputStream is an abstract class, but it provides the framework from which all other input streams are derived. At the core of InputStream is the read method. The basic read is abstract, but for the subclasses that extend InputStream, the method will simply read a byte of information from a stream and return the byte as an integer.

OutputStream is an abstract class, and like InputStream, it provides the framework from which all other output streams are derived. At its heart is the write method, which gets an integer and writes a single byte of information to an output stream. All other stream output is simply a variation of InputStream and OutputStream. You will see many variations of the read and write methods, but remember that they are only variations; the basis of input and output with the JDK 1.0 are the abstract classes InputStream and OutputStream.

If all streams can be represented as variations of the InputStream and OutputStream, then what are the Reader and Writer classes?

An earlier lesson stated that Java takes an international approach to its characters: It adapted a 16-bit representation of characters referred to as Unicode. The problem with InputStream and OutputStream in JDK 1.0 is that they were not designed to handle Unicode, and for those classes that attempted to handle Unicode, it was an incomplete solution.

The InputStream and OutputStream classes are designed to handle byte streams, while the Reader and Writer classes are designed to handle character streams. In fact, the abstract Reader and Writer classes serve the same role in character streams as the InputStream and OutputStream classes serve in byte streams. All other Reader and Writer streams are merely subclasses (and thus variations) of these two.

One question remains: When do you use byte streams and when do you use character streams?

InputStream

The abstract class

from which all other

input byte streams

are derived.

OutputStream

The abstract class

from which all other

output byte streams

are derived.

Reader

The abstract class

from which all other

input character

streams are derived.

Writer

The abstract class

from which all other

output character

streams are derived.

Page 325: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 20: Streams and Serialization 20-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Most Internet communication uses byte streams, not character streams. United States users rely heavily on byte streams and 8-bit ASCII . There seems to be little reason to use character streams. However, the JDK 1.1 (and later versions, including SDK 1.2) have deprecated some of the many useful constructors and methods found in the byte stream classes. Therefore, because the character streams can readily handle byte streams, one could argue the logic of using character streams when it is known that both the sender and receiver are prepared to handle character streams.

Files Files are used heavily with streams in reading and writing to disk, yet a file is not a stream.

Files are encapsulated by the File class. Once you have an instance of a file object, you can find the length of the file, determine whether the file is readable or writable, rename the file, and so forth. With a file object, you can also create directories or obtain directory listings. The File class is useful, but it can be troublesome.

The trouble comes at the price of Java's cross-platform functionality. How can you incorporate the many ways of expressing directories and the different file separators across platforms?

The easiest solution is to always use the FileDialog class you used earlier. FileDialog will automatically respect the file conventions on the local system. Beyond this, you must do some work.

ASCII

A standard means

to represent

characters as

integers ranging

from 0 to 127.

File

A Java class

abstracting the

nature of a system

file.

Page 326: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

20-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

You will examine the File class to see its many functions and address some of the cross-platform issues. Table 20-1 lists the methods you will use.

Table 20-1: Methods of File class

Method Description

exists Returns a boolean describing whether or not a File exists

canRead Returns a boolean describing whether or not a File can be read

canWrite Returns a boolean describing whether or not a File can be written to

getPath Returns a String with the path of the File

getFile Returns a String with the name of the File

getAbsolutePath Returns a String with the absolute path of the File

mkdir Creates a directory from a File object

Instantiating a File object

You can instantiate a File object with the following syntax:

File myFile = new File("SomeFile.txt");

In this case, you are creating a File object in the current directory of your program. If you wanted to specify a file in a different directory, you should be careful.

On a Windows system, you can create a File object in another directory as follows:

File myFile = new File("/MyDocs/Java/SomeFile.txt"); File myFile = new File("\\MyDocs\\Java\\SomeFile.txt"); File myFile = new File("C:\\MyDocs\\Java\\SomeFile.txt");

Notice that you had to use double backslashes in the

second and third examples. Java strings use the backslash character as an escape character. Two

backslashes are interpreted as a single backslash.

Page 327: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 20: Streams and Serialization 20-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Windows is very flexible. Other systems are not, however, and you may have to use syntax such as the following:

String myTmpFile = "/MyDocs/Java/SomeFile.txt"; myTmpFile = myTmpFile.replace ('/', File.separatorChar); File myFile = new File(myTmpFile);

Working with a File object

Once you have your File object, you can use it for many functions.

Methods of File

The following code demonstrates a few examples of methods you can use with File. Assume that you have a file called SomeFile.txt in your local directory that has some text in it.

import java.io.*; class FileTests { public static void main(String[] args) { File myFile = new File("SomeFile.txt"); System.out.println("Exists:" + myFile.exists()); System.out.println("Can Read:" + myFile.canRead()); System.out.println("Can Write:" + myFile.canWrite()); System.out.println("Path:" + myFile.getPath()); System.out.println("Name:" + myFile.getName()); System.out.println("Absolute Path:" + myFile.getAbsolutePath()); System.out.println("Length:" + myFile.length()); } }

Directories

The File object is also the means by which you create directories and make directory listings.

If you want to make a directory called MyDirectory beneath your current directory, you can create a File object with the name of the directory you want, then call the mkdir command as follows:

File myDirectory = new File("MyDirectory"); myDirectory.mkdir();

Page 328: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

20-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

If you want a listing of all files in a directory, you can again use the File object. In the following example, you make a listing of your local directory:

File myLocalDir = new File("."); String[] dirListing = myLocalDir.list(); for(int i = 0;i<dirListing.length;i++) { System.out.println(dirListing[i]); }

FileDialog (revisited)

In the discussion of the AWT, you learned how to instantiate a FileDialog and display it. Now you will learn how to work with the FileDialog class's ability to deliver a file name.

Recall that to cause a FileDialog to pop up (once you instantiate), you can instruct it to display itself as follows:

FileDialog fileDialog = new FileDialog(this, "My Dialog",FileDialog.LOAD); fileDialog.setVisible(true); // ... on to the next line in the program...

At this point, assuming the FileDialog is modal, the pop-up window will appear and wait for the user to respond. Once the user has selected the file, the program flow returns to the next line in the program, from which you get the file name as shown:

// ... the next line in the program after the user has // selected a file. // Get the absolute path of the file name in case the // user browses to a directory other than the // current one. String myFile = fileDialog.getDirectory() + fileDialog.getFile();

Now the program has the absolute file name.

Page 329: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 20: Streams and Serialization 20-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Stream Classes of java.io.* It is difficult to provide a class hierarchy for the stream classes. Because they vary so greatly, Table 20-2 lists only the more common ones.

Table 20-2: Useful stream classes

Class Description Useful Methods

Classes for Byte Streams – JDK 1.0

InputStream The superclass for all other byte input streams

read—an abstract method that reads a byte and returns it as an int

OutputStream The superclass for all other byte output streams

write—an abstract method that writes an int representation of a byte

PrintStream An effective stream for writing lines of text to an output stream

println—a useful method for outputting text formats

DataInputStream An input stream filter class that allows formatting for incoming byte information

readLine—creates a line of text (deprecated)

BufferedInputStream An input stream filter class for adding buffering to input streams

read—reads a specified byte length into its buffer

FileInputStream Creates an input stream from a File

read—reads a byte of information from a File

LineNumberInputStream An input stream filter class that counts the number of lines read

read—reads the byte stream tracking the lines read

getLineNumber—returns the number of lines read

Page 330: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

20-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Table 20-2: Useful stream classes (cont'd)

Class Description Useful Methods

Classes for Character Streams – JDK 1.1 and later

Reader The superclass for all other character input streams

read—an abstract method that reads a Unicode character from an input stream

Writer The superclass for all other character output streams

write—an abstract method that writes a Unicode character to an output stream

PrintWriter An effective stream for writing lines of text to an output stream

println—a useful method for writing to a character output stream in text format

BufferedReader An input stream filter class for adding buffering to input streams

read—reads a specified character length into its buffer

InputStreamReader A converter class that converts byte streams to character streams for input

read—reads a byte from a byte stream and converts it into a character stream

FileReader Creates an input stream from a file read—reads a character from a File

OutputStreamWriter A converter class that converts byte streams to character streams for character output

write—writes a character to an output character stream

FileWriter Creates an output stream to a file write—writes a character to a file

LineNumberReader An input stream filter class that counts the number of lines read

read—reads the character stream tracking the lines read

getLineNumber—returns the number of lines read

All Stream Classes

flush Used with Writer and OutputStream classes to force any buffered bytes out

Must be used to see any output; ensures that output streams are flushed

close Closes input or output streams and frees system resources, which are limited

Automatically flushes output streams

Page 331: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 20: Streams and Serialization 20-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

System.in and System.out

To gain experience with streams, you should practice with them. Fortunately, Java provides the equivalent of standard input (STDIN) and standard output (STDOUT) in other programming languages: System.in and System.out.

System.in is an InputStream whose source is the keyboard. Keys pressed on the keyboard are made available to the System.in stream. System.out is an OutputStream (in fact, it is the PrintStream) whose output is the display monitor. You have been able to use commands such as System.out.println("text") because System.out, being an instance of PrintStream, has a method called println that takes a String as a parameter.

You will use the System.in and System.out streams to practice with stream concepts.

Reading bytes from System.in

The most fundamental use of a byte input stream is reading bytes via the read method. You will notice with input/output (I/O) operations in general that you are often forced to deal with exceptions. This demand is reasonable if you consider all that can go wrong with I/O, including disabled networks, faulty hard drives, and so forth. The following application reads information from the system input stream. It works when you run the application then enter alphanumeric characters. You must press ENTER after each character whose stream you want to read. This application will read byte information you enter, then return the byte as an int. The result is that you will see ASCII values for each character you enter. Study the following code:

import java.io.*; class StreamExample01 { public static void main(String[] args) { // Access the System.in InputStream InputStream is = System.in; try { int i; // Loop until the letter 'q' is hit while((i = is.read()) != 113) { System.out.println(i); } is.close(); } catch(IOException e)

System.in

Java's version of

standard input

(usually the

keyboard).

System.out

Java's version of

standard output

(usually the

monitor).

Page 332: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

20-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

{ System.out.println("main(): " + e); } } }

Following is sample output for StreamExample01:

d <ENTER> 100 13 10 r <ENTER> 114 13 10

Oddly enough, this output is correct. Recall that the read method of this application reads a byte from the input stream, and returns the byte as an int. When you typed d then pressed the RETURN key (to flush the stream), you saw the ASCII integer representation of the letter d (which is 100), then 13 and 10, which stand for \r and \n (escape characters for the return and new line end-of-line terminators used by Windows). Finally, you exited the while loop by entering integer 113, which is the ASCII value for the letter q.

If you want to see the ASCII character output instead of the integers, modify the code and cast the int into a char as follows:

System.out.println((char) i);

After casting the int i as a char, you receive the following output:

d d r r

Now you see the appropriate characters (with the new line characters).

Page 333: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 20: Streams and Serialization 20-13

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Of course, as programming becomes more international, Java's use of Unicode and the deprecation of some more useful byte stream classes, constructors and methods, you must consider the character stream classes as your staple approach to input/output.

Converting a byte stream into a character stream

Most of the Reader and Writer classes (character stream classes) cannot work with byte streams and must use character streams. Java provides the necessary framework to convert a byte stream into a character stream via InputStreamReader and OutputStreamWriter. InputStreamReader converts a byte stream into a character stream for input, while OutputStreamWriter allows you to specify a byte stream to which you can direct your character stream.

This conversion is natural as shown by the following example. Although you see no apparent difference between this example and the previous example, remember the end result: Program output is now a character stream that transmits Unicode, instead of a byte stream that transmits bytes. Consider the following example:

import java.io.*; class StreamExample02 { public static void main(String[] args) { InputStream is = System.in; InputStreamReader isr = new InputStreamReader(is); try { int i; while((char)(i = isr.read()) != 'q') { System.out.println((char)i); } isr.close(); } catch(IOException e) { System.out.println("main(): " + e); } } }

InputStreamReader

A utility stream that

converts a byte

stream into a

character stream

for input.

OutputStreamWriter

A utility stream that

converts a

character stream

into a byte stream

for output.

Page 334: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

20-14 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Wrapper streams

Rarely would you want to work with individual characters; typically, you want to read in lines of text. Java provides a clever approach to this need by allowing you to wrap streams within streams (via the constructors) to gain the results you seek. The streams you use to wrap other streams are not really streams themselves; they are actually filter classes that use a raw stream to produce formatted results.

In the two previous examples, you were able to read only one character at a time. If you want to read a whole line at a time, then you must use a wrapper class. In this case, you need to use the BufferedReader class.

The BufferedReader class offers two elements. The first is a method called readLine, which will read entire lines of text from a character stream. The second element offered is buffering. Buffering delivers an efficiency that non-buffered streams cannot. A buffered stream will read (or write) information into a buffer. Once the buffer is filled, subsequent reads or writes will come from the buffer, instead of making repeated system reads or writes. System reads and writes are expensive; these operations consume far fewer resources if performed from a buffer. Streams should almost always be buffered.

Study Figure 20-1 to help you understand this wrapper approach.

InputStream/System.in

InputStreamReader

BufferedReader

Figure 20-1: Wrapper streams

The following code implements the wrapper stream approach:

import java.io.*; class StreamExample03 { public static void main(String[] args) { // Notice the nesting of streams InputStream is = System.in; InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); try { String s = null; // For a String you test for null

wrapper class

A class that wraps

around other stream

classes to add

functionality.

Page 335: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 20: Streams and Serialization 20-15

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

while((s = br.readLine()) != null) { System.out.println(s); } br.close(); } catch(IOException e) { System.out.println("main(): " + e); } }

Following is sample output for Example03:

Once upon a time... Once upon a time... ... there was a fairy princess... ... there was a fairy princess...

File I/O

Reading and writing to a file is one function you can perform with streams. In this example, you will read from one file then write to a second. In essence, you are making a copy of the first file. You will need several more classes.

The FileReader and FileWriter classes allow you to read and write a raw character stream to and from a file. However, you will also need to format the input and output for line input and output. You have already been introduced to the BufferedReader for the purpose of reading a line of text. The PrintWriter will allow you to write a line of text to the output stream (and thus, the File). This stream is not buffered; you can add buffering if you want.

For this example, assume there exists a text file called input.txt. The output file will be called output.txt.

Page 336: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

20-16 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Notice that the FileReader and FileWriter classes must be instantiated inside of a try/catch block. You chose to instantiate the BufferedReader and PrintWriter classes in the try/catch because they are dependent on the FileReader and FileWriter classes. Study the following code:

import java.io.*; class StreamExample04 { public static void main(String[] args) { File input = new File("input.txt"); File output = new File("output.txt"); FileReader fr = null; BufferedReader br = null; FileWriter fw = null; PrintWriter pw = null; try { // fr and fw must be declared in a try/catch // block. fr = new FileReader(input); fw = new FileWriter(output); br = new BufferedReader(fr); pw = new PrintWriter(fw); String s; while((s = br.readLine()) != null) { pw.println(s); // Don't forget to flush the output stream. pw.flush(); } // Don't forget to close your streams. br.close(); pw.close(); } catch(IOException e1) { System.out.println("main(): " + e1); } } }

Here, you read text from a file and saved that text to another file. In the next section, you will see that Java also delivers the means to read and write complete object streams.

Page 337: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 20: Streams and Serialization 20-17

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Serialization In a typical object-oriented system, objects are instantiated and their internal states are modified. After an object has reached a certain state, it might be perfectly acceptable that all the information is lost when the system is stopped. However, if you want to save the state of an object (or many objects), then you need a solution.

Several solutions can make an object persistent. One approach is to use force. If you have an object of a certain type, you must be able to save its type, its internal information, and information regarding references to other objects. You would save this information to a file via a file output stream. When you need to deserialize the object, you could read in the information you saved, and reconstruct the object and its state. This process is called serialization, and it was used by Java programmers in the first release of the JDK 1.0. With the release of JDK 1.1, Java provides a means of serialization that is effective and much easier to implement than the forced method.

The applications for serialization are endless. The ability to use objects across virtual machines is primary. RMI (the Java version of a distributed object system/protocol) offers this ability. JavaBeans also use serialization regularly. Sophisticated, graphical beans must be saved upon creation to be used at a later time. Some graphical IDEs can save the interface created by the user via serialization. With the flexibility that objects and the object-oriented paradigm provide in system design, the ability to make these objects and systems persistent is a powerful and useful mechanism.

The process of object serialization

Object serialization requires several steps, including marking an object for serialization, writing the object to a file, and reading the object from a file.

Marking an object for serialization

Although serialization is part of the Java language, Java will assume that you do not want an object to be serialized unless you mark it as such. To mark an object as serializable, you must implement the Serializable interface as shown:

import java.io.*; class SampleObject implements Serializable { // You will implement some sample code with this // sample object. String name; int age;

persistent

The ability to

maintain a prior

state.

serialization

The process of

maintaining an

object's state by

converting it into a

byte stream.

Serializable

interface

A Java interface

that marks an

object to be

serialized.

Page 338: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

20-18 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAge(int age) { this.age = age; } public int getAge() { return age; } }

The Serializable interface itself is as follows:

public interface Serializable { }

This code introduces an important programming practice. You will often want to tag an object as a certain type without specifying any functionality.

Writing the object to file

In your example, you are going to save your SampleObject to file. You can send your object anywhere that you would normally direct an output stream.

To write an object to a stream, use the ObjectOutputStream class. This class is simply a wrapper class like those you have used before. It wraps a normal OutputStream (not a Writer stream). You will use the ObjectOutputStream to wrap a FileOutputStream . You then will use the writeObject() method of the ObjectOutputStream class to serialize the object, as follows:

import java.io.*; class Main { public static void main(String[] args) { try { // Get an instance of the SampleObjects and // set their state. SampleObject originalObj1 = new SampleObject(); SampleObject originalObj2 = new SampleObject();

Page 339: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 20: Streams and Serialization 20-19

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

originalObj1.setName("Mary Smith"); originalObj1.setAge(32); originalObj2.setName("John Doe"); originalObj2.setAge(42); // To write the object, you will need a // FileOutputStream and an ObjectOutputStream. FileOutputStream fos = null; ObjectOutputStream oos = null; fos = new FileOutputStream("SerializedObj.obj"); oos = new ObjectOutputStream(fos); oos.writeObject(originalObj1); oos.writeObject(originalObj2); oos.close(); } catch(Exception e) { System.out.println("Main: main(): " + e); } } }

Saving the serialized object as the file SerializedObj.obj was arbitrary, including the file extension. Also, note that you are catching the exception using Exception. This step is rarely recommended (being so general), but there are many exceptions to catch in these examples, and it is worthwhile to focus on the topic of discussion.

Reading the serialized object from a file

Once you have a serialized object saved to disk, you can read it in the same way that you wrote it. Instead of a FileOutputStream, you now need a FileInputStream, and instead of an ObjectOutputStream, you have an ObjectInputStream. Study the following code:

import java.io.*; class Main { public static void main(String[] args) { try {

// Get an instance of the SampleObjects // and set their state. SampleObject originalObj1 = new SampleObject();

SampleObject originalObj2 = new SampleObject(); originalObj1.setName("Mary Smith"); originalObj1.setAge(32); originalObj2.setName("John Doe");

Page 340: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

20-20 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

originalObj2.setAge(42); // To write the object, you will need a // FileOutputStream and an ObjectOutputStream. FileOutputStream fos = null; ObjectOutputStream oos = null; fos = new FileOutputStream("SerializedObj.obj"); oos = new ObjectOutputStream(fos); oos.writeObject(originalObj1); oos.writeObject(originalObj2); oos.close();

// To read the objects, you will need a // FileInputStream and an ObjectInputStream. FileInputStream fis = null; ObjectInputStream ois = null; fis = new FileInputStream("SerializedObj.obj"); ois = new ObjectInputStream(fis); SampleObject newObj1 = (SampleObject) ois.readObject(); SampleObject newObj2 = (SampleObject) ois.readObject(); ois.close(); // And the results... System.out.println("SampleObject1 name: " +

newObj1.getName()); System.out.println("SampleObject2 name: " +

newObj2.getName()) } catch(Exception e) {

System.out.println("Main: main(): " + e); }

} }

Two points should be noted about the preceding example:

• You must read the objects from the file created by an object stream in the same order that you wrote them.

• Because the readObject method returns an Object, you must perform an explicit cast the moment you read the Object from the object stream. For example:

SampleObject newObj1 = (SampleObject) ois.readObject(); SampleObject newObj2 = (SampleObject) ois.readObject();

Page 341: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 20: Streams and Serialization 20-21

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

These steps are necessary if you want to use the methods available with this typed object. However, keep in mind that you should always monitor the types of objects you are reconstituting. As your serialized systems become bigger (and less manageable), you should consider other ways of determining object type.

The objects originalObj1 and newObj1 do not occupy the same memory space. One object will not affect the other. Of course, the same is true for originalObj2 and newObj2.

Transient variables and security

Within an object marked as serializable, you may not want some variables to be put into a persistent state. For example, you might have a variable in your object that always depends on the current system date. In such a case, it is useless to serialize this date variable because it will have no meaning when the object is deserialized. You can prevent an instance variable from being serialized by using the transient keyword. Consider the following example:

import java.util.*; class TrivialObject implements Serializable { transient Date currentDate; transient private int accountID; }

In this code, you made the currentDate variable transient because it relies on the current date and need not remember any past dates. But is the accountID variable also persistent?

One of the disadvantages of serialization is that private members are also serialized. In essence, this information can be exposed or corrupted during the serialization process (and you should never underestimate the desire or ability of others to gain access to this information). Therefore, a programmer may choose not to serialize the accountID variable. A TrivialObject instance would have to obtain the accountID in some other way.

One final note: Static variables are (by default) not serializable. The transient keyword has no significance with a static variable.

transient

A keyword used to

mark members that

will not be serialized.

Page 342: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

20-22 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lab 20-1: Creating a simple word processor in Java

The ability to handle I/O is a staple element in any programming language. In this lab, you will perform I/O with strings by creating a simple word processor to read a text file's contents to a JTextArea. Additionally, you will be able to save the contents of the JTextArea to a file under a different name. The contents of the JTextArea will be cleared as well.

1. Create a class called WordProcessor that extends JFrame. This class will serve as the GUI for your word processor and should resemble Figure 20-2.

JTextAreawithin aJScrollPane

Figure 20-2: Word processor GUI

Note: You should use the FileReader, BufferedReader, FileWriter and PrintWriter classes for Steps 2 and 3.

2. Event-enable the Open button. Upon clicking this button, a JFileChooser should appear in "open" mode starting with your root directory (c:\ on a Windows system). Selecting (or typing) a text-based file to open will output its contents into the JTextArea.

3. Event-enable the Save button. When this button is clicked, a JFileChooser should appear in "save" mode starting with your root directory (c:\ on a Windows system). Selecting (or typing) a file name will save the contents of the JTextArea to the hard drive under that chosen file name.

4. Event-enable the Clear button. When this button is clicked, the contents of the JTextArea will be cleared.

Page 343: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 20: Streams and Serialization 20-23

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

Java's stream classes provide a unified method for accessing and transmitting data to the numerous input sources and output destinations. Describe how the use of nested streams facilitates code reuse. In particular, what data sources and destinations can be used in object serialization?

Skills review

Although many different streams exist, they can be easily organized into several broad categories. The differences depend on the type of data that each stream manipulates and the direction of the stream (input or output). In this lesson, you worked with primitive data types and strings. You also learned to save the persistent state of an object using serialization. Although you saved object states to a file, you will learn in the next lesson that the same streams can be sent across a network, enabling the implementation of your chat server.

Now that you have completed this lesson, you should be able to:

� Define a stream.

� Differentiate between byte streams and character streams.

� Recognize the abstraction of byte streams through the InputStream and OutputStream classes.

� Recognize the abstraction of character streams through the Reader and Writer classes.

� Create and use file objects.

� Use System.in and System.out to perform stream operations.

� Nest streams using wrapper classes to enhance basic stream behavior.

� Perform file I/O.

� Define object serialization.

� Use serialization to save an object to a file, then deserialize the object.

� Explain the transient keyword and issues relative to security.

Page 344: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

20-24 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 20 Review

1. What is a stream?

_______________________________________________________________

2. What are the four types of streams in Java?

_______________________________________________________________

_______________________________________________________________

3. How do byte streams differ from character streams?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

4. What two classes create the abstraction of character streams? What two classes create the abstraction of byte streams?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

5. How does Java allow you to use streams with files?

_______________________________________________________________

_______________________________________________________________

6. What are System.in and System.out in Java?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 345: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 20: Streams and Serialization 20-25

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

7. What framework does Java provide to convert byte streams into character streams so that Reader and Writer classes can work with them?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

8. What is a wrapper class?

_______________________________________________________________

9. What is object serialization?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

10. What is the purpose of the transient keyword?

_______________________________________________________________

Page 346: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

20-26 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 347: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

21Lesson 21:

Networking in Java

Objectives By the end of this lesson, you will be able to:

� Define networking, IP addresses, the Domain Name System, and ports.

� Discuss the socket model and socket-to-socket communication.

� Explain the client/server model and how it relates to socket-to-socket communication.

� Write a single-threaded client/server echo system.

� Write a multithreaded client/server echo system.

Page 348: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

21-2 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Pre-Assessment Questions

1. Which of the following is true with respect to servers written in Java?

a. A server makes use of both a ServerSocket and a Socket. b. Most servers are single threaded. c. A server can have only one active connection at a time. d. A server written in Java can accept network connections only from

other Java programs.

2. Which of the following is true with respect to clients written in Java?

a. A client makes use of both a ServerSocket and a Socket. b. A client can have only one active connection at a time. c. A client written in Java can initiate a network connection only with

other Java programs. d. A single application can act as both a server and a client.

3. What is a socket?

_______________________________________________________________

_______________________________________________________________

Page 349: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 21: Networking in Java 21-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

What Is Networking? Essentially, networking is the ability for computers to communicate with each other. To connect systems into a network, you need network interface cards (NICs), a physical wire, a networking protocol such as TCP/IP, and applications capable of sending packets onto the wire. Internetworking involves the use of routers, switches, and other equipment. As with other languages, Java allows you to work with local area networks (LANs), wide area networks (WANs), intranets, and the Internet. Needless to say, networking is a very broad field. Networking in Java is a very specific subset of networking: socket-to-socket communication using TCP/IP.

Connecting Computers Across

the Internet The Internet is often called a "network of networks." This definition is appropriate if you consider networking as communication among computers because the Internet involves millions of interconnected computers. With such a large network, how can one computer possibly find another computer? Computers find each other using Internet Protocol (IP) addresses.

IP addresses

IPv4 is the most common protocol on the Internet today. In this version, IP addresses are 32 bits long, consisting of four sections separated by decimal points and known as "dotted quads," each between 0 and 255. For example:

207.60.58.44

If a computer were assigned this IP address, then this IP address would be unique to that computer. Any other computer in the world could find this individual computer on the Internet. Using four groups of numbers, each ranging from 0 to 255, means that approximately 4 billion IP addresses can be assigned. In the not-too-distant future, this provision will no longer be adequate. A proposal for a new version of IP, called IPv6, calls for an expanded addressing scheme consisting of eight fields separated by colons, or 128 bits of address space, resulting in approximately 4 trillion possible IP addresses.

Of course, most people prefer not to think in numbers. It is easier to remember words (such as www.ciwcertified.com) than IP addresses (63.72.51.85). This word-based scheme is made possible by the Domain Name System (DNS).

networking

Communication

among computers.

Internet Protocol (IP)

address

The numerical

address assigned to

a specific computer

and used by the

Internet to transfer

information.

Domain Name

System (DNS)

A system that

converts domain

names into

corresponding IP

addresses.

Page 350: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

21-4 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

DNS

DNS servers can be found throughout the Internet, as well as in LANs, WANs and intranets. DNS servers translate domain names into IP addresses. Therefore, if you want to connect to a computer over the Internet, you would probably use a domain name such as www.javasoft.com instead of its IP address, which is 192.18.97.71. You can enter http://www.javasoft.com in your browser, and a DNS server translates it to http://192.18.97.71. This scheme accommodates people and computers because the two representations are interchangeable.

Now that you know how to identify a unique computer on the Internet, how do different computers make contact with each other? They do this by using sockets.

Sockets

Sockets are not physical devices, but they establish the way in which one computer can connect to another computer.

The model of socket-to-socket connections was established in the early 1980s and was so well-received that it thrives to this day, especially in relation to the Internet. A socket on one computer can establish a connection to a socket on another computer. A socket consists of two elements:

• The IP address (or domain name) of the socket on the computer.

• The port number of the socket on the computer.

We have already discussed IP addresses, but what are ports?

If an IP address identifies a unique computer on the Internet, a port number identifies a unique application executing on that computer. A port is like a channel or path for input and output within a socket. The port is represented by an integer ranging from 0 to 65535. The port numbers 0 to 1023 are reserved (sometimes referred to as well-known ports) and are not available for general use. You may already be familiar with some of these reserved ports. Table 21-1 lists some common ports and the protocols for which they are reserved.

port

An integer from 0 to

65535 representing

a particular path for

information flow.

Page 351: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 21: Networking in Java 21-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Table 21-1: Well-known ports and their protocols

Port Protocol

21 FTP

23 Telnet

25 E-mail

79 Finger

80 HTTP

119 NNTP/Usenet

Consider Figure 21-1. How can Socket A establish a connection with Socket B?

Computer A

Socket A

in out in out

port 2010 port 80

Computer B

Socket B

in out in out

port 5001 port 80

IP 201.58.40.32 IP 198.20.98.1

Figure 21-1: Connecting Computer A to Computer B

If Computer A knows of another computer with a socket listening at IP address 198.20.98.1 on port 80, then it can establish a connection using the prearranged protocol (in this case HTTP). This type of connection is made routinely within a Web browser.

The following is a fully qualified URL that includes the port number:

http://www.javasoft.com:80

Page 352: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

21-6 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Normally you do not specify the port number because port 80 is assumed for HTTP. If you are using a different port, however, you must specify it.

Once the connection is established at the proper IP port, the two sockets can exchange information by mutually exchanging input and output streams, using the agreed-upon protocol. Transmission Control Protocol/Internet Protocol (TCP/IP) is a high-level/low-level protocol combination and is the accepted protocol for Internet communication.

Networking Classes of java.net.* The class hierarchy of the java.net.* package does not present essential information. Therefore, Table 21-2 offers some of the more common networking classes you will use in this course.

Table 21-2: Common networking classes

Class Description Useful Methods

InetAddress Represents both the IP address and domain name of an Internet address

GetLocalHost—returns an InetAddress object representing the local host

GetHostName—returns a String representing the host name being associated with the InetAddress object

Socket Abstracts the client-side version of a socket (uses the IP address and port of the sought-after server socket)

GetInetAddress—returns the InetAddress object associated with the socket

GetInputStream—returns an InputStream associated with the server's output stream

GetOutputStream—returns an OutputStream associated with the server's input stream

close—closes the client's socket and any opened streams

ServerSocket Abstracts the server-side version of a socket (specifies a port and automatically obtains the host computer's IP address)

Accept—a blocking method that waits for a socket connection from a client

Transmission Control

Protocol/Internet

Protocol (TCP/IP)

The set of

networking

protocols used for

the Internet.

Page 353: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 21: Networking in Java 21-7

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The Java Client/Server Model Java uses the socket-to-socket connection model well in its representation of client/server interactions.

A server is any computer that delivers information. Web servers, e-mail servers, FTP servers and print servers are examples. A client is any computer that requests information from a server. Probably the most common client/server model is that of Web browsers (clients) and the Web servers that deliver Web documents. Java responds well to this client/server model and socket-to-socket communication by defining two types of socket classes: Socket and ServerSocket.

In the following example, you will use the Socket and ServerSocket classes to create a client/server echo system. The client will send a message to the server, and the server will echo that message back to the client.

You will also learn how to create a multithreaded system so that the server can respond to more than one client. This task will lay an excellent foundation for fully realizing your chat server project.

Building the EchoServer The EchoServer provides an excellent example of Java's powerful networking capabilities. By studying the EchoServer, you will see the entire client/server interaction implemented in Java. Your course project focuses on the client end; your instructor will provide the server.

The client

The client creates a Socket specifying the IP address and port number of the ServerSocket to which it wants to make a connection. The Socket is activated the moment you instantiate it. There is no need to call any invoking method, as you do with threads.

Once you instantiate the client's Socket, and it makes a connection with the server's ServerSocket, input and output streams will be established. The output stream will allow the client to send information to the server's input stream, while the input stream will allow the client to read information from the server's output stream. Study the following code:

import java.net.*; import java.io.*; class Client extends Thread { Socket socket; DataInputStream in;

Socket

A class in Java that

represents the

socket model for

clients.

ServerSocket

A class in Java that

represents the

socket model for

servers.

Page 354: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

21-8 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

PrintStream out; // You will use the local loopback IP String IP = "127.0.0.1"; int port = 8000; String message; public static void main(String args[]) { Client client = new Client(); // Step 1 client.getConnection(); // Step 2 client.sendMessage(); // Step 3 client.receiveMessage(); } private void getConnection() { try { // Create the client's socket socket = new Socket(IP,port); in = new DataInputStream(socket.getInputStream()); out = new PrintStream(socket.getOutputStream()); } catch(UnknownHostException e) { System.out.println("Client - getConnection():" + e); } catch(IOException e) { System.out.println("Client - getConnection():" + e); } } private void sendMessage() { message = "Hello server!"; System.out.println("Client sent: " + message); out.println(message); } public void receiveMessage() { try { while(true) { // readLine() blocks until input is received. message = in.readLine(); System.out.println("Client Received: " + message); } } catch(IOException e)

Page 355: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 21: Networking in Java 21-9

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

{ System.out.println("Client - receiveMessage():" + e); } } }

Following are the steps as defined in the main method.

Step 1: getConnection

First, the client must establish a connection with the server at a prearranged IP address and port. This connection is attempted automatically upon instantiating the Socket, as shown:

socket = new Socket(IP,port);

This constructor must be in a try/catch block, because the constructor might throw an UnknownHostException or IOException. If the connection is successful, then input streams and output streams can be established with the socket at the server's end, as shown:

in = new DataInputStream(socket.getInputStream()); out = new PrintStream(socket.getOutputStream());

Now you must send the message to the server.

Step 2: sendMessage

Sending the message is very straightforward. You send the text using your output stream as follows:

out.println(message);

Once you have sent the message, you must wait for the response from the server.

Step 3: receiveMessage

The fact that you are waiting for a response in an infinite loop is so common that it is almost a rule. See the following example:

while(true) { // readLine() blocks until input is received. message = in.readLine(); System.out.println("Client Received: " + message); }

Page 356: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

21-10 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Also note that the readLine method is a blocking method, as are many I/O methods. This means that the program flow will wait at that method until it receives some input. Only at that point will the program flow continue. Of course, being in an infinite loop means the program flow will wait then resume repeatedly. You should also note that readLine is deprecated as of Java 1.1. The Java compiler will issue a warning about deprecated elements. Instead, consult the Java API for ways to use BufferedReader, BufferedWriter and readUTF for the client and server.

The client's role is now complete. You will see that the server virtually duplicates the client's actions.

The server

The server's role is nearly identical to the client's. The only difference is that the server uses both a ServerSocket and a Socket. The ServerSocket is a special socket that waits for a client socket to make a connection. Once the connection is received, the ServerSocket creates a Socket of its own to maintain communication with the client's Socket. At this point, your server can launch only one Socket. You will later remedy this situation with multithreading. Study the following code:

import java.io.*; import java.net.*; class Server { ServerSocket server; Socket connection; DataInputStream in; PrintStream out; int port = 8000; String message; public static void main(String args[]) { Server server = new Server(); // Step 1 server.getConnection(); // Step 2 server.receiveMessage(); // Step 3 - sendMessage(() from receiveMessage() }

Page 357: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 21: Networking in Java 21-11

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

private void getConnection() { try { // Create the server socket. server = new ServerSocket(port); // Wait for a client to make a connection. System.out.println("Waiting for client..."); connection = server.accept(); in = new DataInputStream(connection.getInputStream()); out = new PrintStream(connection.getOutputStream()); } catch(IOException e) { System.out.println("Server - getConnection():" + e); } } private void receiveMessage() { try { while(true) { // Block here until a message from Client is // received. message = in.readLine(); sendMessage(); } } catch(IOException e) { System.out.println("Server - receiveMessage():" + e); } } private void sendMessage() { out.println(message); } }

Page 358: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

21-12 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Step 1: getConnection

You can see a tremendous amount of similarity between the getConnection method of the server and the getConnection method of the client. The difference is in the use of the ServerSocket:

server = new ServerSocket(port); System.out.println("Waiting for client connection..."); connection = server.accept(); in = new DataInputStream(connection.getInputStream()); out = new PrintStream(connection.getOutputStream());

The ServerSocket is instantiated with a port number. You may wonder why you do not specify an IP address. The IP address is taken directly from the host computer, so it is not necessary to specify it.

The ServerSocket then waits for a client connection:

connection = server.accept();

The accept method is a blocking method that waits for the client's connection, and returns a Socket (for the server to use) once the connection is made.

Once the server's socket is created to communicate with the client's socket, the process is identical to the client's in terms of getting input and output streams.

Step 2: receiveMessage

Notice that this step is not synchronized with the client's process. The server must wait for a message from the client before it returns the message, as shown:

while(true) {

// Block here until a message from Client is // received. message = in.readLine(); sendMessage();

}

Step 3: sendMessage

Once a message is received from the client, the server sends it back as called from the previous receiveMessage method:

private void sendMessage() {

out.println(message); }

Page 359: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 21: Networking in Java 21-13

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Running the client/server example

The problem with this client/server example is that nothing is threaded, and if you were to test it using a single process, it would lock up. To run it, both the client and the server must be run in their own processes. Therefore, take the following steps:

1. Open two separate DOS windows (in Windows).

2. In the first DOS window, start the server (you must do this before you start the client):

java Server

3. In the second DOS window, start the client:

java Client

Your program should run.

Multithreading Your Client/Server

Example You can perform some minor modifications so that your client/server example is able to handle multiple clients simultaneously. To do this, you will change the role of your server slightly and add an additional class.

The server's role changes because all it needs to do now is wait for a new client connection. It then passes that connection to another object, which will handle this unique client connection. The server will now run an infinite loop waiting for new client connections.

The new client connections will be passed from the server to a new class (which you will write) called Connection. This Connection class simply assumes the role that the server performed in our original example: It communicates back to the client. The fact that the server can distribute many client connections to many Connection objects means that you can create a multithreaded client/server system.

Page 360: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

21-14 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Modifications to the server

• Run the getConnection method into an infinite loop.

• Pass any client connections to a Connection object (not yet written) as shown:

import java.io.*; import java.net.*; class Server { ServerSocket server; int port = 8000; public static void main(String args[]) { Server server = new Server(); server.getConnection(); } private void getConnection() { try { server = new ServerSocket(port); while(true) { System.out.println("Waiting for client.."); new Connection(server.accept()); } } catch(IOException e) { System.out.println("Server - getConnection():" + e); } } }

You can see that the server code has been simplified. Any real work by the server must now be performed on behalf of the Connection.

Page 361: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 21: Networking in Java 21-15

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

The Connection class

The Connection class will receive the Socket just established with the client from the server.

Once the Socket is received, this server duplicates the previous actions of the non-threaded server by getting input and output streams, and maintaining a connection with the client. Notice that the code you place in the body of the thread (in the run method) is the code that is continuously waiting for a message from the client. The fact that it continuously waits is a strong suggestion that this code should be threaded. Study the following code:

import java.io.*; import java.net.*; class Connection extends Thread { Socket connection; DataInputStream in; PrintStream out; String message; Connection(Socket connection) { this.connection = connection; try { in = new DataInputStream(connection.getInputStream()); out = new PrintStream(connection.getOutputStream()); } catch(IOException e) { System.out.println("Connection - Connection(): " + e); } start(); // call the run() method } public void run() { try { while(true) { message = in.readLine(); sendMessage(); } }

Page 362: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

21-16 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

catch(IOException e) { System.out.println("Connection - run(): " + e); } } private void sendMessage() { out.println(message); } }

The Client class

You have the option of threading the Client class as well. It can be done the same way as the Connection class; that is, you can convert the receiveMethod in the body of a thread. In this example, however, it is not necessary because you start a new process for each Client.

Running the threaded client/server example

1. Open three separate DOS windows (in Windows).

2. In the first DOS window, start the server (you must do this before you start the client):

java Server

3. In the second DOS window, start the client:

java Client

4. In the third DOS window, start another client.

You now have a multithreaded client/server example.

Page 363: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 21: Networking in Java 21-17

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lab 21-1: Building a client/server chat system

Your chat project focuses on the creation and implementation of the client; the server is provided for you. In reality, the client and server are virtually mirrors of each other in terms of functionality. Therefore, to understand the client is to understand the server. Creating an actual client/server connection is a valuable skill that must be practiced. In this lab, you will create the client side of the client/server chat system. The compiled server is included on the supplemental files CD.

1. Create a class called ClientGUI that extends JFrame. This class will serve as the GUI for your client and should resemble Figure 21-2.

One JTextArea withinone JScrollPane

One JTextField

Figure 21-2: Client GUI

Note: Your instructor should have the server running at his or her station. Be sure to obtain the port number and IP address of the server to make the connection in Step 2.

2. In your ClientGUI class, write the code such that when the ClientGUI is first instantiated, it creates a socket-to-socket connection with the server so that messages can be sent back and forth.

Hint: This function is similar to the getConnection method of the EchoServer.

Page 364: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

21-18 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

3. Event-enable the Send button such that when clicked, any text in the JTextField will be sent to the server to be broadcast to all connected clients.

Hint: This function is similar to the sendMessage method of the EchoServer.

4. In your ClientGUI class, write the code such that any string-based messages sent by the server are received and displayed in the JTextArea of your client.

Hint: This function is similar to the receiveMessage method of the EchoServer.

5. (Optional) Any message that you send should be prefaced with your name so others will know who sent it.

6. (Optional) When the Send button is clicked, the JTextField should be cleared of its contents, and it should receive the focus of the mouse awaiting entry of the next message (consult your API).

7. (Optional) Instead of clicking the Send button, the user should be able to press the ENTER or RETURN key on the keyboard to send the message.

Page 365: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 21: Networking in Java 21-19

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson Summary

Application project

As you learned in an earlier lesson, Java applets face many security restrictions. One such restriction prevents applets from opening network connections with any computer other than the machine from which the applet is downloaded. Consider how this restriction improves security for applet writers and facilitates the code reuse.

Skills review

In this lesson, you learned the basics of networking and socket-to-socket communication in Java. You learned about the Java client/server model and how to write a single-threaded and multithreaded client/server echo system. Finally, you successfully completed your course project by assembling your earlier work and implementing the network to fully realize your client/server chat program.

Now that you have completed this lesson, you should be able to:

� Define networking, IP addresses, the Domain Name System, and ports.

� Discuss the socket model and socket-to-socket communication.

� Explain the client/server model and how it relates to socket-to-socket communication.

� Write a single-threaded client/server echo system.

� Write a multithreaded client/server echo system.

Page 366: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

21-20 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Lesson 21 Review

1. What is networking? What is networking in Java?

_______________________________________________________________

_______________________________________________________________

2. What is an IP address?

_______________________________________________________________

_______________________________________________________________

3. What is DNS?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

4. What is a port?

_______________________________________________________________

_______________________________________________________________

5. What is TCP/IP?

_______________________________________________________________

_______________________________________________________________

6. What is the client/server model? How does it relate to the socket model?

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

_______________________________________________________________

Page 367: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Lesson 21: Networking in Java 21-21

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

7. In this lesson, you created a client/server chat system. How do the client and server compare to each other in terms of functionality?

_______________________________________________________________

_______________________________________________________________

Page 368: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

21-22 Java Programming Fundamentals

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 369: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Appendixes-1

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

22Appendixes Appendix A: Objectives and Locations*

Appendix B: Java Resources on the Web*

Appendix C: Works Consulted*

* Appendix found on Supplemental CD-ROM

Page 370: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Appendixes-2

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 371: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Glossary-1

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

23Glossary

<APPLET>—HTML 3.2 tag used to embed an applet.

abstract—A class or object that is incompletely defined, used to collect properties or behaviors.

Abstract Windowing Toolkit (AWT)— The GUI classes of Java.

abstraction—The consideration of an object in terms of its functionality and not its implementation details.

accessor—A method that reads a variable.

add—A method of Container used to add components.

addItemListener—One of a series of methods that register a listener object with its source; this method is always of the form addSomeListener.

ALIGN—Optional attribute of <APPLET>; specifies the position of the applet.

allocate—Java sets aside enough space in memory for a data structure as soon as it is adequately defined.

ALT—Optional attribute of <APPLET>; allows you to display a comment to a Java-disabled browser.

anonymous inner class—An inner class defined within the parentheses of the appropriate addItemListener method.

applet—A small Java program that must be run from a Web browser.

arithmetic operators—Operators that perform manipulation on numbers.

array—An ordered collection of values, referenced by an integer index, all having the same type.

ASCII —A standard means to represent characters as integers ranging from 0 to 127.

atomic process—A process that has no intermediate state.

bitwise operators—Operators that perform logical manipulation comparing and changing each bit.

Boolean expression—An expression that evaluates as either true or false; the result of a relational or logical operation.

BorderLayout—A Java layout manager that adds components in specified regions.

BoxLayout—A Java layout manager that adds components horizontally or vertically.

break statement—A statement that causes the current conditional or iterative statement to terminate.

bytecode—A platform-neutral file consisting of bytes that the JVM can execute.

callback—When an object refers back to a class to which it has gained reference.

casting—The process of converting values from one data type to another.

class—A type of container into which all Java code must be placed. Also, the template or blueprint for an object.

class member—A variable or method that exists only once for the class regardless of how many objects are created; designated by the keyword static.

class variable—A variable defined outside of any method using the keyword static. Class variables are available throughout the class.

CODE—Required attribute of <APPLET>, needed to embed an applet in an HTML page; specifies the name of the applet class.

code block—A sequence of statements contained in curly braces.

Page 372: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Glossary-2

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

CODEBASE—Optional attribute of <APPLET>; specifies a relative directory in which to save the applet class.

Color—A class of the AWT that represents colors.

concatenation—The act of adding Strings together.

constructor—A special method having the same name as its class; used to instantiate a class.

Container—An abstract, high-level component that offers JFrame and JPanel much of their functionality.

continue statement—A statement that terminates the current iteration of a loop.

cooperative multitasking—A system of multitasking in which one task must willingly yield to another task.

coupling—The level of interdependency between objects.

daemon thread—A thread designed to service user threads. Daemon threads terminate after the last user thread terminates.

dead—The state of a Java thread once it has been stopped or the run method has exited.

deadlock—A condition that occurs when two or more threads reach an impasse due to competition for object monitors.

default constructor—A constructor without parameters; Java assumes a default constructor until you define your own.

destroy—The last method called in the life cycle of an applet; should be used to release system resources.

do while loop—An iterative statement that checks a condition after executing a loop block once, then executes the loop block again if the condition evaluates to true.

Domain Name System (DNS)—A system that converts domain names into corresponding IP addresses.

dot notation—In Java, a reference used to access a member of an object.

drawRect—A method of the Graphics class that draws a rectangle.

encapsulation—The wrapping of variables and methods together; variables can only be accessed through the methods provided.

entry condition/ exit condition—Condition based on whether the Boolean expression is evaluated at the beginning or end of the loop.

error— An inoperable condition that can occur in a program and cause it to terminate.

event—An occurrence or happening.

event delegation model—The event handling model used in JDK 1.1 and SDK 1.2.

event object—The informational object Java creates in response to an event.

exception—An abnormal condition that occurs in a program.

explicit casting—Casting performed by explicitly declaring the more restrictive data type to which you intend to convert.

extends—The Java keyword that designates the class from which to derive.

File—A Java class abstracting the nature of a system file.

FlowLayout—A Java layout manager that adds components centered on each line, top to bottom, in a flowing manner similar to the layout of HTML pages.

Font—A class of the AWT that represents fonts.

for loop—An iterative statement that checks a condition and executes an iteration variable if the condition evaluates to true.

getParameter—A method of Applet used to obtain the name/value pairs sent by the HTML page.

glue—An invisible Swing component that expands to consume free space in a container.

Graphics—An abstract class used to get a graphics context of a component or image.

Page 373: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Glossary-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

graphics context—The workable representation of the Graphics class for a component or image.

GridLayout—A Java layout manager that adds components in a grid-like format.

handleEvent—The method most widely used in the JDK 1.0 to handle event processing.

ID—A way of distinguishing the type of event generated.

identifier— Another term for a variable, method or class name.

if statement—The basic conditional statement; chooses one path or the other.

ImageIcon—A high-level Swing class that facilitates the display of images; implements the Icon interface

immutable—Unable to be changed; a characteristic of Strings.

implicit casting—The form of casting that occurs automatically when data loss is not possible.

import—A statement that makes a package visible within a file.

index—A numeric reference to a specific element of an array; the only way to access elements of an array.

inheritance—In Java, creation of new classes by defining only the differences from existing classes.

init—The first method called in the life cycle of an applet; it resembles a constructor.

inner class—A class defined within the body of another class.

InputStream—The abstract class from which all other input byte streams are derived.

InputStreamReader—A utility stream that converts a byte stream into a character stream for input.

instance member—A variable or method unique for each object (instance of the class).

instantiation—The use of a class definition to create an object.

interface—Abstract methods and final variables that can be used by different classes. Also defines a data type.

Internet Protocol (IP) address—The numerical address assigned to a specific computer and used by the Internet to transfer information.

Java 2 Application Programming Interface (API)—The built-in functionality of Java.

Java Virtual Machine (JVM)— The artificial computer that runs Java programs.

JButton—A simple clickable Swing widget.

JComponent—A high-level Swing class from which many other components receive their core functionality.

JFileChooser—A Swing component used to retrieve the names of files.

JFrame—The fundamental Window in Java; it cannot be contained in another container.

JLabel—A Swing widget used to place text in relation to an icon.

JPanel—A lower-level Container used to hold other Containers; can also be used as a drawing surface.

JScrollBar—A Swing widget used to visually select a single value from a range.

JScrollPane—A Swing text-entry widget that adds scrolling functionality to other components.

JTextArea—A multiline text-entry widget in Swing

JTextField—A single-line text-entry widget in Swing.

label—An identifier that points to a specific line of the code, to which a loop can break or continue.

layout manager—An object used to control the positioning of components within a container.

length property—A characteristic of an array; the number of elements it contains.

life cycle—The life of an applet as controlled by the init, start, stop and destroy methods.

Page 374: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Glossary-4

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

listeners—Classes that listen for, and usually process, the events generated by an event source. Such classes will implement an appropriate listener interface.

literal— A representation of an actual value for a data type.

local variable—A variable defined inside a method. Local variables are not available from outside a method.

logical operators—Operators that allow you to combine two or more relational operators.

lower-level container—A Container that must be contained in another Container, such as a JPanel.

main thread—The user thread created by the JVM from which all other user threads are generated.

member—A general term for both methods and variables.

member inner class—An inner class defined at the same scope as a method or instance variable.

method—A procedural part of a class that contains executable Java statements.

method signature—The method name and parameter types; the return type is not included in the signature.

modal—A property designating that a component blocks its parent Component until proper response is received.

monitor—A control device for an object that limits thread access to the object's methods.

multiprocessing—The ability to execute multiple processes (applications) in parallel.

multitasking—The ability to perform more than one function simultaneously.

multithreading— The ability to execute multiple threads in parallel.

mutator—A method that modifies a variable.

nesting—The use of containers within containers to achieve sophisticated layouts.

networking—Communication among computers.

new—A keyword that signals the JVM to allocate space for an object.

new—The state of a Java thread once it has been instantiated.

no-arguments constructor—A constructor for a class having no parameters; the default constructor is an example.

not runnable—The state of a Java thread when it is removed from the runnable queue but is not dead.

object—A generic term for non-primitive data types; objects represent data and the operations on data. Also, an instance of a class, with unique data and operations.

OutputStream—The abstract class from which all other output byte streams are derived.

OutputStreamWriter—A utility stream that converts a character stream into a byte stream for output.

overloading—Two or more methods with the same name and different parameter types; they usually implement similar types of operations.

overridden method—A method in a derived class with the same method signature; replaces the superclass method for the subclass.

package—A collection of classes designated by the package keyword; Java stores the classes in a directory structure based on the package.

paint—An inherited method from Container that allows painting to the applet surface.

PaintComponent (Graphics g)—A method inherited from JComponent that is passed a reference to the graphics context of that component.

parameter—The mechanism for sending information to a method.

parameter tags—Optional name/value tags that send information to an applet from within the HTML page.

Page 375: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Glossary-5

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

pass by reference—A pointer to the data is passed to a method; changes made to the data by a method are also made to the original data. Although Java always uses pass by value, pass by reference is used for non-primitive data types because the value for a non-primitive type is a reference.

pass by value—A copy of the value of the variable is available to the method; changes to the copy do not affect the original value.

peer pattern—The process by which the JVM calls a platform-specific GUI component equivalent to the component supplied by the GUI; used by the Java AWT.

persistent—The ability to maintain a prior state.

polymorphism—Using one method name to invoke many different methods.

port—An integer from 0 to 65535 representing a particular path for information flow.

pre-emptive multitasking—A system of multitasking in which one task can pre-empt another task if it has a higher priority.

primitive data types—The basic data building blocks of the language; all the primitives consist of a single value.

private—Access modifier that is applied to the member only; restricts access to the class in which it is defined.

protected—Access modifier that allows the class to be seen by classes in the same package or subclasses in other packages.

public—Access modifier that allows the class or member to be seen by every part of the program.

Reader—The abstract class from which all other input character streams are derived.

reference—Java stores the location of a non-primitive type in the variable; the actual memory for the type exists at the pointed-to-memory location.

relational operators—Operators that compare values of variables; all evaluate to the boolean data type (false or true).

repaint—A method of Component that is used to indirectly call paintComponent for a graphics update.

run—The method that contains the body of a thread.

runnable—The state of a Java thread once it has been started.

Runnable interface—An interface that prototypes the run method, targeting it as a thread.

runtime exception—A set of possible conditions that can occur in a program and cause an illegal operation.

sandbox—The strict security restrictions placed on applets.

SecurityManager—A Java class used by browsers to set security restrictions on an applet.

Serializable interface—A Java interface that marks an object to be serialized.

serialization—The process of maintaining an object's state by converting it into a byte stream.

ServerSocket—A class in Java that represents the socket model for servers.

setColor—An overloaded method of the Graphics class that establishes the current color of the graphics context.

short-circuit operators—Operators that do not evaluate all the relational operations unless necessary.

signed applet—A digitally signed applet; if accepted by the user, security limitations are reduced.

Socket—A class in Java that represents the socket model for clients.

source—The Component that generates the event object.

start—The second method called in the life cycle of an applet. Also, the method that starts a thread by calling the run method.

stop—A method that works in conjunction with start; should be used to suspend resource-draining code.

Page 376: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Glossary-6

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

stream—A path of information from a source to a destination.

StringBuffer—A peer class to the String class; it is not immutable.

strongly typed—Term used to describe a language. Requiring that the programmer specify the kind of information that each variable can hold.

strut—An invisible Swing component that creates fixed-sized horizontal or vertical space in a container.

subclass—A class that inherits from a superclass.

super—The keyword used to refer to the superclass object; allows you to call a method defined in the superclass.

superclass—A class from which one or more classes are derived.

Swing—A GUI toolkit used by Java.

switch statement—A more complex conditional statement; chooses from multiple options.

synchronization—Controlling the flow of multiple, simultaneous threads.

synchronized—The keyword used to access an object's mon tor.

System.in—Java's version of standard input (usually the keyboard).

System.out—Java's version of standard output (usually the monitor).

this—A keyword that refers to the current object.

thread—Program code running in parallel with other program code within the same application.

thread racing—Competition between two or more threads for the same resource.

thread state—The current condition of a program thread.

top-level container—A Container that cannot be contained in another Container, such as a JFrame.

transient—A keyword used to mark members that will not be serialized.

Transmission Control Protocol/Internet Protocol (TCP/IP)—The set of networking protocols used for the Internet.

type—Identifies the kind of information that a variable can store.

user thread—A thread created by other user threads with the purpose of being controlled by the programmer.

while loop—An iterative statement that checks a condition and executes a loop block if the condition evaluates to true.

widget—A term used to refer to any interactive visual component of a GUI.

WIDTH/HEIGHT— Required attributes of <APPLET>, needed to embed an applet in an HTML page; determines the size of the applet.

WindowListener—One of many interfaces that allow an object to receive certain events.

wrapper class—A class that wraps around other stream classes to add functionality.

Writer—The abstract class from which all other output character streams are derived.

wrapper—A class that wraps around other stream classes to add functionality.

Writer —The abstract class from which all other output character streams are derived.

Page 377: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Index-1

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

24Index

<APPLET> tag, 16-6 <APPLET> tag attributes, 16-7 <APPLET> tag parameters, 16-6 abstract, 9-9 Abstract Windowing Toolkit (AWT), 11-3 abstraction, 6-9 accessor, 10-7 add (method), 11-23 addItemListener (method), 14-8 allocate, 5-3 anonymous inner class, 15-6 applet, 1-3 arithmetic (operator), 2-7 array, 5-3 array, initializing an, 5-3 array, passing to a method, 5-5 array, using an, 5-5 ASCII, 20-5 atomic process, 19-8 automatic casting, 2-10 AWT, 11-3 AWT 1.1, 11-4 bitwise (operator), 2-10 Boolean expression, 3-4 BorderLayout, 12-8 BoxLayout, 12-10 break (statement), 3-5 bytecode, 1-4 callback, 8-4 casting, 2-6 class, 1-3 class member, 6-7 class variable, 2-4 client, 21-7 Client (class), 21-16 client/server model (Java), 21-7 code block, 3-3 Color (class), 13-9 Color (object), 13-9 command line parameters, 5-8 comment, 1-5 compiler, 1-5 concatenation, 8-11 conditional statement, 3-4 Connection (class), 21-15 constructor, 8-4

constructor process, 8-8 constructors, callbacks and, 8-9 continue (statement), 3-8 cooperative multitasking, 18-3 coupling, 9-5 currentThread (method), 18-11 daemon thread, 18-4 data types, primitive, 2-3 dead, 18-11 deadlock, 19-16 default constructor, 8-5 destroy (method), 16-5 do while loop, 3-6 Domain Name System (DNS), 21-3, 21-4 dot notation, 6-6 drawRect (method), 13-8 EchoServer, 21-7 encapsulation, 10-7 error, 17-4 event, 14-3 event delegation model, 14-4 event object, 14-3 exception, 17-4 exceptions, catching, 17-6 exceptions, handling, 17-5 exceptions, ignoring, 17-6 exceptions, inheritance and, 17-11 exceptions, throwing to the calling method, 17-7 exceptions, user-defined, 17-8 explicit casting, 2-6 explicit exception, 17-5 extends (keyword), 7-5 File (class), 20-5 File class methods, 20-6 file I/O, 20-15 File object directories, 20-7 File object, instantiating a, 20-6 File object, working with a, 20-7 files, 20-5 FlowLayout, 12-6 Font (class), 13-10 for loop, 3-7 garbage collection, 5-7 getParameter (method), 16-8 glue, 12-12 Graphics (class), 13-3

Page 378: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Index-2

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

graphics context, 13-3 GridLayout, 12-7 handleEvent (method), 14-3 ID, 14-3 identifier, 2-4 if (conditional statement), 3-4 immutable, 8-11 implicit casting, 2-6 import (statement), 10-4 index, 5-3 inheritance, 7-4 inheritance, exceptions and, 17-11 init (method), 16-5 inner class, 15-4 InputStream (abstract class), 20-4 InputStreamReader, 20-13 instance member, 6-5 instance variable, 2-4 instantiation, 6-4 interface, 9-4 interface contents, 9-4 interface functions, 9-5 Internet Protocol (IP) address, 21-3 Internet Protocol version 4 (IPv4), 21-3 iteration variable, 3-7 iterative (loop) statement, 3-6 Java 2 Application Programming Interface

(API), 10-6 Java 2 Software Development Kit (SDK), 1-4 Java Runtime Environment (JRE), 1-5 Java Virtual Machine (JVM), 1-3 JavaBeans, 11-25 JDK 1.0 event handling, 14-3 JFileChooser, 11-18 JFrame, 11-21 JPanel, 11-22 JRE, 1-5 JScrollPane, 11-16 JVM, 1-3 label, 3-8 layout manager, 12-5 layouts, combining, 12-14 length property, 5-5 life cycle, applet, 16-5 listeners, 14-4 literal, 4-5 local variable, 2-4 logical (operator), 2-9 loop (iterative) statement, 3-6 lower-level (Swing container), 11-20 main thread, 18-4 member, 4-4 member inner class, 15-6 memory leak, 6-10 method, 1-3, 4-4 method signature, 4-7

method, calling a, 4-5 method, overriding a, 7-6 modal, 11-18 Model-View-Controller (MVC), 11-5 monitor, 19-4 multiprocessing, 18-3 multitasking, 18-3 multithreading, 18-3 mutator, 10-7 MVC, 11-5 namespace conflict, 8-6 nested loop, 3-7 networking, 21-3 networking classes, 21-6 new (keyword), 6-6 new state, 18-10 no-arguments constructor, 8-7 not runnable, 18-10 object, 5-4 object encapsulation, 10-8 object reference, 6-10 object serialization, 20-17 object-oriented programming, 6-4 operators, 2-7 OutputStream (abstract class), 20-4 OutputStreamWriter, 20-13 overloading, 4-7 package, 10-4 package access level, 10-5 paint (method), 16-5 paintComponent (Graphics g), 13-3 parameter, 4-5 parameter tag, 16-7 pass by value, 4-6 passed by reference, 5-6 peer pattern, 11-3 persistence, 20-17 polymorphism, 9-6 port, 21-4 pre-emptive multitasking, 18-3 primitive computer (producer thread), 19-9 primitive printer (consumer thread), 19-9 primitives (primitive data types), 2-3 private access level, 10-5 protected access level, 10-5 public access level, 10-5 race condition, 19-5 Reader (class), 20-4 reference, 5-3 relational (operator), 2-8 repaint (method), 13-8 return (statement), 4-4 run (method), 18-5 runnable, 18-10 Runnable interface, 18-7 runtime exception, 17-4

Page 379: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Index-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

sandbox, 16-9 SDK, 1-4 SDK 1.2 event handling, 14-4 SecurityManager (class), 16-9 Serializable interface, 20-17 serialization, 20-17 server, 21-10 ServerSocket (class), 21-7 setColor (method), 13-9 setName (method), 18-12 setPriority (method), 18-13 short-circuit (logical operator), 2-9 signed applet, 16-9 sleep (method), 18-12 socket, 21-4 Socket (class), 21-7 source, 14-3 start (method), 16-5, 18-6 stop (method), 16-5 stream, 20-3 stream classes, 20-9 String (class), 8-10 String, methods of, 8-12 StringBuffer (class), 8-13 strongly typed (language), 2-3 strut, 12-11 subclass, 7-5 super (keyword), 7-5, 8-7 superclass, 7-5 Swing, 11-4

Swing components, 11-6 Swing containers, 11-20 switch (conditional statement), 3-5 synchronization, 19-3 synchronized (keyword), 19-4 System.in, 20-11 System.out, 20-11 this (keyword), 8-6 thread, 18-3 thread racing, 19-3 thread state, 18-10 thread, resuming a, 19-15 thread, stopping a, 19-13 thread, suspending a, 19-14 top-level (Swing container), 11-20 transient (keyword), 20-21 Transmission Control Protocol/Internet Protocol

(TCP/IP), 21-6 type, 6-6 user thread, 18-4 variable values, default, 2-5 variables, declaring, 2-4 while loop, 3-6 widget, 11-7 WindowListener (interface), 14-6 wrapper class, 20-14 wrapper streams, 20-14 Writer (class), 20-4 yield (method), 18-14

Page 380: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Index-4

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 381: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Supplemental CD-ROM Contents-1

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

25Supplemental CD-ROM

Contents The Java Programming Fundamentals supplemental CD-ROM contains the following files needed to complete the course labs:

� Java_Prg_Fnd_LearningCenter_Student _CD � Answers

� Appendix

� Handouts � Lab Files

����Answers ANSWERS_Activity.pdf

ANSWERS_CourseAssessment.pdf

ANSWERS_Lab.pdf

ANSWERS_OptionalLab.pdf

ANSWERS_PreAssessment.pdf

ANSWERS_Quiz.pdf

ANSWERS_Review.pdf

����Appendix Appendix_A.pdf Appendix_B.pdf Appendix_C.pdf

����Handouts HANDOUTS_Activity.pdf

HANDOUTS_CourseAssessment.pdf

HANDOUTS_OptionalLab.pdf HANDOUTS_Quiz.pdf

����Lab Files � Completed_Labs � Student_Files

����Lab Files\Completed_Labs � Lesson_01

� Lesson_02

� Lesson_03

� Lesson_04

� Lesson_05

� Lesson_06

� Lesson_07

� Lesson_08

� Lesson_09

� Lesson_10

� Lesson_11

� Lesson_12

� Lesson_13

� Lesson_14

� Lesson_15

� Lesson_16

� Lesson_17

� Lesson_18

� Lesson_19

� Lesson_20

� Lesson_21

���� Lab Files\Completed_Labs\Lesson_01 � Lab 1-1 � Optional Lab 1-1

����Lab Files\Completed_Labs\Lesson_02 � Lab 2-1 � Optional Lab 2-1

����Lab Files\Completed_Labs\Lesson_03 � Lab 3-1 � Optional Lab 3-1

Page 382: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Supplemental CD-ROM Contents-2

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

����Lab Files\Completed_Labs\Lesson_04 � Lab 4-1 � Optional Lab 4-1

����Lab Files\Completed_Labs\Lesson_05 � Lab 5-1 � Optional Lab 5-1

����Lab Files\Completed_Labs\Lesson_06 � Lab 6-1 � Optional Lab 6-1

����Lab Files\Completed_Labs\Lesson_07 � Lab 7-1 � Optional Lab 7-1

����Lab Files\Completed_Labs\Lesson_07\Lab 7-1 � Optional Step 2

����Lab Files\Completed_Labs\Lesson_08 � Lab 8-1 � Optional Lab 8-1

����Lab Files\Completed_Labs\Lesson_08\Optional Lab 8-1 � Optional

����Lab Files\Completed_Labs\Lesson_09 � Lab 9-1 � Optional Lab 9-1

����Lab Files\Completed_Labs\Lesson_10 � Lab 10-1 � Optional Lab 10-1

����Lab Files\Completed_Labs\Lesson_10\Optional Lab 10-1 � employees

����Lab Files\Completed_Labs\Lesson_11 � Lab 11-1 � Optional Lab 11-1

����Lab Files\Completed_Labs\Lesson_12 � Lab 12-1 � Optional Lab 12-1

����Lab Files\Completed_Labs\Lesson_13 � Lab 13-1 � Optional Lab 13-1

����Lab Files\Completed_Labs\Lesson_14 � Lab 14-1 � Optional Lab 14-1

����Lab Files\Completed_Labs\Lesson_15 � Lab 15-1 � Optional Lab 15-1

����Lab Files\Completed_Labs\Lesson_16 � Lab 16-1 � Optional Lab 16-1

Page 383: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Supplemental CD-ROM Contents-3

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

����Lab Files\Completed_Labs\Lesson_17 � Optional Lab 17-1

����Lab Files\Completed_Labs\Lesson_18 � Lab 18-1 � Optional Lab 18-1

����Lab Files\Completed_Labs\Lesson_19 � Lab 19-1 � Optional Lab 19-1

����Lab Files\Completed_Labs\Lesson_20 � Lab 20-1 � Optional Lab 20-1

����Lab Files\Completed_Labs\Lesson_21 � Lab 21-1 � Optional Lab 21-1

����Lab Files\Student_Files � Lesson 21

����Lab Files\Student_Files\Lesson 21 � Lab 21-1

Page 384: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Supplemental CD-ROM Contents-4

© 2009 ProsoftTraining All Rights Reserved. Version 6.07

Page 385: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

By opening this package, you agree to be bound by t he following agreement:

Some of the material on the accompanying disk may b e copyrighted, in which case all rights are reserved by the copyright holder. You are licensed to use the material copyrighted by the publisher and its licensors on a single computer. Y ou may copy and/or modify the disk content as needed to use it on a single computer. Copying t he disk and its content for any other purpose is a violation of the United States copyright laws.

This disk and its content are provided as is, witho ut warranty of any kind, either expressed or implied, including but not limited to the implied w arranties of merchantability and fitness for a particular purpose. The publisher assumes no liabil ity for alleged or actual damages arising from the use of this disk (including but not limite d to damages due to viruses).

Page 386: Java Programming Fundamentals: Learning Center Student · PDF fileJava Programming Fundamentals: Learning Center Student Guide CIW Java Programming Series CCL05-CEJPRF-PR-203 • CIWv4

Blank Text For The Docutech!

www.ciwcertified.com